diff --git a/.gitattributes b/.gitattributes index b85fd2886d47ab925e85d54927703a51bb268691..7f5ae2201d5e0641657f4c54c38b2b5ca693d672 100644 --- a/.gitattributes +++ b/.gitattributes @@ -194,3 +194,145 @@ Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_linalg_p Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_interpolative.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_update.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/bin/python filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/bin/python3 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/bin/python3.10 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/dataarray.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/_aggregations.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/dataset.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-c55a5f7a.so.1.1.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libpng16-d00bd151.so.16.49.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/liblcms2-cc10e42f.so.2.0.17 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/liblzma-64b7ab39.so.5.8.1 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libopenjp2-56811f71.so.2.5.3 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libjpeg-8a13c6e0.so.62.4.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libharfbuzz-fe5b8f8d.so.0.61121.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libtiff-13a02c81.so.6.1.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libxcb-64009ff3.so.1.1.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libfreetype-083ff72c.so.6.20.2 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libwebp-5f0275c0.so.7.1.10 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libavif-01e67780.so.16.3.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_refs/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/decompositions.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libgomp.so.1 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libc10_cuda.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libc10.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_python.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/linalg/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/bin/protoc-3.13.0.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/overrides.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_tensor_docs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_meta_registrations.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda_linalg.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/nn/__pycache__/functional.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufile/lib/libcufile.so.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcheckpoint.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libpcsamplingutil.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.8 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.alt.so.12.8 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cublas/lib/libnvblas.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn.so.9 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_graph.so.9 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_cnn.so.9 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fast_histogram/_histogram_core.abi3.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_host.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_engines_runtime_compiled.so.9 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_runtime/lib/libcudart.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufft/lib/libcufftw.so.11 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_heuristic.so.9 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/nvjitlink/lib/libnvJitLink.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.alt.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/curand/lib/libcurand.so.10 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops.so.9 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cublas/lib/libcublas.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/functorch/_C.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolverMg.so.11 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/yaml/_yaml.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolver.so.11 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/FileCheck filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/instrumentation/libGPUInstrumentationTestLib.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/language/__pycache__/core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_adv.so.9 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/instrumentation/libPrintLoadStoreMemSpaces.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/_C/libproton.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/cuobjdump filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/libdevice.10.bc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcheckpoint.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libpcsamplingutil.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/cuda_bf16.h filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.1 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/cuda_fp16.hpp filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufft/lib/libcufft.so.11 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/backend_bases.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/patches.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/widgets.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/figure.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/backends/_tkagg.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/backends/_backend_agg.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/amd/lib/ockl.bc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host_static.a filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/amd/lib/ocml.bc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti_static.a filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/ft2font.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/colors.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/_cm_listed.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/pyplot.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_axes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99-934c22de.so.0.0.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1-0352e75f.so.5.0.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/nccl/lib/libnccl.so.2 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libscipy_openblas-68440149.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_engines_precompiled.so.9 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusparselt/lib/libcusparseLt.so.0 filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/resultproxy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/collections.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/processors.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/util.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/Scripts_Climate_to_LAI/.venv/bin/python b/Scripts_Climate_to_LAI/.venv/bin/python new file mode 100644 index 0000000000000000000000000000000000000000..70f41baa9a6e156c35b7f0c5d15a5bea8ce5e22f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/bin/python @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6bca2b84e73c7775a0dd5e6a76899cfe4ee62863d7c8f88513811d1fda23f49 +size 5937704 diff --git a/Scripts_Climate_to_LAI/.venv/bin/python3 b/Scripts_Climate_to_LAI/.venv/bin/python3 new file mode 100644 index 0000000000000000000000000000000000000000..70f41baa9a6e156c35b7f0c5d15a5bea8ce5e22f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/bin/python3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6bca2b84e73c7775a0dd5e6a76899cfe4ee62863d7c8f88513811d1fda23f49 +size 5937704 diff --git a/Scripts_Climate_to_LAI/.venv/bin/python3.10 b/Scripts_Climate_to_LAI/.venv/bin/python3.10 new file mode 100644 index 0000000000000000000000000000000000000000..70f41baa9a6e156c35b7f0c5d15a5bea8ce5e22f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/bin/python3.10 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6bca2b84e73c7775a0dd5e6a76899cfe4ee62863d7c8f88513811d1fda23f49 +size 5937704 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/_virtualenv.pth b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/_virtualenv.pth new file mode 100644 index 0000000000000000000000000000000000000000..74d2eb6578fd774c6d8e324cd2fad5efb8beb747 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/_virtualenv.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69ac3d8f27e679c81b94ab30b3b56e9cd138219b1ba94a1fa3606d5a76a1433d +size 18 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0dfff539343c939cef072609c86e78d0f5dcf3b5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f22b7f307c1f94161cda346e6b9295057635e2064eeccb87e8602e4159bc57e1 +size 854312 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..ff62a934a5009337271c60501278a7a34913a20b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3ea52e7b6e968de0d884df1288193596fa95b803db4f92a18279a7398004475 +size 156400 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/distutils-precedence.pth b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/distutils-precedence.pth new file mode 100644 index 0000000000000000000000000000000000000000..c659194195f07bd6f19b5522515551309af14a3d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/distutils-precedence.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2638ce9e2500e572a5e0de7faed6661eb569d1b696fcba07b0dd223da5f5d224 +size 151 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fast_histogram/_histogram_core.abi3.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fast_histogram/_histogram_core.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..ae24a9a116df852b8534144b97c171703e9e4b7b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fast_histogram/_histogram_core.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62f63264c9ca82fed1076403f8e754f9389cb74cf0b3845892c6703717468417 +size 131360 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/functorch/_C.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/functorch/_C.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d066fbd9126d82b5c7888c5cfca157f1368eaa74 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/functorch/_C.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:deb34f37b48b89449b5f3bc79a59b5f09be7b8604f436af1e66c588acc03184a +size 314544 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np16.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np16.gz new file mode 100644 index 0000000000000000000000000000000000000000..fedefdd304054a85fa995801885f997ca8e1a44f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np16.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:418447e90d83486568ae3092a960b18d358230e24ac9ec38365daa99f415bd0f +size 769 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np17.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np17.gz new file mode 100644 index 0000000000000000000000000000000000000000..3fd32f71887ddd0c94d06c8a77afccc322fed583 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np17.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1f4e8cccfca94f25ae744d1f050b0734f663263ba38ed0642181404b348b17b +size 757 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py33_np18.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py33_np18.gz new file mode 100644 index 0000000000000000000000000000000000000000..7cd1fcc9dc7a04d7ac251d3b1bbf973609b947b8 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py33_np18.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9e215780f978ce693e48110ead23652e1c6de1c2189172232690198f7088788 +size 792 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py34_np19.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py34_np19.gz new file mode 100644 index 0000000000000000000000000000000000000000..7cc0ad77a184883b0268bffd1e2f3d195ae99f6b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py34_np19.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1abdb3ff5b555831f51f7ff00951e66a49277fc2aa787293f18cf8775be65023 +size 794 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py35_np19.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py35_np19.gz new file mode 100644 index 0000000000000000000000000000000000000000..878decdcad534f6d2cdd14a487c207f8c6133261 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py35_np19.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a56c3fc6e0db3a4102aaed4a19fd4e154eecd956f30b6bf9179897844ed3c01e +size 790 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl new file mode 100644 index 0000000000000000000000000000000000000000..38202b72d880ff53255dbb86eccd73bdb6224c74 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89c4508e3dfbe01f801e4e739f1aded13f685941e89281c8050f0ca8aa3c97e5 +size 986 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..77ea56324322ed8657967221aad47bc0063a12fc --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a18415232322531c918164ae04148ebc258acd3a00fa4529728416755e14a15e +size 997 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.xz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.xz new file mode 100644 index 0000000000000000000000000000000000000000..7812497bc95e5894c8e880736bfb06aa22bb2fae --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.xz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efb146d450c6d061d06affb56f17384e7f64cbab9b516fcc6c4d3f8869b3e707 +size 712 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl new file mode 100644 index 0000000000000000000000000000000000000000..d6cf697b1c1c752d4d8a78d702a70042ad047ce9 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e064c2eecfdc58d552844467da7bd56eca596098322bfd266a7e1312abdd5735 +size 1068 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..317981559c4a9987aa099efeb68e4359c08d71ec --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e86d6f6ecfe2626cf691827ac38a81d64ec3ebb527c5432eb344b8496781b45a +size 1000 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.xz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.xz new file mode 100644 index 0000000000000000000000000000000000000000..826c9ba7b9579a988f8f1718219bbc41fd1ad756 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.xz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e9a63dcc7df38ab0a1137a9b44b436b13cebfa300eb19dba4ae4bce50d0fa81 +size 752 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl new file mode 100644 index 0000000000000000000000000000000000000000..f22c25bdb59d15a3771104dff6dfebe564e98add --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cbe456f5b91f5a3cb8e386838f276c30335432a351426686187761d5c34168b +size 1068 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..80818a8baa1e2481b62bed06bb2b95f4a614cc3a --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f2af67ea667c1f5315ddcab06bfa447005863c1c0fd88bb7e04a0b8acb9a54b +size 1021 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.xz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.xz new file mode 100644 index 0000000000000000000000000000000000000000..1cd5660dd8d32121e8dd7b40534187add5981639 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.xz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04d7e68907e978b56975f9309492b8849e42a60974beb795c9e93273977f3cd3 +size 752 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl new file mode 100644 index 0000000000000000000000000000000000000000..360af38dc3a9bde47e3b18b144dc1c5257e7daca --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97b9ef2e896104321d3c5ce73b3de504788c38f04f08c8b56d7a29d6d1520a96 +size 1068 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..06e8395437874c25cfdf6a6783eab12a6c178f90 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6a1a9b884be654e2e3fc9a48251ecf0c6920e255c3f2ee5dd71d8252a694606 +size 1005 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz new file mode 100644 index 0000000000000000000000000000000000000000..cec2871b09ae347e07c81eb55e7979300748ccd1 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02cf30d8b196c303662b2dd035d2a58caeb762ae3a82345ffd1274961e7f5aa0 +size 752 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_compressed_pickle_py36_np111.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_compressed_pickle_py36_np111.gz new file mode 100644 index 0000000000000000000000000000000000000000..f2e65e202609648f0a5464ae5b78b9f9fba8dd6e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_compressed_pickle_py36_np111.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d56ae75c3a83a0d10f60e657d50e56af6e3addbf2f555e9fc385a6e52e1b32de +size 800 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl new file mode 100644 index 0000000000000000000000000000000000000000..4dda21d9ad4ce279b8474ecce9697e3290e96bfa --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e6b0e171782d5fd5a61d1844dc946eb27c5f6b2e8075d436b23808433142ebc +size 1068 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..895dd324d574d9b2298833317a76f3794209bbb3 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc8db259be742ca2ff36067277f5e4a03e6d78883ddee238da65a7c7d79ef804 +size 991 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.xz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.xz new file mode 100644 index 0000000000000000000000000000000000000000..c7607dcdb2b09e7a50acc3239cc585974e7a09e6 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.xz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd787f35b3197418d8c7bca77c9dc5ca47b6f22cd24524b3ccd074cf90f893d6 +size 752 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.8.4_compressed_pickle_py27_np17.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.8.4_compressed_pickle_py27_np17.gz new file mode 100644 index 0000000000000000000000000000000000000000..fc4e28719d5acc118ac1d8bd8cdd15227eef25ba --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.8.4_compressed_pickle_py27_np17.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a9f994fb8baa63e689f681ba6db33bbb45aaf32693a61c9ebb50a3a608f40c8 +size 659 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np16.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np16.gz new file mode 100644 index 0000000000000000000000000000000000000000..1238376dd6ac2e166bf56f263862afe56b866da3 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np16.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34bb43aefa365c81f42af51402f84ea8c7a85c48c65b422e4e4fe8b2ee57883c +size 658 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np17.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np17.gz new file mode 100644 index 0000000000000000000000000000000000000000..1238376dd6ac2e166bf56f263862afe56b866da3 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np17.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34bb43aefa365c81f42af51402f84ea8c7a85c48c65b422e4e4fe8b2ee57883c +size 658 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py34_np19.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py34_np19.gz new file mode 100644 index 0000000000000000000000000000000000000000..0720a70aee276c37f9457817922ae60b67600d47 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py34_np19.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f33bd8a21a41b729b05dac5deeb0e868f218a092b0e3fe5988094cf167217f6 +size 673 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz new file mode 100644 index 0000000000000000000000000000000000000000..0720a70aee276c37f9457817922ae60b67600d47 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f33bd8a21a41b729b05dac5deeb0e868f218a092b0e3fe5988094cf167217f6 +size 673 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl new file mode 100644 index 0000000000000000000000000000000000000000..f7ca0addc6d032e93d0b530a2b42a583fb0d4b81 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9da8a3764db121e29d21ade67c9c3426598e76d88deae44cd7238983af8cef73 +size 670 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_01.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_01.npy new file mode 100644 index 0000000000000000000000000000000000000000..15574a4193ad4ad724b2b8053c701a82efa78fd5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_01.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_02.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_02.npy new file mode 100644 index 0000000000000000000000000000000000000000..f00f08fbeeda280fa3ce00069c313c5412a33eca --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_02.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_03.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_03.npy new file mode 100644 index 0000000000000000000000000000000000000000..ccc84c361de2569ed5cb91967f9063efcd84dd14 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_03.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0c45ae2a289841cbeba2443b7ebaa3b31c0a9e9dcc73294aca5729da0092405 +size 236 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_04.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_04.npy new file mode 100644 index 0000000000000000000000000000000000000000..e9b5e77c73268dfff541b576126f06fc6fed3d59 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_04.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05 +size 104 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl new file mode 100644 index 0000000000000000000000000000000000000000..976cba8c28be9a3dd0075efe5a6b3ce704319161 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f29d7f1d2ceca07f10df172c0e826ef08163a14b12c6ef3fa80ec53a5fcdc3c +size 670 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_01.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_01.npy new file mode 100644 index 0000000000000000000000000000000000000000..15574a4193ad4ad724b2b8053c701a82efa78fd5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_01.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_02.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_02.npy new file mode 100644 index 0000000000000000000000000000000000000000..f00f08fbeeda280fa3ce00069c313c5412a33eca --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_02.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_03.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_03.npy new file mode 100644 index 0000000000000000000000000000000000000000..ccc84c361de2569ed5cb91967f9063efcd84dd14 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_03.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0c45ae2a289841cbeba2443b7ebaa3b31c0a9e9dcc73294aca5729da0092405 +size 236 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_04.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_04.npy new file mode 100644 index 0000000000000000000000000000000000000000..e9b5e77c73268dfff541b576126f06fc6fed3d59 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_04.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05 +size 104 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl new file mode 100644 index 0000000000000000000000000000000000000000..e739b6d035cdf110063dbb8b2cdceb116e187019 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3d4cbc690d3ce9e5323a714ea546f32c01ab1710285c420184f6cdf4b26fc25 +size 691 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_01.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_01.npy new file mode 100644 index 0000000000000000000000000000000000000000..15574a4193ad4ad724b2b8053c701a82efa78fd5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_01.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_02.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_02.npy new file mode 100644 index 0000000000000000000000000000000000000000..f00f08fbeeda280fa3ce00069c313c5412a33eca --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_02.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_03.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_03.npy new file mode 100644 index 0000000000000000000000000000000000000000..73976395be90d4b2b2d955c79a90721e16cebc82 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_03.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ede9a64a52b25d7db30950956c978ec0b3932b7d14acd5abc63216e64babde7 +size 307 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_04.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_04.npy new file mode 100644 index 0000000000000000000000000000000000000000..e9b5e77c73268dfff541b576126f06fc6fed3d59 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_04.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05 +size 104 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl new file mode 100644 index 0000000000000000000000000000000000000000..19b2b0b8ee910063dcc1b24a87b1f387604c3706 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a538100e6ae94b16f2ab0f7d92d4d7e7a622be2dfcc0f6b0b73b623bc513ae2 +size 691 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_01.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_01.npy new file mode 100644 index 0000000000000000000000000000000000000000..15574a4193ad4ad724b2b8053c701a82efa78fd5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_01.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_02.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_02.npy new file mode 100644 index 0000000000000000000000000000000000000000..f00f08fbeeda280fa3ce00069c313c5412a33eca --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_02.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy new file mode 100644 index 0000000000000000000000000000000000000000..73976395be90d4b2b2d955c79a90721e16cebc82 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ede9a64a52b25d7db30950956c978ec0b3932b7d14acd5abc63216e64babde7 +size 307 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_04.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_04.npy new file mode 100644 index 0000000000000000000000000000000000000000..e9b5e77c73268dfff541b576126f06fc6fed3d59 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_04.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05 +size 104 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl new file mode 100644 index 0000000000000000000000000000000000000000..93417ab8e94e4542a24211ad514948f9d1b80a3a --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59f0d522a29c333ce1d60480b2121fcc1a08a5d2dd650b86efdc987f991fa4ea +size 691 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy new file mode 100644 index 0000000000000000000000000000000000000000..15574a4193ad4ad724b2b8053c701a82efa78fd5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy new file mode 100644 index 0000000000000000000000000000000000000000..f00f08fbeeda280fa3ce00069c313c5412a33eca --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1 +size 120 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_03.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_03.npy new file mode 100644 index 0000000000000000000000000000000000000000..73976395be90d4b2b2d955c79a90721e16cebc82 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_03.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ede9a64a52b25d7db30950956c978ec0b3932b7d14acd5abc63216e64babde7 +size 307 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_04.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_04.npy new file mode 100644 index 0000000000000000000000000000000000000000..e9b5e77c73268dfff541b576126f06fc6fed3d59 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_04.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05 +size 104 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz new file mode 100644 index 0000000000000000000000000000000000000000..e3125fe0fd4709dbd0067e67a06a3f24073934ad --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f2361f589b31d2863627edcb96612280ae5c0a59c9496d89dab7de493670f93b +size 802 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/_cm_listed.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/_cm_listed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d149e1ed9b530d2b76dc2827ab68da543567a9f5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/_cm_listed.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c3ab91c8b07b9fabfdd1806651bdee3e136bdff29dd5586e413e2a6bdd17658 +size 128846 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/backend_bases.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/backend_bases.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5426c2d4b4263aed39b66c3826a613deccec2adf --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/backend_bases.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9556814dd43fe734a76a477e341b95c6fe888571e781920c085e42cde79eeb9a +size 117397 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/colors.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/colors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24a96d84cf045b5a927d0ce68a754bd18e609333 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/colors.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37f2db4880be7e614eda04c2a50bebb11237c9cabfd4f1ba29f156d3ddb8aadd +size 118920 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/figure.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/figure.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87f609e5debae638a69ab6007dc50e607e2d8a8e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/figure.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:341504692e7a84decc4a72e422aa804ac788d32564c1587fc54b641b2a3bf5e0 +size 119745 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/patches.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/patches.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51cd2ffe1697b71c36997712d745c6e14c4e3bbe --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/patches.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b16d3c6e09e2caebce5c1d064e311040f07903e4aa528c8f968d273a47e4f60 +size 141950 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/pyplot.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/pyplot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b98fe1c56fdda5fc37b1c632d1d5ad09f50b7ad1 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/pyplot.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a367445c2b2263e4a2acaf4d20fb6b3fad11186462f00b9ca33ad1a632c59cc5 +size 121138 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/widgets.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/widgets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf1346c460d4e5ab4c6155494540ed42fbf21d20 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/__pycache__/widgets.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00aeceb8b1d4ed95146b33e7e6b9844bf93f028354fa15f257d4f298f0e99f03 +size 120892 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..805bac8defca7909bd4c111543e7a062f00e1eb0 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8ae1d3c9dc089dc55cdc22ad377e8858d4df2571739619631d3dd5958295faf +size 267216 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9a72a90c96ba06fd4e2e811a66a659e09d22f601 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2b39a3bf71dfaa9a1ce63c651402c550e6362c753b846acfb5e06cf3f8e0ad7 +size 586232 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9bfabd07809265bdf285d8dd8d970f72c10cc4db --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62b043f9c05752b89e1857c5a49f55bd5175e973f13a8ce7c6c77a9d27ca89cd +size 506808 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..09ad377170cdca4f6c49db03d374197dfbe66293 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:133734177165cddec9cd6b26609c4aec7b0b1da9ba1c0910c5046a773fc447a2 +size 764784 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7b6cd1c3d0d4ddabccaaea50616c2fd551f52b41 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9979cbccd0ea20c3cdcd791d41e9477a5f0131b52187c6cd09557a7f395f793 +size 441352 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_axes.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_axes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33716192623c83d79413d79221f37d81b8294e2f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_axes.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:676f701d230277f2821924319f5f14bd47bd5dc3dea2079ccd269dff83dfad28 +size 275792 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_base.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfdda3eaf11987605829e2c3dace5a72a24c074a --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_base.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8eae599a692bc95386df6fdd2f90984332c139a17fed1c31c7c1eb2d2dc8d0c7 +size 150279 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/backends/_backend_agg.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/backends/_backend_agg.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6c3451fbf572ed785789c5982f6cce4c60a337c1 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/backends/_backend_agg.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8da7a5e5a876488018eb1c080c00ea1b1e9cfaf09d2cd7ff849f2ef1621a14d3 +size 771424 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/backends/_tkagg.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/backends/_tkagg.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1a9aa807145ff677f72e9e635615e87622180ce9 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/backends/_tkagg.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4492c979edc78c470da076d0b3852cb287097de4db2d284bb0c0269b792408f +size 298400 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/ft2font.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/ft2font.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bf39a5095d00c1e2072028d5e1202bd2335b04f2 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/ft2font.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e879629431d847346995ac5df1eb6e839772f1712e878e0e59f2c4349cde3511 +size 1438856 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..39699bd84ae17507955ce571caa859ad14997f4e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b184b89e3c1075f22f6b71575b6fc20d4972b3cfd3b23322ca6fd596dcaef167 +size 704128 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf new file mode 100644 index 0000000000000000000000000000000000000000..cfd64ecefe8e5cdf2a0ea7d128019650a68ee682 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6edf0283160186af451cbee71e7b845f2e4cabf264bb992ce668c83c25465e6f +size 641720 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf new file mode 100644 index 0000000000000000000000000000000000000000..4ddf1fabb8648ac811ba05df9980121ec6a36452 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccdf74b350f11fd3dd5774de50e5e6346a1a5da1f5b7d5fb83590665e97a5213 +size 633840 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf new file mode 100644 index 0000000000000000000000000000000000000000..f47aa8cffd396d3ac221ad7a2a518bc9a554c9ce --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fdf69cabf06049ea70a00b5919340e2ce1e6d02b0cc3c4b44fb6801bd1e0d22 +size 756072 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..fb4675de56d8c2b2b09734578191896c7bf6948e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:baada9a5172fe20886251aff0433fc38461912d5daf07287e7bee56620a8da96 +size 331536 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ee85d0dc6915489b236e932ab89838b200443aba --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a69081c15c76c827e0a27a5a7f5c74b6135c843499955495ffa8c20d3a98288b +size 253116 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf new file mode 100644 index 0000000000000000000000000000000000000000..ba2147393770bbb669b1a6c735190f3cf6e732a8 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28052813f7a709fc89f52d192dc995ef4f0fdc5c3d7b73a49d6849b1916d0cd0 +size 251472 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono.ttf new file mode 100644 index 0000000000000000000000000000000000000000..60f42148ea53bf551fc77faef9d6382ff0efcb16 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:602ec86b8948cfcd956482fe64f94c36c867770149ef2f791d4613f443bcecb3 +size 340240 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..0137479cb3e30823976d9137d9e75ed8e225c57f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3753f2ed6bc673f15846dc45addbeb3b9c872f32fb18fd53a21f1bef1ed7676 +size 355692 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b89793b3fe00a3510c0a22b54d9ee7735e5e0803 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d93efec7a9d2e826768d1a2ee95b95870e15e29599a84f3484af1de1cec2e181 +size 347064 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..c1a70e8374879a0c04e370eb5c57861c4fd5abce --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e7994fbc54fa10ce3352a42d548fadd7d9cadb69cb1109bc9d960f6dac57f04 +size 345612 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif.ttf new file mode 100644 index 0000000000000000000000000000000000000000..73a4204e08a49a83ab7336cb55add8b32200ae24 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:107244956e9962b9e96faccdc551825e0ae0898ae13737133e1b921a2fd35ffa +size 379740 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf new file mode 100644 index 0000000000000000000000000000000000000000..cbf159757c5c0a47f1d8f2b984f0c20f52b7e25b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:167378031e2dddc6216d67819c9260e9a06ffc4c478e4e23cb98a6fd44b183c2 +size 448228 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf new file mode 100644 index 0000000000000000000000000000000000000000..64ca51419ec522ee78c91e6f36f57fdb3bde290b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8533dc7083fa346bda1933d60ea4a83b67d0945bceaf1b3541f82b4a0e2c6a0 +size 237360 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf new file mode 100644 index 0000000000000000000000000000000000000000..585e03c626a96775f018e690fc6e10f6cd3e4047 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98788fd4ba48dfbb2bd026c0e20a247a8b06c7372879628b7a6bb0d5bb09736c +size 181152 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf new file mode 100644 index 0000000000000000000000000000000000000000..67ce0a807f6ae1dc2b4f7b863ce99620d29e6cb7 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6cfcb333d22b7c3c623bdfd40174f14c85c3d6731ca6166c1edc80140eae8527 +size 175040 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/back.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/back.png new file mode 100644 index 0000000000000000000000000000000000000000..55f9825cb8f877b184933e56771c3c8ac2e43dae --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/back.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1387467f81a7cf5c49d6fdad33280757460d4204a1ade0de540a5a31bfbbe265 +size 380 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/back_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/back_large.png new file mode 100644 index 0000000000000000000000000000000000000000..507c4abbd0d01f9b5cafe4c116d07342707bea4d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/back_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f40ea151241eb3385838d13866e1f792f388b4cd097c356eead91fae89826ec4 +size 620 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/filesave.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/filesave.png new file mode 100644 index 0000000000000000000000000000000000000000..005d211bb326baf22069479767b0234de4b3ffce --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/filesave.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6fb72db9caccfc5da61be0f271379d1bf6bfcb8a47931dc5fb333b975f062e19 +size 458 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/filesave_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/filesave_large.png new file mode 100644 index 0000000000000000000000000000000000000000..2cce9e38a514ceaf5ebd3d035e205163161f883e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/filesave_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cd6d10f9299dca7fb9dba7eb2dc7f6b5ffa5df18149651f0dda609a7ce846f9 +size 720 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/forward.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/forward.png new file mode 100644 index 0000000000000000000000000000000000000000..95f0608c72554c70629727dc7f8b9cd71c8b7a40 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/forward.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4a6cb7a98068867b26364c2065f2cbe3be6ed9e024b78b2b05c5cab8191fb09 +size 357 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/forward_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/forward_large.png new file mode 100644 index 0000000000000000000000000000000000000000..2328e60fea66d1087c095c8bf2ea37f81e02ac7d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/forward_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfa87b9bb0d90c7aa5ea491da4d3dc9328b62ca09eff1861c9abd6011cffda44 +size 593 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/hand.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/hand.png new file mode 100644 index 0000000000000000000000000000000000000000..6b7ff3c8418e91558c0409618a12b29b6122d376 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/hand.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9c7214444c629ad2160d294c672400709326171013ea272fd5a923e54f45b64 +size 979 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/help.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/help.png new file mode 100644 index 0000000000000000000000000000000000000000..cf8c8dd200b2cb2c5e7e873dd6f717d213e4691f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/help.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b38a50aea690d29cbc23bbdcf61bf7048dc33bfb64cbeed804ca5a1ee0430816 +size 472 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/help_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/help_large.png new file mode 100644 index 0000000000000000000000000000000000000000..1e15e7bfe1260cf9e379e053680b04be817c2469 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/help_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d48c04c967c64609e809633eafd0891c4a204c9543e67d5cf0b5d32b8009e111 +size 747 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/home.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/home.png new file mode 100644 index 0000000000000000000000000000000000000000..ed93c90376015f29af47453690284cce33582da4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/home.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21c15d00051aebf034aadf083b723ca78ae95e942002527c9dd04408287b0b5c +size 468 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/home_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/home_large.png new file mode 100644 index 0000000000000000000000000000000000000000..c7948b51928065ce25a3c074fd1f709e26054634 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/home_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb14b63b7b5638787589abbb09a555e1eae6209699d34ee26e6e59de2f245d88 +size 790 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/matplotlib.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/matplotlib.png new file mode 100644 index 0000000000000000000000000000000000000000..68677ab753e5aa4d86df73b35f635f2ec17e0598 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/matplotlib.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3c28b45855afafa146576b8d618096ae42ea288acdb77f73457dd73bda95186 +size 1283 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/matplotlib_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/matplotlib_large.png new file mode 100644 index 0000000000000000000000000000000000000000..a19957e9d2a491aa91ddd80fd343f2579dba76c8 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/matplotlib_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:125468b9ef60ad4aa4657267824fa7be1e0629fa6f278804ebd5abca309b5f95 +size 3088 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/move.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/move.png new file mode 100644 index 0000000000000000000000000000000000000000..f12eb8277f4bc4ec080f610cb3230dd4538f22eb --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/move.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e68d1e352334b3c466e1894715eb85f4cf1d818ebc5b587ddc48abe71b6bf37 +size 481 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/move_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/move_large.png new file mode 100644 index 0000000000000000000000000000000000000000..5ab33ce3c717255aacb0fea1de28e4d339742929 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/move_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a48f3da75bf453039b3fd20f3c81dab686b55b9ba0ce71f616e05bb8d859fd5 +size 767 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/qt4_editor_options.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/qt4_editor_options.png new file mode 100644 index 0000000000000000000000000000000000000000..d6153282c61ab97dd47bb2786c47dd29f39dd233 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/qt4_editor_options.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12bc908d0e61876770988c6dcc216230dd54e939ddd75a750837e01f96478cd3 +size 380 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/qt4_editor_options_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/qt4_editor_options_large.png new file mode 100644 index 0000000000000000000000000000000000000000..4045320f2734b20820293a6d90e6eb381417a4bc --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/qt4_editor_options_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8f77ef55879688af73d96bc3ba19efc12e8e35922127a6691d0e3f1ad752646 +size 619 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/subplots.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/subplots.png new file mode 100644 index 0000000000000000000000000000000000000000..3080d08cfeaa2c7d1c2e4367151f6dbd41bedd5f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/subplots.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3147c222dab7ff2cdbf724627863a09699f463be21f0803b9b98bbd01eb78917 +size 445 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/subplots_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/subplots_large.png new file mode 100644 index 0000000000000000000000000000000000000000..dbc0c5889a8837f7ed750bcc32cbc70328a00bb4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/subplots_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11dbbd4b054c4045c9679a205397325bb54b7305c976175ff84b71c66c5d908b +size 662 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/zoom_to_rect.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/zoom_to_rect.png new file mode 100644 index 0000000000000000000000000000000000000000..c11408f35f7676b8041880b4cd2fade52e677b5d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/zoom_to_rect.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68dcf741906b220c6ef44f9f15f690c1e095362b46b83505a02dbb7b9354d8be +size 530 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/zoom_to_rect_large.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/zoom_to_rect_large.png new file mode 100644 index 0000000000000000000000000000000000000000..12e527a5282e3e1359b9a6ed7a0a5fb9a94effa9 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/images/zoom_to_rect_large.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:57aa64c669ba570144c5d83f3c425674adfb1c1ee4ddc13f728acb6bb45b50c9 +size 1016 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/Minduka_Present_Blue_Pack.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/Minduka_Present_Blue_Pack.png new file mode 100644 index 0000000000000000000000000000000000000000..5cb71359fb8d5589d6c0043257d56fe2648a2ed8 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/Minduka_Present_Blue_Pack.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e72868826a7a4329a950e5a9efa393594807833fb7f27e5cd001a8afb9cd081 +size 13634 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/axes_grid/bivariate_normal.npy b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/axes_grid/bivariate_normal.npy new file mode 100644 index 0000000000000000000000000000000000000000..a76ff8b1f63c970d5e02b481a16b3231408aebe4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/axes_grid/bivariate_normal.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e9599f6e74087aa2ca58aa77846b6ec3e8491180e445c07a2c69c65756ef7c5 +size 1880 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/goog.npz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/goog.npz new file mode 100644 index 0000000000000000000000000000000000000000..bd82e71bf7d72da7db030381c31f769a3d9736bb --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/goog.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:400917cf30e6b664f7b0da93d7c745860d3aa9008da8b7f160d2dd12e6a318b1 +size 22845 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/grace_hopper.jpg b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/grace_hopper.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e603790a61a93f8196c4a87a7098004bae891676 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/grace_hopper.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8ca6d734765703b09728ab47fe59f473d93ae3967fc24c7c0288c3c7adb7130 +size 61306 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/jacksboro_fault_dem.npz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/jacksboro_fault_dem.npz new file mode 100644 index 0000000000000000000000000000000000000000..065732313f852fe861ea6852a84f8c59666c90b1 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/jacksboro_fault_dem.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d493f50a33e82a4420494c54d1fca1539d177bdc27ab190bc5fe6e92f62fb637 +size 174061 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/logo2.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/logo2.png new file mode 100644 index 0000000000000000000000000000000000000000..f154a552bea670643fe9be8da3853c1350d0e21b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/logo2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d7371e055decaac47cb6e809af3442e9c1ecd02f1c1e2d063d1cfee4b4a21d7 +size 22279 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/s1045.ima.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/s1045.ima.gz new file mode 100644 index 0000000000000000000000000000000000000000..29d1c7f70afaa882d9673861bc3d17a4ffd7235d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/s1045.ima.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32b424d64f62b7e71cb24d29fd53938ad5664d608055a67ab2b2af4369f8b89e +size 33229 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/topobathy.npz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/topobathy.npz new file mode 100644 index 0000000000000000000000000000000000000000..67fc6c403643c5b4e0624005b7bd99ac59e856fd --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/matplotlib/mpl-data/sample_data/topobathy.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0244e03291702df45024dcb5cacbc4f3d4cb30d72dfa7fd371c4ac61c42b4fbf +size 45224 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_axes_basic.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_axes_basic.png new file mode 100644 index 0000000000000000000000000000000000000000..c5dcabcd70cf8ee32b6f25155884a2dab83d9765 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_axes_basic.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64a2def585a5039e2e47e0b6a0574526c6444fd3d8b8250789a43b942868dc7c +size 23704 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_axes_projection.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_axes_projection.png new file mode 100644 index 0000000000000000000000000000000000000000..257c5f05a3708fe3f103ca2a7fe9c89472309d49 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_axes_projection.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bcc64fb911c72c28f45e832727b79bc1313fbb663e219e187c322dcb6dfdd86c +size 13594 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_color.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_color.png new file mode 100644 index 0000000000000000000000000000000000000000..3bcb0ea9ea74cb57bded250bbb89cb8581504c4d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_color.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b8351c05ca50b3535f20cbd6c6499709eebe076ee40ccaee79435252b1eb9ef +size 59599 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_colorcode.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_colorcode.png new file mode 100644 index 0000000000000000000000000000000000000000..7231b1ae8789e5f689c5ca3b85cb03654513727f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_colorcode.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c35f18fcfe873450d2a5986c13367a8713137a84dc06f961503758f4399420ea +size 18191 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_colorcode_downres.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_colorcode_downres.png new file mode 100644 index 0000000000000000000000000000000000000000..9d0c919f2c034b5a232ac3db3537b8ba4c05f451 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_colorcode_downres.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d0b16b336f05d3417dfec127f583418bbcd5ad73ff9fd65d640103072bf6941 +size 5231 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_default.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_default.png new file mode 100644 index 0000000000000000000000000000000000000000..58c7197ccd1dcf31577469e38102d0bc03c5d873 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_default.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edff809108d21a9707a9dd2fb4d5115ee40bc845717d94515f462a87daed7d69 +size 128051 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_downres_False.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_downres_False.png new file mode 100644 index 0000000000000000000000000000000000000000..b0a1eff6a96faa27f55e46b60c2e276482e0d18f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_downres_False.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d35dda76b8f1710eb76ed85e366bf720236d7a8f2187d31ddfe7accdfa3ceef9 +size 6641 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_downres_True.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_downres_True.png new file mode 100644 index 0000000000000000000000000000000000000000..0e6222e11634267215d2465e21b212e4843343de --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_downres_True.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c66fe2ff73e502309a2abd690efe61b07f7bf97e276217ff3816749982bcea9d +size 4993 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_False-False.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_False-False.png new file mode 100644 index 0000000000000000000000000000000000000000..05ab50fa6d6bfff7bf9e9b467c14d4f021c9a389 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_False-False.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9093225532cd4a89b382fc07c15f4f842fd571285d0c573014cb8f42efcb2273 +size 32808 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_False-True.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_False-True.png new file mode 100644 index 0000000000000000000000000000000000000000..2565fe52881ef738fb1d52fe615cc582607cbfaa --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_False-True.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c85eca03a2ce80b2e08f403aef5c5df4c968aaa70ee54f79572ccbd063117c09 +size 32996 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_True-False.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_True-False.png new file mode 100644 index 0000000000000000000000000000000000000000..20ec7cd852d743f8ccdd9f0e5d8cc68a647ebfb0 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_True-False.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d7aa701c8c279be3048307079dc5a269622d3ee7cb30184417a384ff0e07ba8 +size 32846 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_True-True.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_True-True.png new file mode 100644 index 0000000000000000000000000000000000000000..9c181145c63ddedb4ccad6f625ba3b95eceda417 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_flipping_True-True.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47b42d9d87af4f21df676643db8df326c9a70ed69a19155acff57ba9d78ca250 +size 32995 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_image_settings.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_image_settings.png new file mode 100644 index 0000000000000000000000000000000000000000..aedadd8d52f85056d3608b401525011f5e685882 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_image_settings.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13eb84ee214ea6b3da8bf714752e56786b235aaac415c9f4cc63cc0f8ad43761 +size 91085 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_manual_limits.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_manual_limits.png new file mode 100644 index 0000000000000000000000000000000000000000..8bf9334d492a9e883a9c9106f9e0063e71fa057b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_manual_limits.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1baac7ea8673c03e07b11aa9824eda30dcb19b82aa2715b78145f7110c38e135 +size 45822 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_multi_scatter.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_multi_scatter.png new file mode 100644 index 0000000000000000000000000000000000000000..6431b3def94aff48d82b635d99e6e793bc5de714 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_multi_scatter.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d585276065cd4e02074f8a5b342ebf94f30e88bb0b7b4100b3556e9c3278ebd2 +size 17221 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_norm.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_norm.png new file mode 100644 index 0000000000000000000000000000000000000000..cb5eb49cd492f8e3c2be4f05799a6b97fa13ffb5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_norm.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:316549aeb92b3f230a7f748a4141b09146bfbe0ddca34f6d30cc02daec4f5374 +size 50567 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_origin.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_origin.png new file mode 100644 index 0000000000000000000000000000000000000000..3f726578edc0e5c40a6b0e588b2e840a365c18ef --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_origin.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8028b0c65707bd324a6717c3c74c2960134c651c28f5bb67392e091914b70e75 +size 18524 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_remove.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_remove.png new file mode 100644 index 0000000000000000000000000000000000000000..10bc2ef96a3c50170c3472400a6991fcdb47db9d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_remove.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88fa27bdbc207c9fdbd9d5c561c272315f2d948ef4bf44ce248ff1f2bc2f2f7b +size 6273 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_linear-linear.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_linear-linear.png new file mode 100644 index 0000000000000000000000000000000000000000..373cfb7145b4839361854eb5d00c47d20e1c60ce --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_linear-linear.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fd531e23af9020a3bfd67c7713dec5af9a25797ef7fe1783fc67144f54401b9 +size 12408 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_linear-log.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_linear-log.png new file mode 100644 index 0000000000000000000000000000000000000000..a9ab7f516c4b2280690e1cb6e341582021c33b6c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_linear-log.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a2cb8d02624f894585c8d2757c56ccf9fb04aacb3101e86fd548756c0f2af68 +size 21818 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_log-linear.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_log-linear.png new file mode 100644 index 0000000000000000000000000000000000000000..6e8365f4499927894b2951ae69eee51ca5d959f4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_log-linear.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ddd15bbf891387f33e64c097077e2c5d35db3513e14d8c9cf731976badf99a56 +size 25448 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_log-log.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_log-log.png new file mode 100644 index 0000000000000000000000000000000000000000..858471c116505156f55a43c0cde51d730f09319c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/mpl_scatter_density/tests/baseline/3.0.x/test_scales_log-log.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87547bcd4cc716892b3b4e00dacda613f64685f899b4d41961dfad9db0990246 +size 58090 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gl1.gpickle.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gl1.gpickle.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..5e9291ea7aa77204bbaab28651e6a4d4f47a4bea --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gl1.gpickle.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf8f81ceb5eaaee1621aa60b892d83e596a6173f6f6517359b679ff3daa1b0f8 +size 44623 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gw1.gpickle.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gw1.gpickle.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..356e5deb3d243226bd9942e3ce02129d3d7a0201 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/gw1.gpickle.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f79f0e90fa4c51ec79165f15963e1ed89477576e06bcaa67ae622c260411931 +size 42248 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..9351606de26547246c807a6f74ffa81c84448456 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/netgen-2.gpickle.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b17e66cdeda8edb8d1dec72626c77f1f65dd4675e3f76dc2fc4fd84aa038e30 +size 18972 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/wlm3.gpickle.bz2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/wlm3.gpickle.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..c95da5b280f27411afeeb215cac8a99219e89078 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/algorithms/flow/tests/wlm3.gpickle.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccacba1e0fbfb30bec361f0e48ec88c999d3474fcda5ddf93bd444ace17cfa0e +size 88132 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png new file mode 100644 index 0000000000000000000000000000000000000000..6c9e5bdee713b998b23ceb6782595b29c2870a0d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/drawing/tests/baseline/test_house_with_colors.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1508bda48445c23ab882f801f1c0dd0472f97ae414245c3ab1094005fda4455a +size 21918 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz new file mode 100644 index 0000000000000000000000000000000000000000..2cb5d1308c1168df6218cee0a97552c5787a29b8 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/networkx/generators/atlas.dat.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73fc416df0164923607751cb759f4ae81deb5f6550bf25be59c86de3b747e41d +size 8887 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cublas/lib/libcublas.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cublas/lib/libcublas.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..bb58b05fe4679649023c94850f174af45c2880f7 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cublas/lib/libcublas.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:031ce6c2cbfbb9468f040527cab5c599069ce5609e73e28f87503881063eac21 +size 116388640 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cublas/lib/libnvblas.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cublas/lib/libnvblas.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..c57b5c5f6ed2ccd520590ab4f3f2b56db62ef325 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cublas/lib/libnvblas.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d244820d32966f0af47afe6c9ee6f34b230fafe87ea0141dc71241a5d2b340c +size 753824 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcheckpoint.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcheckpoint.so new file mode 100644 index 0000000000000000000000000000000000000000..221583bed327fcea48fee44f96ff29532106f0e4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcheckpoint.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06ba82bd09237b934cf16da2172ed5943c582caa35c79b52cfcfeb0ff71f7250 +size 1644872 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..277e6a8743a6175aa88f51ee597b507e243647a4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fccdc5fcc7c32f8cf4b3ed9b17f7f187a185a6fa0a5bcc06e3434cbd1687c808 +size 7595792 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_host.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_host.so new file mode 100644 index 0000000000000000000000000000000000000000..993b778b11f3e8abcbcd6fa70d6ab6b45c3bb9e8 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_host.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:609f54063c253daff6efba79fe49252fdd2324308ab0ffb991cc125d3e9a1eab +size 25825936 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_target.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_target.so new file mode 100644 index 0000000000000000000000000000000000000000..3e02016ad79ea11a402b8c3ecef67f46dd441a36 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libnvperf_target.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f10e1109fc341a57434c28e4006b45a89247801e20f5ace135c302c173e0770 +size 5275312 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libpcsamplingutil.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libpcsamplingutil.so new file mode 100644 index 0000000000000000000000000000000000000000..4dcf914441ef17f77fc607d8d6dab7e5219e9d35 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libpcsamplingutil.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6fa2783077974fb2765bfa9cbaebf980736df74eebf994c59c7596988aec83b +size 970064 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.alt.so.12.8 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.alt.so.12.8 new file mode 100644 index 0000000000000000000000000000000000000000..42c9ab575e23eb0427a5262923021b25afbc0a1b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.alt.so.12.8 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e971f2dcced2628f327ddb037d02c41b834f2c3dbfbff03c9d2c3177f1b9b6d +size 6309832 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.8 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.8 new file mode 100644 index 0000000000000000000000000000000000000000..4e450efadaaa36a785461f39ad19dfaf3ba9fea2 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.8 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eccaa824230ee7858a94a3055cb01f1cb634df05d313880d0bdcf195161fcb4e +size 6338504 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.alt.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.alt.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..8a31cf538a6b4297217a2ba61a03792b7468aac4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.alt.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8260dbfdba5820d0e710dd00f4370285d5ebe18c7d98ba2a6737deedf48d3eb +size 104966520 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..69425398fff1ec11a5940fe4bc5a38dedc4da2b0 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43731e24cd89e3749826304f304e8aa11fbecf1188715271b1f5018d6212b5e6 +size 104487248 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_runtime/lib/libcudart.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_runtime/lib/libcudart.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..4bff80847b31e48a2ccc85390129a46297cd0539 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cuda_runtime/lib/libcudart.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3a75b33af334a3486d197dbd1584a2985183ba4688d237a2be5f2f679329920 +size 728800 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn.so.9 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn.so.9 new file mode 100644 index 0000000000000000000000000000000000000000..bf5d797eaff7321e2206c1c301736509b099604c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn.so.9 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b68ea689be647bce63cb3c2d9edb589add415405a7e9f296d69ca029cae0b8b +size 125136 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_adv.so.9 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_adv.so.9 new file mode 100644 index 0000000000000000000000000000000000000000..a711794caa8758382722a2e36745a60599ad25a4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_adv.so.9 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9814d64e04fce1f6cbd16d02ccefd6611541b3c61736fb450e334b482635ca07 +size 285226600 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_cnn.so.9 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_cnn.so.9 new file mode 100644 index 0000000000000000000000000000000000000000..0e93cfc3938f01d129283bf6733cc9d68e0eb318 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_cnn.so.9 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:655c2d2649466c73b6b4c19705fb6906fd95e331a1f8218314b49f37dd7cafed +size 6301096 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_engines_precompiled.so.9 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_engines_precompiled.so.9 new file mode 100644 index 0000000000000000000000000000000000000000..5e5d22a8b2c504f09dd4ce8d855cfd4102b953f4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_engines_precompiled.so.9 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f504745d346542609f975de51227080647d3675eac576ead82c396b8124f8f28 +size 547383096 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_engines_runtime_compiled.so.9 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_engines_runtime_compiled.so.9 new file mode 100644 index 0000000000000000000000000000000000000000..f6ad34b190533e900631f65c41d0a997a29e2a81 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_engines_runtime_compiled.so.9 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8222672743c4f2e39feb1c365d6f6b6c40f56023471506f49944910847f1ee0a +size 23094328 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_graph.so.9 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_graph.so.9 new file mode 100644 index 0000000000000000000000000000000000000000..bc1dc399f5d7d92c18690922887c5a70898f9344 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_graph.so.9 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:787c955dce49091ead850e4536666594095ea9f92a8a08879d8ddad466674657 +size 4439912 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_heuristic.so.9 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_heuristic.so.9 new file mode 100644 index 0000000000000000000000000000000000000000..91de6957a83787a3d85936391ab07fa5b176fff7 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_heuristic.so.9 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2804eee5f6fc11d0299ba07687eda0a974d3b2436357c639706c4e282cc2cc05 +size 58726712 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops.so.9 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops.so.9 new file mode 100644 index 0000000000000000000000000000000000000000..4a17334bd1f80fd214e37d9601b27c615bd075df --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib/libcudnn_ops.so.9 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34f56d67f3df108949d1e5e03543064e055e217d0f5e53dc6d4f7c9454d852f8 +size 127936080 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufft/lib/libcufft.so.11 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufft/lib/libcufft.so.11 new file mode 100644 index 0000000000000000000000000000000000000000..347c794d2698d5aaebfd52ab415b88c7e84206fc --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufft/lib/libcufft.so.11 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c912146449614f9d73ebd1a5cb604242da6b819d94ba5b4a99272a0649f3761 +size 278925016 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufft/lib/libcufftw.so.11 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufft/lib/libcufftw.so.11 new file mode 100644 index 0000000000000000000000000000000000000000..baac2e26a894cda7f7e62914c9f43cf42265d549 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufft/lib/libcufftw.so.11 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fe4db0533c317e21ef73aa6529ec5fafc6edea80aafcff103eb58f00512b8ea +size 2101472 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufile/lib/libcufile.so.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufile/lib/libcufile.so.0 new file mode 100644 index 0000000000000000000000000000000000000000..06bb45e1bec279768e85910c789d7b0e9cc755e7 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cufile/lib/libcufile.so.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2f4854177f666c1a8c719b486e4cb1119ebfdd858ebaa6349cb63c5549d27e8 +size 3209496 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/curand/lib/libcurand.so.10 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/curand/lib/libcurand.so.10 new file mode 100644 index 0000000000000000000000000000000000000000..1138aa1ec28bdc15b00a8ee90fe18f2651362029 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/curand/lib/libcurand.so.10 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9bea038a2703b721571fd45a299a898141fd8cb264a5912635c95116f5960fe +size 136749240 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolver.so.11 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolver.so.11 new file mode 100644 index 0000000000000000000000000000000000000000..ae920722b31becb0f4e5aaf9bcd4496f7f31384c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolver.so.11 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b64b838bf3e2f27373a59312aff73a5fb7e452300c4048db353a7f30d009a1d7 +size 243303872 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolverMg.so.11 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolverMg.so.11 new file mode 100644 index 0000000000000000000000000000000000000000..52ddebdef58cb26fbb7a71ef1e3e06770738d908 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolverMg.so.11 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d947654631c536e9099abcc9fe551ece97d0ffeb8fbab142189ea2c85bc55e8e +size 161493576 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..fe4ff6f438c4d17d0463bc866e0a6887776017fe --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:437651d1ec5d0e5b1b4d07b8c492f153cb4825222fe2d763232a407f667d9bb2 +size 387990224 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusparselt/lib/libcusparseLt.so.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusparselt/lib/libcusparseLt.so.0 new file mode 100644 index 0000000000000000000000000000000000000000..563396da27035452e1e5077fccfb349ba438d4df --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/cusparselt/lib/libcusparseLt.so.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3d85a0311eadfd3cec86b0291c9a4b5769cba2f248a9e7e8167fbf3ffa99863 +size 451980513 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/nccl/lib/libnccl.so.2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/nccl/lib/libnccl.so.2 new file mode 100644 index 0000000000000000000000000000000000000000..a4cdc302ba817b19af48b43a30f25d35cf7002e5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/nccl/lib/libnccl.so.2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fc36eebc84f4b10923eee21538ed8fa25725647d06f4840bc0fe399a6ed9bc4 +size 429634192 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/nvjitlink/lib/libnvJitLink.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/nvjitlink/lib/libnvJitLink.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..52f8dce6679097249f83540fa5d89fc1f3453033 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/nvidia/nvjitlink/lib/libnvJitLink.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0369e6867d44b800437de4e146d72c65afc6c75adf677a15c2ecd8e6a7ac135f +size 94101392 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libavif-01e67780.so.16.3.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libavif-01e67780.so.16.3.0 new file mode 100644 index 0000000000000000000000000000000000000000..03731923ccfebc6f840404c3e11fbb1a01b03ea5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libavif-01e67780.so.16.3.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c425e503cfeb820cec080fc4b16285ce0a8f0664f58a1a590a8de2332bc3d4fd +size 5142057 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-c55a5f7a.so.1.1.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-c55a5f7a.so.1.1.0 new file mode 100644 index 0000000000000000000000000000000000000000..0ef430e693219748841bfcc2f182573048786f1a --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-c55a5f7a.so.1.1.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1da2db326dd87a15fbe7dc2017b654d2457085d817e2e91fbd034acada1aaf0f +size 144425 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libfreetype-083ff72c.so.6.20.2 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libfreetype-083ff72c.so.6.20.2 new file mode 100644 index 0000000000000000000000000000000000000000..bacdbede163f1188ca1a6f5931dff95fe5b2ed8c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libfreetype-083ff72c.so.6.20.2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d1ed08fcbc7998985a8f2ae755fee5888c6dcda18dd91081aac92b81dc5c62d +size 1430825 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libharfbuzz-fe5b8f8d.so.0.61121.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libharfbuzz-fe5b8f8d.so.0.61121.0 new file mode 100644 index 0000000000000000000000000000000000000000..ae6d2a580a5a7d071a432e78a40185fd26f7696f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libharfbuzz-fe5b8f8d.so.0.61121.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec1618623334334acdc44a35775caaa92a0e18b09c6ecf89aa2d4a5aac6fa263 +size 908081 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libjpeg-8a13c6e0.so.62.4.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libjpeg-8a13c6e0.so.62.4.0 new file mode 100644 index 0000000000000000000000000000000000000000..a7ccb12c68691e641d0fdfcd1d0ccb32bdd2d12e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libjpeg-8a13c6e0.so.62.4.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fd2cd3b79617a40ff920815e83ae0b25788fe05df97711f5b0029891c31cbd9 +size 832177 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/liblcms2-cc10e42f.so.2.0.17 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/liblcms2-cc10e42f.so.2.0.17 new file mode 100644 index 0000000000000000000000000000000000000000..14890ce029d018e642384ff45769f23e206ecd86 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/liblcms2-cc10e42f.so.2.0.17 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4932310354a330c5c8a785b425eaa8512da7b30224056043d2cfe2ae96d1ded +size 519073 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/liblzma-64b7ab39.so.5.8.1 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/liblzma-64b7ab39.so.5.8.1 new file mode 100644 index 0000000000000000000000000000000000000000..ae7fa8d9cc6056ed01fa9027ae016ec300bef3b2 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/liblzma-64b7ab39.so.5.8.1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84dd81d913c433ac0e82f111fe0e377cd8db350fd2b2b7a75f6c2501f1d6fa70 +size 266369 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libopenjp2-56811f71.so.2.5.3 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libopenjp2-56811f71.so.2.5.3 new file mode 100644 index 0000000000000000000000000000000000000000..9b76f1e56aac052f8e797ab420dac563359fc4e1 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libopenjp2-56811f71.so.2.5.3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:686f62cbed321379e3e38be7ae94c56411d4345bde8d54e557b40472d9a7693a +size 585849 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libpng16-d00bd151.so.16.49.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libpng16-d00bd151.so.16.49.0 new file mode 100644 index 0000000000000000000000000000000000000000..72bc1097c1ff23ca88b863d9fc0bd6e3653f98d4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libpng16-d00bd151.so.16.49.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:558882880a0307a7675a595b712a4ebbd0eb1ca4374e1e2d7a9896761760fe6c +size 278001 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libtiff-13a02c81.so.6.1.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libtiff-13a02c81.so.6.1.0 new file mode 100644 index 0000000000000000000000000000000000000000..ed5803bd15b9edccbb282f05b3ab2a0f7f93056e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libtiff-13a02c81.so.6.1.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:007f36ed9297e1fffe0e962feba0442dcce486455d6cd98b2c58a57bcbd15605 +size 746233 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libwebp-5f0275c0.so.7.1.10 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libwebp-5f0275c0.so.7.1.10 new file mode 100644 index 0000000000000000000000000000000000000000..ce3b4688a3cf83c9d3db9d1b094dba04ff3d178e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libwebp-5f0275c0.so.7.1.10 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3a3778927251e1ae485268cfdc16a93b20066b59ed698069b0264fb0ce14989 +size 731185 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libxcb-64009ff3.so.1.1.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libxcb-64009ff3.so.1.1.0 new file mode 100644 index 0000000000000000000000000000000000000000..50d8dbbeb6524f9a4679c30c15c56df5fca4d606 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pillow.libs/libxcb-64009ff3.so.1.1.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7437ed16bae7ac4498049fd14e10d1bd1c3e7d15d0e5eab1d2ead42a83a49d1 +size 251425 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip new file mode 100644 index 0000000000000000000000000000000000000000..400905eecf0385de4d3b8e50b9892e1302b2b894 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01845c437f4655e3cf9cc4fc4e49cfd607431f22675e1b611129a90239f34822 +size 1809 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/core.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7669709f6fa7e6f57ca972b9504427efd6e09b24 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/core.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bfd6b46746208c99ec1505c6a50a9612143aee3045e58bdfdf9ff67b51694a3 +size 193059 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..c67fba89d7868adf8cda19d759510b7b4a34c6ab --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a7eaece7231911be2fbb1b3e7cb4cb5c2e0f84e0c2bb73739472b5a1feec8c1 +size 168193 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1-0352e75f.so.5.0.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1-0352e75f.so.5.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..32aeee9a92e063a830909443ffa10a61f8eb4896 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1-0352e75f.so.5.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6090048eccc763522c12ef016f81da6b627cb3a044f55cf0479a839c41c0980 +size 2833617 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..47f28619b3aab72df5480d0140d9f43ea3859d30 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14afb3129b1a8b50bc40a3b0820c7f1152ea9bc10121aab152943f7057472886 +size 2686065 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99-934c22de.so.0.0.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99-934c22de.so.0.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..4e1eb5101254f9fcebd5d9b3fec1f6413b0f931c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99-934c22de.so.0.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ed5137f412781ad7863439fb543613f620b43c32b63292a0029246162f5bbc6 +size 250985 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..c4b4570cb08e531daffd8e9ca6cf501eb500c067 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:934c22ded0e7d169c4d4678876c96051adf3d94545da962f60b41659b075da3b +size 247609 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libscipy_openblas-68440149.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libscipy_openblas-68440149.so new file mode 100644 index 0000000000000000000000000000000000000000..949095f115ca7dd9bd6a6947284062392f130904 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy.libs/libscipy_openblas-68440149.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e739a2435af49d2d938749f316aa338c65f41c9ae6615406e7cf83feb662f46 +size 22211841 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/collections.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/collections.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..58d996159d33434f9004d64aa6c2278657fe40a2 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/collections.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:813aeb583aee02a90772d3ba671cf0ff6c87cc06e4958cf2ba0b4efdb4efa4bd +size 2007152 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/processors.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/processors.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c60b70319ce7064b9007356bef9eeb21cd36209b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/processors.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fcc0f6b57d2197ab15db52faea389c610c08e090f3e3396ac89dd8fb1f6d5e14 +size 543208 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/resultproxy.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/resultproxy.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..86668fc3e0776a4f5cb7050f801066fdb6122f2d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/resultproxy.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08f7c1df53173182e6ceb3995c6c23f22ea8b350749b5f7ff3f9273622f4e350 +size 547112 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/util.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/util.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a78f6217ba65607efabc48925272846d342c62ff --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/sqlalchemy/cyextension/util.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c25ce6b73dbd73df87010753a2b4b17f70524e8b607889b602229049e5933b05 +size 819200 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_meta_registrations.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_meta_registrations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..028567e6dd0db51ccf28e36ce1d4db6c095a1049 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_meta_registrations.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76fed6253aeafefe06802d2b64d0173680a5a20c6d681a2563926b3ed1e590c5 +size 205726 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_tensor_docs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_tensor_docs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88f869616f7b5ae78ef8cc69e08e4dce1ba00c42 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_tensor_docs.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ecc4c2fc336d30aa9c425a9b9fd98560086d243c942d5ba54de296311f29ba4 +size 136521 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a937dacead56a71f1c151c69ebc8e08b31947fea --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09952d2e5a36369636180c18c6456d9c627f31dad5711ad30c4df0132a3934ac +size 418731 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/overrides.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/overrides.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afc7b752bc13e0e717a6fde46b6a58ac7cf0dbec --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/__pycache__/overrides.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1363f9eb14f377ab82521549c8db86549574f324ec58035ad05da12c0378b35d +size 158640 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/decompositions.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/decompositions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c091d8a4a384de8f088306c3a3aa9880f00b330a --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_decomp/__pycache__/decompositions.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30a3d9ce790f155f443b6a803d6c6750113e3e7d162023795a1c9909b45ebcae +size 123576 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c27327ca11fa3948307f1ea8e541a6cedf5aabb --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4cf8a0da94b449d782083cfed38a541badb26c3a1cec3481b8b2ecac45f734a +size 109836 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43fa91ad28daf42b5826f0548cdba487c2014c65 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:228dbfd34997405bf8104924d509cf2cebadefa8f2e031e3915ca2a29084b79d +size 108812 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/utils.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3185160fadca2caf45fe6528f60a91fd6a93c0fa --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_dynamo/__pycache__/utils.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:142f1c1d45517f4ea634147abca96353f9fb4ee1db6e7ad2cb88affb92476d6f +size 127969 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_refs/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_refs/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d154db1a5344247125396b0c158c9c90b829a69 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/_refs/__pycache__/__init__.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3d2109dac007d720790a43539501370687ef53e3e4544adef5b66c8aa083498 +size 146203 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/bin/protoc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/bin/protoc new file mode 100644 index 0000000000000000000000000000000000000000..090f02c2a0acedc7101138cd0d691a8fa50f9281 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/bin/protoc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae97a0c26f9f7f15c0bce489e240dfb3c092d85e679840c40a9dc072e3291c35 +size 5285920 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/bin/protoc-3.13.0.0 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/bin/protoc-3.13.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..090f02c2a0acedc7101138cd0d691a8fa50f9281 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/bin/protoc-3.13.0.0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae97a0c26f9f7f15c0bce489e240dfb3c092d85e679840c40a9dc072e3291c35 +size 5285920 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43977892a52240d0b678680d8ea364c3d78734b0 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9da9bd0acfa4c3a99b5d6037986dbc5e6a32570557363c38cfce8df194dbccac +size 165640 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60e3ed856be7b056204a469371a21ba928446b4c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20e746f2d0a70e3757927f69ac37fbcc70cac2de95a87d73e8e9f77f204d95ea +size 196999 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libc10.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libc10.so new file mode 100644 index 0000000000000000000000000000000000000000..1c41a6f3054cf56da0a81079d3b2310a747c3cb3 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libc10.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11add41a25c7803dcbcae77fb42b428d94e091c72738d4b0b923f3bc21fe2f11 +size 1389289 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libc10_cuda.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libc10_cuda.so new file mode 100644 index 0000000000000000000000000000000000000000..970391cde3b0865637a54c103bc9cab7d828bb75 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libc10_cuda.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee3e15d5705c557d7d82e7bc289b194eeacb223b27d7be66435c928d4bde9b1a +size 667985 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libgomp.so.1 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libgomp.so.1 new file mode 100644 index 0000000000000000000000000000000000000000..8e8eb50376dc445265a84a66e8f1e1827015ee4c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libgomp.so.1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76cac79d3b5cadd927888c09ecbced6fc9ea6a411cd4409d301543866e8ac25e +size 254305 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch.so new file mode 100644 index 0000000000000000000000000000000000000000..351f86cab6075cfc58502c80eaf9fcf4f8587938 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05967e296713f7f4f2c587ba8c4eb45a84440d5b1127816996c746fc898240ab +size 391273 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so new file mode 100644 index 0000000000000000000000000000000000000000..d099f6b5121a1c3399bfbf7a92ebf501dc73d8c7 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfe3acf07f4a1924483a26e615b8c343e163d72ee7d9a2815c2db2b7577ca57f +size 430926857 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so new file mode 100644 index 0000000000000000000000000000000000000000..658b45c303560d8c95189b236c6edd7851975974 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84027b0ac8e637f9ebc80a3a19d1e9c341f0429a100382233c45ce5224581dfe +size 1015364433 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda_linalg.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda_linalg.so new file mode 100644 index 0000000000000000000000000000000000000000..32ff2ddc3e142f56c2a647b3b6ffc54e4653c7a9 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda_linalg.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8db2767d5bc9813b6a2ddcbb0c01aa39b2d1e5b405c43469e570211ee8becaab +size 127492609 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_python.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_python.so new file mode 100644 index 0000000000000000000000000000000000000000..91f5bae3f3687fece3095f09f7c91fc91ce8b06f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/lib/libtorch_python.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6a6132e0bd2256f0f07b4bfd5589de3032a0daa1abf198113b6fc2ebb225676 +size 27795209 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/linalg/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/linalg/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25d239e2115517a10a8396ec8202e33d05b45efd --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/linalg/__pycache__/__init__.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9781c1d5f720db585963c66aa5c9e578090cdd2b71d625cb55120f92575c8ddd +size 113470 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/nn/__pycache__/functional.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/nn/__pycache__/functional.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d922192288d12e87393c798a2b62a9f23aae5cfc --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/nn/__pycache__/functional.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:decd785a76a5b7543bfc6394433064c110753378582d92af33371458fac6ea4a +size 188359 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4f12afb9f3cf0c979db91e5a903cd854aab3e0f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:736c80c0e600e28e427659477f3509c0ee9a16fd65a8c369c105a2c8a533ee70 +size 135874 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/FileCheck b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/FileCheck new file mode 100644 index 0000000000000000000000000000000000000000..e62f5027b29fc298f8568528ffc9fd1ecf5fcf1f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/FileCheck @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6ef600a5d6693ee89479a9227383b8add94730e184f0b51de365067bc08ef6f +size 1078376 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/_C/libproton.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/_C/libproton.so new file mode 100644 index 0000000000000000000000000000000000000000..3ae418c12fdec41ea2e006d8f8cb8ccba1674074 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/_C/libproton.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0dfed19820984039bd00396c1f91356b2af286fae34f84b3f4391ac8b1f04499 +size 12378896 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/amd/lib/ockl.bc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/amd/lib/ockl.bc new file mode 100644 index 0000000000000000000000000000000000000000..fcf8db85bce4220e8ae64c92faf4be26d55f9f1f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/amd/lib/ockl.bc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c10282ce42ae9081dbbb49728ca5189619dd73b4b6ef1b68e8be78274067f82d +size 246124 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/amd/lib/ocml.bc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/amd/lib/ocml.bc new file mode 100644 index 0000000000000000000000000000000000000000..cab03188324d6d8e92666963e0f8358e5b191879 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/amd/lib/ocml.bc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50f3535d6d2009750d07e73aa2b498c1bfa6cfdfe68d473bce7cbfbdf1736b8e +size 205964 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/cuobjdump b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/cuobjdump new file mode 100644 index 0000000000000000000000000000000000000000..07b8d61d6c06c4490c921f443a1a8ebc82c8d443 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/cuobjdump @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad1d0f0699f46603416eb58e7b9fdf9a293e95f9312c9df7fd6fda56a6c30d41 +size 569008 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/nvdisasm b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/nvdisasm new file mode 100644 index 0000000000000000000000000000000000000000..1942c79deb3d8601df5dc1f54877b29772f3190f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/nvdisasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1080bc909a3020761ff4c78a9b7bd9b4937bdb9c0978709cbe52381de612a1f2 +size 5894744 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas new file mode 100644 index 0000000000000000000000000000000000000000..473f90451422caa95afb0aa2dcefae645dec3e93 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c960a4f238b17d5c5d3c01ad2bbc1ebd2c5aecc459cb4d223bff10b45f9b8fca +size 31912192 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/cuda_bf16.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/cuda_bf16.h new file mode 100644 index 0000000000000000000000000000000000000000..513344bb9aeee883fde1f7eff7c2f301fea53644 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/cuda_bf16.h @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8351eb9b2e9280850c94770d3656e3414f7d20547f13a8260b0b953a03d57ead +size 204512 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/cuda_fp16.hpp b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/cuda_fp16.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f0686937d1f5041f87f67e1cc28c7fcdda54c690 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/include/cuda_fp16.hpp @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:636fbb859ca30defbec9a72c924a5616d7b8157d2b563e578b290eca8df40657 +size 120927 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcheckpoint.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcheckpoint.so new file mode 100644 index 0000000000000000000000000000000000000000..221583bed327fcea48fee44f96ff29532106f0e4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcheckpoint.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06ba82bd09237b934cf16da2172ed5943c582caa35c79b52cfcfeb0ff71f7250 +size 1644872 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so new file mode 100644 index 0000000000000000000000000000000000000000..277e6a8743a6175aa88f51ee597b507e243647a4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fccdc5fcc7c32f8cf4b3ed9b17f7f187a185a6fa0a5bcc06e3434cbd1687c808 +size 7595792 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.12 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.12 new file mode 100644 index 0000000000000000000000000000000000000000..277e6a8743a6175aa88f51ee597b507e243647a4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fccdc5fcc7c32f8cf4b3ed9b17f7f187a185a6fa0a5bcc06e3434cbd1687c808 +size 7595792 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.1 b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.1 new file mode 100644 index 0000000000000000000000000000000000000000..277e6a8743a6175aa88f51ee597b507e243647a4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fccdc5fcc7c32f8cf4b3ed9b17f7f187a185a6fa0a5bcc06e3434cbd1687c808 +size 7595792 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti_static.a b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti_static.a new file mode 100644 index 0000000000000000000000000000000000000000..bc7f86e8fd80c96d9f378d05439f1997a1ca8b3e --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libcupti_static.a @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab6d9db248f9d87527e34c2c27afb983d0050ff698b4e4aa225349adb46a3a4a +size 43563448 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host.so new file mode 100644 index 0000000000000000000000000000000000000000..993b778b11f3e8abcbcd6fa70d6ab6b45c3bb9e8 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:609f54063c253daff6efba79fe49252fdd2324308ab0ffb991cc125d3e9a1eab +size 25825936 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host_static.a b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host_static.a new file mode 100644 index 0000000000000000000000000000000000000000..8f186d2e5f2dd0344bac0cdcd6a3c89adcb90645 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host_static.a @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b132e85f9606f3525706848a9b77cba3444074fdc7a884a682dc7c2f8ed717ee +size 33480030 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_target.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_target.so new file mode 100644 index 0000000000000000000000000000000000000000..3e02016ad79ea11a402b8c3ecef67f46dd441a36 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_target.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f10e1109fc341a57434c28e4006b45a89247801e20f5ace135c302c173e0770 +size 5275312 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libpcsamplingutil.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libpcsamplingutil.so new file mode 100644 index 0000000000000000000000000000000000000000..4dcf914441ef17f77fc607d8d6dab7e5219e9d35 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/cupti/libpcsamplingutil.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6fa2783077974fb2765bfa9cbaebf980736df74eebf994c59c7596988aec83b +size 970064 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/libdevice.10.bc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/libdevice.10.bc new file mode 100644 index 0000000000000000000000000000000000000000..f6fe369965c6e281d627c80f008cd80214085b81 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/backends/nvidia/lib/libdevice.10.bc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c2fae37c86e68c3a38605a95f512d7d12d5f3db986310be47f57304aa72a5ee +size 473728 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/instrumentation/libGPUInstrumentationTestLib.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/instrumentation/libGPUInstrumentationTestLib.so new file mode 100644 index 0000000000000000000000000000000000000000..b2aab0a3e499b3dcca99e8910c57322f05175035 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/instrumentation/libGPUInstrumentationTestLib.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bf7f0e7e7d9480ede037fce16c78e3d68a75f6533f5d0e323c33bbbe181d474 +size 6407104 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/instrumentation/libPrintLoadStoreMemSpaces.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/instrumentation/libPrintLoadStoreMemSpaces.so new file mode 100644 index 0000000000000000000000000000000000000000..8a38565ef59bb58bd2b15437a87c2190c0e3829b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/instrumentation/libPrintLoadStoreMemSpaces.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af895c597cd4575637762234e77f03d52a2a50ef86c7b734040634cc9d079d9f +size 8941080 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/language/__pycache__/core.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/language/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa2af863aabbda4065ed05ab89571ef118d51488 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/triton/language/__pycache__/core.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee1885c43aad08b25323ae83a0aa1ca22a2be97315f2bcf8447387e2bd23e4ba +size 116765 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/_aggregations.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/_aggregations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e544d38f10dd2a139d0bb5e67ae1b1ddccfa1c08 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/_aggregations.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7aef856d446189b6012556990acf974c684ebc2abaf9bd573215db71695a1a9 +size 300840 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/dataarray.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/dataarray.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50251faa95f17afe89b70f3a4037a938dd0954b4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/dataarray.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b88b76d0694a83f4bf2db43580fe4a728abfdba74b2a29330d49e00adfc12ede +size 277814 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/dataset.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..056ec0d9cfc3caa19ed01f1d40fa57a8a695260a --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/core/__pycache__/dataset.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e25f44020c97edcb49b30e9494b6d25d1638f40a625870a8688aa4a3ddf3fd08 +size 344614 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/tests/data/example_1.nc.gz b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/tests/data/example_1.nc.gz new file mode 100644 index 0000000000000000000000000000000000000000..ca5b68542d57cd3cbdf3a7c8c50d9a4ec4db027c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/xarray/tests/data/example_1.nc.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d88def15dddb52a79c63a1b412922b30c9112eba30d374944176110ba523261e +size 470 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/yaml/_yaml.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/yaml/_yaml.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ea08486ca22f666758e77fe218eada23ffbb1644 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/yaml/_yaml.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db41d5f9c569205b8eb95513990d7e3d021bcadd27f1cb5f5eaec908c21f6eb5 +size 2383664 diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2140970015d099763797d60a98a3a3b6f4b5f219 --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8c8c4b1623bf0bca8ff1ae6203a4765e2054bec Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e271b7c0c812b0cf591aced756351cf510492aa Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02d25325c5e073011d877b43e49301e1e43097d8 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e95dd53673d9789ed8af6e319828429ffee74b75 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9f1f829dc9e42e6c9735114109d61ed44bb72de Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1761f1397f71a2b5c20cf9673edc80e9775da3c0 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..589958339d412bae15fd5c0777431acf133f1390 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02e3c7d864c9080dae96184e60e65633e3149f91 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba3ac7c9eff7d9d6d1118fda4d956ab7b0ab1f1e Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..399578a60d23df2c03959d6c4d45de7d8d2746b7 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b29809dd7aa988ef2ffd324012629d7cfbfc2eb Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..293a3e7038f77f26c83934b5e18377c40b8ae2ca Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa0e95ba35a1eb8dc1c8d2872036b3864547c6d1 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c20a160c90ce58bbbf72a5b581d379ed9f951d6 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..072a7f3d2d6427596a3eab9e63e2717530d06279 Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4094d88c75d93367c481f5c3f603424cd6c13c --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py @@ -0,0 +1,606 @@ +"""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 os + +from types import ModuleType +from typing import Any, Literal, TypeAlias + +import numpy as np +import numpy.typing as npt + +from scipy._lib import array_api_compat +from scipy._lib.array_api_compat import ( + is_array_api_obj, + 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_array_api_strict_namespace as is_array_api_strict +) + +__all__ = [ + '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal', + 'get_xp_devices', + 'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch', + 'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for', + 'xp_assert_close', 'xp_assert_equal', 'xp_assert_less', + 'xp_copy', 'xp_copysign', 'xp_device', + 'xp_moveaxis_to_end', 'xp_ravel', 'xp_real', 'xp_sign', 'xp_size', + 'xp_take_along_axis', 'xp_unsupported_param_msg', 'xp_vector_norm', +] + + +# 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") + +_GLOBAL_CONFIG = { + "SCIPY_ARRAY_API": SCIPY_ARRAY_API, + "SCIPY_DEVICE": SCIPY_DEVICE, +} + + +Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589) +ArrayLike: TypeAlias = Array | npt.ArrayLike + + +def _compliance_scipy(arrays): + """Raise exceptions on known-bad subclasses. + + 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 + - Any array-like which is neither array API compatible nor coercible by NumPy + - Any array-like which is coerced by NumPy to an unsupported dtype + """ + for i in range(len(arrays)): + array = arrays[i] + + from scipy.sparse import issparse + # this comes from `_util._asarray_validated` + if issparse(array): + 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 isinstance(array, np.ma.MaskedArray): + raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.") + elif isinstance(array, np.matrix): + raise TypeError("Inputs of type `numpy.matrix` are not supported.") + if isinstance(array, np.ndarray | np.generic): + dtype = array.dtype + if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)): + raise TypeError(f"An argument has dtype `{dtype!r}`; " + f"only boolean and numerical dtypes are supported.") + elif not is_array_api_obj(array): + try: + array = np.asanyarray(array) + except TypeError: + raise TypeError("An argument is neither array API compatible nor " + "coercible by NumPy.") + dtype = array.dtype + if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)): + message = ( + f"An argument was coerced to an unsupported dtype `{dtype!r}`; " + f"only boolean and numerical dtypes are supported." + ) + raise TypeError(message) + arrays[i] = array + return arrays + + +def _check_finite(array: Array, xp: ModuleType) -> None: + """Check for NaNs or Infs.""" + msg = "array must not contain infs or NaNs" + try: + if not xp.all(xp.isfinite(array)): + raise ValueError(msg) + except TypeError: + raise ValueError(msg) + + +def array_namespace(*arrays: Array) -> ModuleType: + """Get the array API compatible namespace for the arrays xs. + + Parameters + ---------- + *arrays : sequence of array_like + Arrays used to infer the common namespace. + + Returns + ------- + namespace : module + Common namespace. + + Notes + ----- + Thin wrapper around `array_api_compat.array_namespace`. + + 1. Check for the global switch: SCIPY_ARRAY_API. This can also be accessed + dynamically through ``_GLOBAL_CONFIG['SCIPY_ARRAY_API']``. + 2. `_compliance_scipy` raise exceptions on known-bad subclasses. See + its definition for more details. + + When the global switch is False, it defaults to the `numpy` namespace. + In that case, there is no compliance check. This is a convenience to + ease the adoption. Otherwise, arrays must comply with the new rules. + """ + if not _GLOBAL_CONFIG["SCIPY_ARRAY_API"]: + # here we could wrap the namespace if needed + return np_compat + + _arrays = [array for array in arrays if array is not None] + + _arrays = _compliance_scipy(_arrays) + + return array_api_compat.array_namespace(*_arrays) + + +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 _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 check_namespace: + _assert_matching_namespace(actual, desired) + + # 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: + _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 + + +def _assert_matching_namespace(actual, desired): + __tracebackhide__ = True # Hide traceback for py.test + actual = actual if isinstance(actual, tuple) else (actual,) + desired_space = array_namespace(desired) + for arr in actual: + arr_space = array_namespace(arr) + _msg = (f"Namespaces do not match.\n" + f"Actual: {arr_space.__name__}\n" + f"Desired: {desired_space.__name__}") + assert arr_space == desired_space, _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 + if xp is None: + xp = array_namespace(actual) + + actual, desired = _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 + if xp is None: + xp = array_namespace(actual) + + actual, desired = _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_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 + if xp is None: + xp = array_namespace(actual) + + actual, desired = _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_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 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_xp_devices(xp: ModuleType) -> list[str] | list[None]: + """Returns a list of available devices for the given namespace.""" + devices: list[str] = [] + if is_torch(xp): + devices += ['cpu'] + import torch # type: ignore[import] + num_cuda = torch.cuda.device_count() + for i in range(0, num_cuda): + devices += [f'cuda:{i}'] + if torch.backends.mps.is_available(): + devices += ['mps'] + return devices + elif is_cupy(xp): + import cupy # type: ignore[import] + num_cuda = cupy.cuda.runtime.getDeviceCount() + for i in range(0, num_cuda): + devices += [f'cuda:{i}'] + return devices + elif is_jax(xp): + import jax # type: ignore[import] + num_cpu = jax.device_count(backend='cpu') + for i in range(0, num_cpu): + devices += [f'cpu:{i}'] + num_gpu = jax.device_count(backend='gpu') + for i in range(0, num_gpu): + devices += [f'gpu:{i}'] + num_tpu = jax.device_count(backend='tpu') + for i in range(0, num_tpu): + devices += [f'tpu:{i}'] + return devices + + # given namespace is not known to have a list of available devices; + # return `[None]` so that one can use this in tests for `device=None`. + return [None] + + +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 + + +# temporary substitute for xp.moveaxis, which is not yet in all backends +# or covered by array_api_compat. +def xp_moveaxis_to_end( + x: Array, + source: int, + /, *, + xp: ModuleType | None = None) -> Array: + xp = array_namespace(xp) if xp is None else xp + axes = list(range(x.ndim)) + temp = axes.pop(source) + axes = axes + [temp] + return xp.permute_dims(x, axes) + + +# temporary substitute for xp.copysign, which is not yet in all backends +# or covered by array_api_compat. +def xp_copysign(x1: Array, x2: Array, /, *, xp: ModuleType | None = None) -> Array: + # no attempt to account for special cases + xp = array_namespace(x1, x2) if xp is None else xp + abs_x1 = xp.abs(x1) + return xp.where(x2 >= 0, abs_x1, -abs_x1) + + +# partial substitute for xp.sign, which does not cover the NaN special case +# that I need. (https://github.com/data-apis/array-api-compat/issues/136) +def xp_sign(x: Array, /, *, xp: ModuleType | None = None) -> Array: + xp = array_namespace(x) if xp is None else xp + if is_numpy(xp): # only NumPy implements the special cases correctly + return xp.sign(x) + sign = xp.zeros_like(x) + one = xp.asarray(1, dtype=x.dtype) + sign = xp.where(x > 0, one, sign) + sign = xp.where(x < 0, -one, sign) + sign = xp.where(xp.isnan(x), xp.nan*one, sign) + return sign + +# maybe use `scipy.linalg` if/when array API support is added +def xp_vector_norm(x: Array, /, *, + axis: int | tuple[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_real(x: Array, /, *, xp: ModuleType | None = None) -> Array: + # Convenience wrapper of xp.real that allows non-complex input; + # see data-apis/array-api#824 + xp = array_namespace(x) if xp is None else xp + return xp.real(x) if xp.isdtype(x.dtype, 'complex floating') else x + + +def xp_take_along_axis(arr: Array, + indices: Array, /, *, + axis: int = -1, + xp: ModuleType | None = None) -> Array: + # Dispatcher for np.take_along_axis for backends that support it; + # see data-apis/array-api/pull#816 + xp = array_namespace(arr) if xp is None else xp + if is_torch(xp): + return xp.take_along_dim(arr, indices, dim=axis) + elif is_array_api_strict(xp): + raise NotImplementedError("Array API standard does not define take_along_axis") + else: + return xp.take_along_axis(arr, indices, axis) + + +# utility to broadcast arrays and promote to common dtype +def xp_broadcast_promote(*args, ensure_writeable=False, force_floating=False, xp=None): + xp = array_namespace(*args) if xp is None else xp + + args = [(_asarray(arg, subok=True) if arg is not None else arg) for arg in args] + args_not_none = [arg for arg in args if arg is not None] + + # determine minimum dtype + default_float = xp.asarray(1.).dtype + dtypes = [arg.dtype for arg in args_not_none] + try: # follow library's prefered mixed promotion rules + dtype = xp.result_type(*dtypes) + if force_floating and xp.isdtype(dtype, 'integral'): + # If we were to add `default_float` before checking whether the result + # type is otherwise integral, we risk promotion from lower float. + dtype = xp.result_type(dtype, default_float) + except TypeError: # mixed type promotion isn't defined + float_dtypes = [dtype for dtype in dtypes + if not xp.isdtype(dtype, 'integral')] + if float_dtypes: + dtype = xp.result_type(*float_dtypes, default_float) + elif force_floating: + dtype = default_float + else: + dtype = xp.result_type(*dtypes) + + # 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) + + # convert dtype/copy only if needed + if (arg.dtype != dtype) or ensure_writeable: + arg = xp.astype(arg, dtype, copy=True) + out.append(arg) + + return 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 diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b6fe1affd172eea620760a20f185f192d37b69 --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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, *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) diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py new file mode 100644 index 0000000000000000000000000000000000000000..bb562e4348f46dc1137afe3d3ce50f1149c85376 --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py @@ -0,0 +1,225 @@ +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__, + } + 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py new file mode 100644 index 0000000000000000000000000000000000000000..1980d06f5489e6633fb611c35bfb56903bd63e7f --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py new file mode 100644 index 0000000000000000000000000000000000000000..683c5c8e518705e710212dafc01363f92a2f947d --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py @@ -0,0 +1,254 @@ +""" +Disjoint set data structure +""" + + +class DisjointSet: + """ Disjoint set data structure for incremental connectivity queries. + + .. versionadded:: 1.6.0 + + 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 + """ + 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py new file mode 100644 index 0000000000000000000000000000000000000000..f345539efe76b9f9439957a78e5ebdc1ec2bf517 --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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): + 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) \ No newline at end of file diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py new file mode 100644 index 0000000000000000000000000000000000000000..05efe86d31c137e7d780ebc438ec587df4e911dd --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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 + +_ESIGNERR = -1 +_ECONVERR = -2 +_EVALUEERR = -3 +_ECALLBACK = -4 +_EINPUTERR = -5 +_ECONVERGED = 0 +_EINPROGRESS = 1 + +def _initialize(func, xs, args, 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`. + 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 + + # 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. + xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename + xat = xp.result_type(*[xa.dtype for xa in xas]) + xat = xp.asarray(1.).dtype if xp.isdtype(xat, "integral") else xat + 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[:] = _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(): + # Need to find a better way than these try/excepts + # Somehow need to keep compressible numerical args separate + if key == 'args': + continue + try: + work[key] = val[proceed] + except (IndexError, TypeError, KeyError): # not a compressible array + work[key] = 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[active] = 1 + active_mask = active_mask & mask + for key, val in update_dict.items(): + try: + res[key][active_mask] = val[active_mask] + except (IndexError, TypeError, KeyError): + res[key][active_mask] = val + else: + active_mask = active[mask] + for key, val in update_dict.items(): + try: + res[key][active_mask] = val[mask] + except (IndexError, TypeError, KeyError): + res[key][active_mask] = val + else: + for key, val in update_dict.items(): + if preserve_shape: + try: + val = val[active] + except (IndexError, TypeError, KeyError): + pass + res[key][active] = 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py new file mode 100644 index 0000000000000000000000000000000000000000..506057b48b3f49244e1ed6cd755fad8ad43d8739 --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py @@ -0,0 +1,145 @@ +from numpy import arange, newaxis, hstack, prod, array + + +def _central_diff_weights(Np, ndiv=1): + """ + Return weights for an Np-point central derivative. + + Assumes equally-spaced function points. + + If weights are in the vector w, then + derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx) + + Parameters + ---------- + Np : int + Number of points for the central derivative. + ndiv : int, optional + Number of divisions. Default is 1. + + Returns + ------- + w : ndarray + Weights for an Np-point central derivative. Its size is `Np`. + + Notes + ----- + Can be inaccurate for a large number of points. + + Examples + -------- + We can calculate a derivative value of a function. + + >>> def f(x): + ... return 2 * x**2 + 3 + >>> x = 3.0 # derivative point + >>> h = 0.1 # differential step + >>> Np = 3 # point number for central derivative + >>> weights = _central_diff_weights(Np) # weights for first derivative + >>> vals = [f(x + (i - Np/2) * h) for i in range(Np)] + >>> sum(w * v for (w, v) in zip(weights, vals))/h + 11.79999999999998 + + This value is close to the analytical solution: + f'(x) = 4x, so f'(3) = 12 + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Finite_difference + + """ + if Np < ndiv + 1: + raise ValueError( + "Number of points must be at least the derivative order + 1." + ) + if Np % 2 == 0: + raise ValueError("The number of points must be odd.") + from scipy import linalg + + ho = Np >> 1 + x = arange(-ho, ho + 1.0) + x = x[:, newaxis] + X = x**0.0 + for k in range(1, Np): + X = hstack([X, x**k]) + w = prod(arange(1, ndiv + 1), axis=0) * linalg.inv(X)[ndiv] + return w + + +def _derivative(func, x0, dx=1.0, n=1, args=(), order=3): + """ + Find the nth derivative of a function at a point. + + Given a function, use a central difference formula with spacing `dx` to + compute the nth derivative at `x0`. + + Parameters + ---------- + func : function + Input function. + x0 : float + The point at which the nth derivative is found. + dx : float, optional + Spacing. + n : int, optional + Order of the derivative. Default is 1. + args : tuple, optional + Arguments + order : int, optional + Number of points to use, must be odd. + + Notes + ----- + Decreasing the step size too small can result in round-off error. + + Examples + -------- + >>> def f(x): + ... return x**3 + x**2 + >>> _derivative(f, 1.0, dx=1e-6) + 4.9999999999217337 + + """ + if order < n + 1: + raise ValueError( + "'order' (the number of points used to compute the derivative), " + "must be at least the derivative order 'n' + 1." + ) + if order % 2 == 0: + raise ValueError( + "'order' (the number of points used to compute the derivative) " + "must be odd." + ) + # pre-computed for n=1 and 2 and low-order for speed. + if n == 1: + if order == 3: + weights = array([-1, 0, 1]) / 2.0 + elif order == 5: + weights = array([1, -8, 0, 8, -1]) / 12.0 + elif order == 7: + weights = array([-1, 9, -45, 0, 45, -9, 1]) / 60.0 + elif order == 9: + weights = array([3, -32, 168, -672, 0, 672, -168, 32, -3]) / 840.0 + else: + weights = _central_diff_weights(order, 1) + elif n == 2: + if order == 3: + weights = array([1, -2.0, 1]) + elif order == 5: + weights = array([-1, 16, -30, 16, -1]) / 12.0 + elif order == 7: + weights = array([2, -27, 270, -490, 270, -27, 2]) / 180.0 + elif order == 9: + weights = ( + array([-9, 128, -1008, 8064, -14350, 8064, -1008, 128, -9]) + / 5040.0 + ) + else: + weights = _central_diff_weights(order, 2) + else: + weights = _central_diff_weights(order, n) + val = 0.0 + ho = order >> 1 + for k in range(order): + val += weights[k] * func(x0 + (k - ho) * dx, *args) + return val / prod((dx,) * n, axis=0) diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3a443899bde3481ed6c1359eff4ef9696f6c8e4d Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..854ae36228614f3eb8849e9f95abf0dd387b5d35 --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py @@ -0,0 +1,105 @@ +""" +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 +from platform import python_implementation + +__all__ = ['set_gc_state', 'gc_state', 'assert_deallocated'] + + +IS_PYPY = python_implementation() == 'PyPy' + + +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. + + This check is not available on PyPy. + + 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 + """ + if IS_PYPY: + raise RuntimeError("assert_deallocated is unavailable on PyPy") + + 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py new file mode 100644 index 0000000000000000000000000000000000000000..d546e32a0349461a0aab76bfb4636ebf25227ca0 --- /dev/null +++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py @@ -0,0 +1,487 @@ +"""Utility to compare pep440 compatible version strings. + +The LooseVersion and StrictVersion classes that distutils provides don't +work; they don't recognize anything like alpha/beta/rc/dev versions. +""" + +# Copyright (c) Donald Stufft and individual contributors. +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# 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 collections +import itertools +import re + + +__all__ = [ + "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN", +] + + +# BEGIN packaging/_structures.py + + +class Infinity: + def __repr__(self): + return "Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return False + + def __le__(self, other): + return False + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return True + + def __ge__(self, other): + return True + + def __neg__(self): + return NegativeInfinity + + +Infinity = Infinity() + + +class NegativeInfinity: + def __repr__(self): + return "-Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return True + + def __le__(self, other): + return True + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return False + + def __ge__(self, other): + return False + + def __neg__(self): + return Infinity + + +# BEGIN packaging/version.py + + +NegativeInfinity = NegativeInfinity() + +_Version = collections.namedtuple( + "_Version", + ["epoch", "release", "dev", "pre", "post", "local"], +) + + +def parse(version): + """ + Parse the given version string and return either a :class:`Version` object + or a :class:`LegacyVersion` object depending on if the given version is + a valid PEP 440 version or a legacy version. + """ + try: + return Version(version) + except InvalidVersion: + return LegacyVersion(version) + + +class InvalidVersion(ValueError): + """ + An invalid version was found, users should refer to PEP 440. + """ + + +class _BaseVersion: + + def __hash__(self): + return hash(self._key) + + def __lt__(self, other): + return self._compare(other, lambda s, o: s < o) + + def __le__(self, other): + return self._compare(other, lambda s, o: s <= o) + + def __eq__(self, other): + return self._compare(other, lambda s, o: s == o) + + def __ge__(self, other): + return self._compare(other, lambda s, o: s >= o) + + def __gt__(self, other): + return self._compare(other, lambda s, o: s > o) + + def __ne__(self, other): + return self._compare(other, lambda s, o: s != o) + + def _compare(self, other, method): + if not isinstance(other, _BaseVersion): + return NotImplemented + + return method(self._key, other._key) + + +class LegacyVersion(_BaseVersion): + + def __init__(self, version): + self._version = str(version) + self._key = _legacy_cmpkey(self._version) + + def __str__(self): + return self._version + + def __repr__(self): + return f"" + + @property + def public(self): + return self._version + + @property + def base_version(self): + return self._version + + @property + def local(self): + return None + + @property + def is_prerelease(self): + return False + + @property + def is_postrelease(self): + return False + + +_legacy_version_component_re = re.compile( + r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE, +) + +_legacy_version_replacement_map = { + "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@", +} + + +def _parse_version_parts(s): + for part in _legacy_version_component_re.split(s): + part = _legacy_version_replacement_map.get(part, part) + + if not part or part == ".": + continue + + if part[:1] in "0123456789": + # pad for numeric comparison + yield part.zfill(8) + else: + yield "*" + part + + # ensure that alpha/beta/candidate are before final + yield "*final" + + +def _legacy_cmpkey(version): + # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch + # greater than or equal to 0. This will effectively put the LegacyVersion, + # which uses the defacto standard originally implemented by setuptools, + # as before all PEP 440 versions. + epoch = -1 + + # This scheme is taken from pkg_resources.parse_version setuptools prior to + # its adoption of the packaging library. + parts = [] + for part in _parse_version_parts(version.lower()): + if part.startswith("*"): + # remove "-" before a prerelease tag + if part < "*final": + while parts and parts[-1] == "*final-": + parts.pop() + + # remove trailing zeros from each series of numeric parts + while parts and parts[-1] == "00000000": + parts.pop() + + parts.append(part) + parts = tuple(parts) + + return epoch, parts + + +# 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
+            [-_\.]?
+            (?P(a|b|c|rc|alpha|beta|pre|preview))
+            [-_\.]?
+            (?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
+"""
+
+
+class Version(_BaseVersion):
+
+    _regex = re.compile(
+        r"^\s*" + VERSION_PATTERN + r"\s*$",
+        re.VERBOSE | re.IGNORECASE,
+    )
+
+    def __init__(self, version):
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # 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):
+        return f""
+
+    def __str__(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append(f"{self._version.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        # Pre-release
+        if self._version.pre is not None:
+            parts.append("".join(str(x) for x in self._version.pre))
+
+        # Post-release
+        if self._version.post is not None:
+            parts.append(f".post{self._version.post[1]}")
+
+        # Development release
+        if self._version.dev is not None:
+            parts.append(f".dev{self._version.dev[1]}")
+
+        # Local version segment
+        if self._version.local is not None:
+            parts.append(
+                "+{}".format(".".join(str(x) for x in self._version.local))
+            )
+
+        return "".join(parts)
+
+    @property
+    def public(self):
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append(f"{self._version.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        return "".join(parts)
+
+    @property
+    def local(self):
+        version_string = str(self)
+        if "+" in version_string:
+            return version_string.split("+", 1)[1]
+
+    @property
+    def is_prerelease(self):
+        return bool(self._version.dev or self._version.pre)
+
+    @property
+    def is_postrelease(self):
+        return bool(self._version.post)
+
+
+def _parse_letter_version(letter, number):
+    if letter:
+        # We assume there is an implicit 0 in a pre-release if there is
+        # no 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)
+    if not letter and number:
+        # We assume that if we are given a number but not given a letter,
+        # then this is using the implicit post release syntax (e.g., 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+
+_local_version_seperators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local):
+    """
+    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_seperators.split(local)
+        )
+
+
+def _cmpkey(epoch, release, pre, post, dev, local):
+    # 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 no 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 = -Infinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        pre = Infinity
+
+    # Versions without a post-segment should sort before those with one.
+    if post is None:
+        post = -Infinity
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        dev = Infinity
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        local = -Infinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alphanumeric segments sort before numeric segments
+        # - Alphanumeric 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 (-Infinity, i)
+            for i in local
+        )
+
+    return epoch, release, pre, post, dev, local
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..3bd017197577d973e5c77c3c51ad966a015b890b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..34c0e024dcd5924c7287e6ce8105975c4d9ab7f5
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..60dc2423372bf2fb24dece8ab51b1f9b7f26d7eb
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8da7e403dec5de5cb7d9a98d8c69a2c49e377c6a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py
@@ -0,0 +1,369 @@
+"""
+Generic test utilities.
+
+"""
+
+import inspect
+import os
+import re
+import shutil
+import subprocess
+import sys
+import sysconfig
+import threading
+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._lib import _pep440
+    required_version = '3.0.8'
+    if _pep440.parse(cython_version) < _pep440.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:
+            pytest_args += list(extra_argv)
+
+        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 is equivalent to using a ThreadPoolExecutor, but using the threading
+    primitives instead. 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.
+
+    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()
+        fn(i, *args, **kwargs)
+
+    workers = []
+    for i in range(0, n_workers):
+        workers.append(threading.Thread(
+            target=closure,
+            args=(i,) + args, kwargs=kwargs))
+
+    for worker in workers:
+        worker.start()
+
+    for worker in workers:
+        worker.join()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py
new file mode 100644
index 0000000000000000000000000000000000000000..530339ec7075dafdb81e9fa0ff5447952af77497
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py
@@ -0,0 +1,58 @@
+import threading
+
+import scipy._lib.decorator
+
+
+__all__ = ['ReentrancyError', 'ReentrancyLock', 'non_reentrant']
+
+
+class ReentrancyError(RuntimeError):
+    pass
+
+
+class ReentrancyLock:
+    """
+    Threading lock that raises an exception for reentrant calls.
+
+    Calls from different threads are serialized, and nested calls from the
+    same thread result to an error.
+
+    The object can be used as a context manager or to decorate functions
+    via the decorate() method.
+
+    """
+
+    def __init__(self, err_msg):
+        self._rlock = threading.RLock()
+        self._entered = False
+        self._err_msg = err_msg
+
+    def __enter__(self):
+        self._rlock.acquire()
+        if self._entered:
+            self._rlock.release()
+            raise ReentrancyError(self._err_msg)
+        self._entered = True
+
+    def __exit__(self, type, value, traceback):
+        self._entered = False
+        self._rlock.release()
+
+    def decorate(self, func):
+        def caller(func, *a, **kw):
+            with self:
+                return func(*a, **kw)
+        return scipy._lib.decorator.decorate(func, caller)
+
+
+def non_reentrant(err_msg=None):
+    """
+    Decorate a function with a threading lock and prevent reentrant calls.
+    """
+    def decorator(func):
+        msg = err_msg
+        if msg is None:
+            msg = f"{func.__name__} is not re-entrant"
+        lock = ReentrancyLock(msg)
+        return lock.decorate(func)
+    return decorator
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f9fd546a9d2ae3e9a20c0684f79eb0b3d61ee92
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py
@@ -0,0 +1,86 @@
+''' Contexts for *with* statement providing temporary directories
+'''
+import os
+from contextlib import contextmanager
+from shutil import rmtree
+from tempfile import mkdtemp
+
+
+@contextmanager
+def tempdir():
+    """Create and return a temporary directory. This has the same
+    behavior as mkdtemp but can be used as a context manager.
+
+    Upon exiting the context, the directory and everything contained
+    in it are removed.
+
+    Examples
+    --------
+    >>> import os
+    >>> with tempdir() as tmpdir:
+    ...     fname = os.path.join(tmpdir, 'example_file.txt')
+    ...     with open(fname, 'wt') as fobj:
+    ...         _ = fobj.write('a string\\n')
+    >>> os.path.exists(tmpdir)
+    False
+    """
+    d = mkdtemp()
+    yield d
+    rmtree(d)
+
+
+@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
+    '''
+    pwd = os.getcwd()
+    d = mkdtemp()
+    os.chdir(d)
+    yield d
+    os.chdir(pwd)
+    rmtree(d)
+
+
+@contextmanager
+def in_dir(dir=None):
+    """ Change directory to given directory for duration of ``with`` block
+
+    Useful when you want to use `in_tempdir` for the final test, but
+    you are still debugging. For example, you may want to do this in the end:
+
+    >>> with in_tempdir() as tmpdir:
+    ...     # do something complicated which might break
+    ...     pass
+
+    But, indeed, the complicated thing does break, and meanwhile, the
+    ``in_tempdir`` context manager wiped out the directory with the
+    temporary files that you wanted for debugging. So, while debugging, you
+    replace with something like:
+
+    >>> with in_dir() as tmpdir: # Use working directory by default
+    ...     # do something complicated which might break
+    ...     pass
+
+    You can then look at the temporary file outputs to debug what is happening,
+    fix, and finally replace ``in_dir`` with ``in_tempdir`` again.
+    """
+    cwd = os.getcwd()
+    if dir is None:
+        yield cwd
+        return
+    os.chdir(dir)
+    yield dir
+    os.chdir(cwd)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..5f2b90a026aaecbdc090b3d3234954ab29fce8ae
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..91afdcedb180599a41758cdd8c03416cf6c20d76
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e596113e28e64ce2a48576c701cc4ef8d6df5804
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d17496bb51136069c73eba1881212a68c68fb00
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ea71965761ca6916485828ee23d3402bfb1b7d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_util.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d16072007395221fdf7a1f5352fd2838fd7a6ec
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/_util.py
@@ -0,0 +1,1179 @@
+import re
+from contextlib import contextmanager
+import functools
+import operator
+import warnings
+import numbers
+from collections import namedtuple
+import inspect
+import math
+from typing import TypeAlias, TypeVar
+
+import numpy as np
+from scipy._lib._array_api import array_namespace, is_numpy, xp_size
+from scipy._lib._docscrape import FunctionDoc, Parameter
+
+
+AxisError: type[Exception]
+ComplexWarning: type[Warning]
+VisibleDeprecationWarning: type[Warning]
+
+if np.lib.NumpyVersion(np.__version__) >= '1.25.0':
+    from numpy.exceptions import (
+        AxisError, ComplexWarning, VisibleDeprecationWarning,
+        DTypePromotionError
+    )
+else:
+    from numpy import (  # type: ignore[attr-defined, no-redef]
+        AxisError, ComplexWarning, VisibleDeprecationWarning  # noqa: F401
+    )
+    DTypePromotionError = TypeError  # type: ignore
+
+np_long: type
+np_ulong: type
+
+if np.lib.NumpyVersion(np.__version__) >= "2.0.0.dev0":
+    try:
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                r".*In the future `np\.long` will be defined as.*",
+                FutureWarning,
+            )
+            np_long = np.long  # type: ignore[attr-defined]
+            np_ulong = np.ulong  # type: ignore[attr-defined]
+    except AttributeError:
+            np_long = np.int_
+            np_ulong = np.uint
+else:
+    np_long = np.int_
+    np_ulong = np.uint
+
+IntNumber = int | np.integer
+DecimalNumber = float | np.floating | np.integer
+
+copy_if_needed: bool | None
+
+if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
+    copy_if_needed = None
+elif np.lib.NumpyVersion(np.__version__) < "1.28.0":
+    copy_if_needed = False
+else:
+    # 2.0.0 dev versions, handle cases where copy may or may not exist
+    try:
+        np.array([1]).__array__(copy=None)  # type: ignore[call-overload]
+        copy_if_needed = None
+    except TypeError:
+        copy_if_needed = False
+
+
+_RNG: TypeAlias = np.random.Generator | np.random.RandomState
+SeedType: TypeAlias = IntNumber | _RNG | None
+
+GeneratorType = TypeVar("GeneratorType", bound=_RNG)
+
+# Since Generator was introduced in numpy 1.17, the following condition is needed for
+# backward compatibility
+try:
+    from numpy.random import Generator as Generator
+except ImportError:
+    class Generator:  # type: ignore[no-redef]
+        pass
+
+
+def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
+    """Return elements chosen from two possibilities depending on a condition
+
+    Equivalent to ``f(*arrays) if cond else fillvalue`` performed elementwise.
+
+    Parameters
+    ----------
+    cond : array
+        The condition (expressed as a boolean array).
+    arrays : tuple of array
+        Arguments to `f` (and `f2`). Must be broadcastable with `cond`.
+    f : callable
+        Where `cond` is True, output will be ``f(arr1[cond], arr2[cond], ...)``
+    fillvalue : object
+        If provided, value with which to fill output array where `cond` is
+        not True.
+    f2 : callable
+        If provided, output will be ``f2(arr1[cond], arr2[cond], ...)`` where
+        `cond` is not True.
+
+    Returns
+    -------
+    out : array
+        An array with elements from the output of `f` where `cond` is True
+        and `fillvalue` (or elements from the output of `f2`) elsewhere. The
+        returned array has data type determined by Type Promotion Rules
+        with the output of `f` and `fillvalue` (or the output of `f2`).
+
+    Notes
+    -----
+    ``xp.where(cond, x, fillvalue)`` requires explicitly forming `x` even where
+    `cond` is False. This function evaluates ``f(arr1[cond], arr2[cond], ...)``
+    onle where `cond` ``is True.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
+    >>> def f(a, b):
+    ...     return a*b
+    >>> _lazywhere(a > 2, (a, b), f, np.nan)
+    array([ nan,  nan,  21.,  32.])
+
+    """
+    xp = array_namespace(cond, *arrays)
+
+    if (f2 is fillvalue is None) or (f2 is not None and fillvalue is not None):
+        raise ValueError("Exactly one of `fillvalue` or `f2` must be given.")
+
+    args = xp.broadcast_arrays(cond, *arrays)
+    bool_dtype = xp.asarray([True]).dtype  # numpy 1.xx doesn't have `bool`
+    cond, arrays = xp.astype(args[0], bool_dtype, copy=False), args[1:]
+
+    temp1 = xp.asarray(f(*(arr[cond] for arr in arrays)))
+
+    if f2 is None:
+        # If `fillvalue` is a Python scalar and we convert to `xp.asarray`, it gets the
+        # default `int` or `float` type of `xp`, so `result_type` could be wrong.
+        # `result_type` should/will handle mixed array/Python scalars;
+        # remove this special logic when it does.
+        if type(fillvalue) in {bool, int, float, complex}:
+            with np.errstate(invalid='ignore'):
+                dtype = (temp1 * fillvalue).dtype
+        else:
+           dtype = xp.result_type(temp1.dtype, fillvalue)
+        out = xp.full(cond.shape, dtype=dtype,
+                      fill_value=xp.asarray(fillvalue, dtype=dtype))
+    else:
+        ncond = ~cond
+        temp2 = xp.asarray(f2(*(arr[ncond] for arr in arrays)))
+        dtype = xp.result_type(temp1, temp2)
+        out = xp.empty(cond.shape, dtype=dtype)
+        out[ncond] = temp2
+
+    out[cond] = temp1
+
+    return out
+
+
+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 _aligned_zeros(shape, dtype=float, order="C", align=None):
+    """Allocate a new ndarray with aligned memory.
+
+    Primary use case for this currently is working around a f2py issue
+    in NumPy 1.9.1, where dtype.alignment is such that np.zeros() does
+    not necessarily create arrays aligned up to it.
+
+    """
+    dtype = np.dtype(dtype)
+    if align is None:
+        align = dtype.alignment
+    if not hasattr(shape, '__len__'):
+        shape = (shape,)
+    size = functools.reduce(operator.mul, shape) * dtype.itemsize
+    buf = np.empty(size + align + 1, np.uint8)
+    offset = buf.__array_interface__['data'][0] % align
+    if offset != 0:
+        offset = align - offset
+    # Note: slices producing 0-size arrays do not necessarily change
+    # data pointer --- so we use and allocate size+1
+    buf = buf[offset:offset+size+1][:-1]
+    data = np.ndarray(shape, dtype, buf, order=order)
+    data.fill(0)
+    return data
+
+
+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)
+
+        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]  # 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:
+        import scipy.sparse
+        if scipy.sparse.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 = 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 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 Pool
+            # user supplies a number
+            if int(pool) == -1:
+                # use as many processors as possible
+                self.pool = 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 = 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 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, 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
+
+
+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 _argmin(a, keepdims=False, axis=None):
+    """
+    argmin with a `keepdims` parameter.
+
+    See https://github.com/numpy/numpy/issues/8710
+
+    If axis is not None, a.shape[axis] must be greater than 0.
+    """
+    res = np.argmin(a, axis=axis)
+    if keepdims and axis is not None:
+        res = np.expand_dims(res, axis=axis)
+    return res
+
+
+def _first_nonnan(a, axis):
+    """
+    Return the first non-nan value along the given axis.
+
+    If a slice is all nan, nan is returned for that slice.
+
+    The shape of the return value corresponds to ``keepdims=True``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> nan = np.nan
+    >>> a = np.array([[ 3.,  3., nan,  3.],
+                      [ 1., nan,  2.,  4.],
+                      [nan, nan,  9., -1.],
+                      [nan,  5.,  4.,  3.],
+                      [ 2.,  2.,  2.,  2.],
+                      [nan, nan, nan, nan]])
+    >>> _first_nonnan(a, axis=0)
+    array([[3., 3., 2., 3.]])
+    >>> _first_nonnan(a, axis=1)
+    array([[ 3.],
+           [ 1.],
+           [ 9.],
+           [ 5.],
+           [ 2.],
+           [nan]])
+    """
+    k = _argmin(np.isnan(a), axis=axis, keepdims=True)
+    return np.take_along_axis(a, k, axis=axis)
+
+
+def _nan_allsame(a, axis, keepdims=False):
+    """
+    Determine if the values along an axis are all the same.
+
+    nan values are ignored.
+
+    `a` must be a numpy array.
+
+    `axis` is assumed to be normalized; that is, 0 <= axis < a.ndim.
+
+    For an axis of length 0, the result is True.  That is, we adopt the
+    convention that ``allsame([])`` is True. (There are no values in the
+    input that are different.)
+
+    `True` is returned for slices that are all nan--not because all the
+    values are the same, but because this is equivalent to ``allsame([])``.
+
+    Examples
+    --------
+    >>> from numpy import nan, array
+    >>> a = array([[ 3.,  3., nan,  3.],
+    ...            [ 1., nan,  2.,  4.],
+    ...            [nan, nan,  9., -1.],
+    ...            [nan,  5.,  4.,  3.],
+    ...            [ 2.,  2.,  2.,  2.],
+    ...            [nan, nan, nan, nan]])
+    >>> _nan_allsame(a, axis=1, keepdims=True)
+    array([[ True],
+           [False],
+           [False],
+           [False],
+           [ True],
+           [ True]])
+    """
+    if axis is None:
+        if a.size == 0:
+            return True
+        a = a.ravel()
+        axis = 0
+    else:
+        shp = a.shape
+        if shp[axis] == 0:
+            shp = shp[:axis] + (1,)*keepdims + shp[axis + 1:]
+            return np.full(shp, fill_value=True, dtype=bool)
+    a0 = _first_nonnan(a, axis=axis)
+    return ((a0 == a) | np.isnan(a)).all(axis=axis, keepdims=keepdims)
+
+
+def _contains_nan(a, nan_policy='propagate', policies=None, *,
+                  xp_omit_okay=False, xp=None):
+    # 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.
+    if xp is None:
+        xp = array_namespace(a)
+    not_numpy = not is_numpy(xp)
+
+    if policies is None:
+        policies = {'propagate', 'raise', 'omit'}
+    if nan_policy not in policies:
+        raise ValueError(f"nan_policy must be one of {set(policies)}.")
+
+    if xp_size(a) == 0:
+        contains_nan = False
+    elif 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
+        contains_nan = False
+
+    if contains_nan and nan_policy == 'raise':
+        raise ValueError("The input contains nan values")
+
+    if not xp_omit_okay and not_numpy and contains_nan and nan_policy=='omit':
+        message = "`nan_policy='omit' is incompatible with non-NumPy arrays."
+        raise ValueError(message)
+
+    return contains_nan, nan_policy
+
+
+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, xp=None):
+    xp = array_namespace(*data) if xp is None else xp
+    # Get NaN of appropriate dtype for data
+    data = [xp.asarray(item) for item in data]
+    try:
+        min_float = getattr(xp, 'float16', xp.float32)
+        dtype = xp.result_type(*data, min_float)  # must be at least a float
+    except DTypePromotionError:
+        # fallback to float64
+        dtype = xp.float64
+    return xp.asarray(xp.nan, dtype=dtype)[()]
+
+
+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
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..30b1d852db016240f06f8a6dfb163b2e3edafba0
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py
@@ -0,0 +1,22 @@
+"""
+NumPy Array API compatibility library
+
+This is a small wrapper around NumPy and CuPy that is 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.9.1'
+
+from .common import *  # noqa: F401, F403
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbb0470fcd0f01f716ac6b942647ed54a555109b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbe08bdcb4493d3ff8e388e763bd8c099baa7b45
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..170a1ff9e6459a8cd76f8f6f9b4bca1e894e9883
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py
@@ -0,0 +1,46 @@
+"""
+Internal helpers
+"""
+
+from functools import wraps
+from inspect import signature
+
+def get_xp(xp):
+    """
+    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):
+        @wraps(f)
+        def wrapped_f(*args, **kwargs):
+            return f(*args, xp=xp, **kwargs)
+
+        sig = signature(f)
+        new_sig = sig.replace(
+            parameters=[sig.parameters[i] for i in sig.parameters 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
+        return wrapped_f
+
+    return inner
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..91ab1c405e1d700e2bab5a87fc70196a34871e7d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py
@@ -0,0 +1 @@
+from ._helpers import * # noqa: F403
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..95255e9236f1da7a6b739cd70b7599cd0c35deec
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7f48b15d69d6b1997d3c486903a7ade646d6b65
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2a8bfd5f0b3429e5d60000d32cf076313209da3
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5901ed5725b62abf789750a01455a803f6375589
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bfed05463e7d35d0400843e815c96358ccc6fa2f
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a90f44424d81f25e54babb79b09fef7d1b05660
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
@@ -0,0 +1,555 @@
+"""
+These are functions that are just aliases of existing functions in NumPy.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Sequence, Tuple, Union
+    from ._typing import ndarray, Device, Dtype
+
+from typing import NamedTuple
+import inspect
+
+from ._helpers import array_namespace, _check_device, device, is_torch_array, is_cupy_namespace
+
+# These functions are modified from the NumPy versions.
+
+# Creation functions add the device keyword (which does nothing for NumPy)
+
+def arange(
+    start: Union[int, float],
+    /,
+    stop: Optional[Union[int, float]] = None,
+    step: Union[int, float] = 1,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.arange(start, stop=stop, step=step, dtype=dtype, **kwargs)
+
+def empty(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.empty(shape, dtype=dtype, **kwargs)
+
+def empty_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.empty_like(x, dtype=dtype, **kwargs)
+
+def eye(
+    n_rows: int,
+    n_cols: Optional[int] = None,
+    /,
+    *,
+    xp,
+    k: int = 0,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.eye(n_rows, M=n_cols, k=k, dtype=dtype, **kwargs)
+
+def full(
+    shape: Union[int, Tuple[int, ...]],
+    fill_value: Union[int, float],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.full(shape, fill_value, dtype=dtype, **kwargs)
+
+def full_like(
+    x: ndarray,
+    /,
+    fill_value: Union[int, float],
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.full_like(x, fill_value, dtype=dtype, **kwargs)
+
+def linspace(
+    start: Union[int, float],
+    stop: Union[int, float],
+    /,
+    num: int,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    endpoint: bool = True,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.linspace(start, stop, num, dtype=dtype, endpoint=endpoint, **kwargs)
+
+def ones(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.ones(shape, dtype=dtype, **kwargs)
+
+def ones_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.ones_like(x, dtype=dtype, **kwargs)
+
+def zeros(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.zeros(shape, dtype=dtype, **kwargs)
+
+def zeros_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _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: ndarray
+    indices: ndarray
+    inverse_indices: ndarray
+    counts: ndarray
+
+
+class UniqueCountsResult(NamedTuple):
+    values: ndarray
+    counts: ndarray
+
+
+class UniqueInverseResult(NamedTuple):
+    values: ndarray
+    inverse_indices: ndarray
+
+
+def _unique_kwargs(xp):
+    # 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: ndarray, /, xp) -> 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: ndarray, /, xp) -> 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: ndarray, /, xp) -> 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: ndarray, /, xp) -> ndarray:
+    kwargs = _unique_kwargs(xp)
+    return xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=False,
+        **kwargs,
+    )
+
+def astype(x: ndarray, dtype: Dtype, /, *, copy: bool = True) -> ndarray:
+    if not copy and dtype == x.dtype:
+        return x
+    return x.astype(dtype=dtype, copy=copy)
+
+# These functions have different keyword argument names
+
+def std(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    correction: Union[int, float] = 0.0, # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs,
+) -> ndarray:
+    return xp.std(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+def var(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    correction: Union[int, float] = 0.0, # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs,
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[int] = None,
+    dtype: Optional[Dtype] = None,
+    include_initial: bool = False,
+    **kwargs
+) -> ndarray:
+    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=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: ndarray,
+    /,
+    min: Optional[Union[int, float, ndarray]] = None,
+    max: Optional[Union[int, float, ndarray]] = None,
+    *,
+    xp,
+    # TODO: np.clip has other ufunc kwargs
+    out: Optional[ndarray] = None,
+) -> ndarray:
+    def _isscalar(a):
+        return isinstance(a, (int, float, type(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 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
+
+    if out is None:
+        out = wrapped_xp.asarray(xp.broadcast_to(x, result_shape),
+                                 copy=True, device=device(x))
+    if min is not None:
+        if is_torch_array(x) and x.dtype == xp.float64 and _isscalar(min):
+            # Avoid loss of precision due to torch defaulting to float32
+            min = wrapped_xp.asarray(min, dtype=xp.float64)
+        a = xp.broadcast_to(wrapped_xp.asarray(min, device=device(x)), result_shape)
+        ia = (out < a) | xp.isnan(a)
+        # torch requires an explicit cast here
+        out[ia] = wrapped_xp.astype(a[ia], out.dtype)
+    if max is not None:
+        if is_torch_array(x) and x.dtype == xp.float64 and _isscalar(max):
+            max = wrapped_xp.asarray(max, dtype=xp.float64)
+        b = xp.broadcast_to(wrapped_xp.asarray(max, device=device(x)), result_shape)
+        ib = (out > b) | xp.isnan(b)
+        out[ib] = wrapped_xp.astype(b[ib], out.dtype)
+    # Return a scalar for 0-D
+    return out[()]
+
+# Unlike transpose(), the axes argument to permute_dims() is required.
+def permute_dims(x: ndarray, /, axes: Tuple[int, ...], xp) -> ndarray:
+    return xp.transpose(x, axes)
+
+# np.reshape calls the keyword argument 'newshape' instead of 'shape'
+def reshape(x: ndarray,
+            /,
+            shape: Tuple[int, ...],
+            xp, copy: Optional[bool] = None,
+            **kwargs) -> ndarray:
+    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: ndarray, /, xp, *, axis: int = -1, descending: bool = False, stable: bool = True,
+    **kwargs,
+) -> ndarray:
+    # 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: ndarray, /, xp, *, axis: int = -1, descending: bool = False, stable: bool = True,
+    **kwargs,
+) -> ndarray:
+    # 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: ndarray, /, xp, **kwargs) -> Tuple[ndarray, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return xp.nonzero(x, **kwargs)
+
+# ceil, floor, and trunc return integers for integer inputs
+
+def ceil(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.ceil(x, **kwargs)
+
+def floor(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.floor(x, **kwargs)
+
+def trunc(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.trunc(x, **kwargs)
+
+# linear algebra functions
+
+def matmul(x1: ndarray, x2: ndarray, /, xp, **kwargs) -> ndarray:
+    return xp.matmul(x1, x2, **kwargs)
+
+# Unlike transpose, matrix_transpose only transposes the last two axes.
+def matrix_transpose(x: ndarray, /, xp) -> ndarray:
+    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: ndarray,
+              x2: ndarray,
+              /,
+              xp,
+              *,
+              axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2,
+              **kwargs,
+) -> ndarray:
+    return xp.tensordot(x1, x2, axes=axes, **kwargs)
+
+def vecdot(x1: ndarray, x2: ndarray, /, xp, *, axis: int = -1) -> ndarray:
+    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 = 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: Union[Dtype, str, Tuple[Union[Dtype, str], ...]], xp,
+    *, _tuple=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 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: ndarray, /, xp, *, axis: int = 0) -> Tuple[ndarray, ...]:
+    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: ndarray, /, xp, **kwargs) -> ndarray:
+    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 == 0+0j] = 0+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[()]
+
+__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',
+           'astype', 'std', 'var', 'cumulative_sum', 'clip', 'permute_dims',
+           'reshape', 'argsort', 'sort', 'nonzero', 'ceil', 'floor', 'trunc',
+           'matmul', 'matrix_transpose', 'tensordot', 'vecdot', 'isdtype',
+           'unstack', 'sign']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..666b0b1f84211052ac23be8a2a3009457b3b19d2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py
@@ -0,0 +1,183 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Union, Optional, Literal
+
+if TYPE_CHECKING:
+    from ._typing import Device, ndarray
+    from collections.abc import Sequence
+
+# Note: NumPy fft functions improperly upcast float32 and complex64 to
+# complex128, which is why we require wrapping them all here.
+
+def fft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    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, *, d: float = 1.0, device: Optional[Device] = None) -> ndarray:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    return xp.fft.fftfreq(n, d=d)
+
+def rfftfreq(n: int, /, xp, *, d: float = 1.0, device: Optional[Device] = None) -> ndarray:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    return xp.fft.rfftfreq(n, d=d)
+
+def fftshift(x: ndarray, /, xp, *, axes: Union[int, Sequence[int]] = None) -> ndarray:
+    return xp.fft.fftshift(x, axes=axes)
+
+def ifftshift(x: ndarray, /, xp, *, axes: Union[int, Sequence[int]] = None) -> ndarray:
+    return xp.fft.ifftshift(x, axes=axes)
+
+__all__ = [
+    "fft",
+    "ifft",
+    "fftn",
+    "ifftn",
+    "rfft",
+    "irfft",
+    "rfftn",
+    "irfftn",
+    "hfft",
+    "ihfft",
+    "fftfreq",
+    "rfftfreq",
+    "fftshift",
+    "ifftshift",
+]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..91056e249a30bf1d0f14341c31286d64dad0b676
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py
@@ -0,0 +1,825 @@
+"""
+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
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional, Union, Any
+    from ._typing import Array, Device
+
+import sys
+import math
+import inspect
+import warnings
+
+def _is_jax_zero_gradient_array(x):
+    """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.
+    """
+    if 'numpy' not in sys.modules or 'jax' not in sys.modules:
+        return False
+
+    import numpy as np
+    import jax
+
+    return isinstance(x, np.ndarray) and x.dtype == jax.float0
+
+def is_numpy_array(x):
+    """
+    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
+    """
+    # Avoid importing NumPy if it isn't already
+    if 'numpy' not in sys.modules:
+        return False
+
+    import numpy as np
+
+    # TODO: Should we reject ndarray subclasses?
+    return (isinstance(x, (np.ndarray, np.generic))
+            and not _is_jax_zero_gradient_array(x))
+
+def is_cupy_array(x):
+    """
+    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
+    """
+    # Avoid importing CuPy if it isn't already
+    if 'cupy' not in sys.modules:
+        return False
+
+    import cupy as cp
+
+    # TODO: Should we reject ndarray subclasses?
+    return isinstance(x, (cp.ndarray, cp.generic))
+
+def is_torch_array(x):
+    """
+    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
+    """
+    # Avoid importing torch if it isn't already
+    if 'torch' not in sys.modules:
+        return False
+
+    import torch
+
+    # TODO: Should we reject ndarray subclasses?
+    return isinstance(x, torch.Tensor)
+
+def is_ndonnx_array(x):
+    """
+    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
+    """
+    # Avoid importing torch if it isn't already
+    if 'ndonnx' not in sys.modules:
+        return False
+
+    import ndonnx as ndx
+
+    return isinstance(x, ndx.Array)
+
+def is_dask_array(x):
+    """
+    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
+    """
+    # Avoid importing dask if it isn't already
+    if 'dask.array' not in sys.modules:
+        return False
+
+    import dask.array
+
+    return isinstance(x, dask.array.Array)
+
+def is_jax_array(x):
+    """
+    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
+    """
+    # Avoid importing jax if it isn't already
+    if 'jax' not in sys.modules:
+        return False
+
+    import jax
+
+    return isinstance(x, jax.Array) or _is_jax_zero_gradient_array(x)
+
+def is_pydata_sparse_array(x) -> bool:
+    """
+    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
+    """
+    # Avoid importing jax if it isn't already
+    if 'sparse' not in sys.modules:
+        return False
+
+    import sparse
+
+    # TODO: Account for other backends.
+    return isinstance(x, sparse.SparseArray)
+
+def is_array_api_obj(x):
+    """
+    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 is_numpy_array(x) \
+        or is_cupy_array(x) \
+        or is_torch_array(x) \
+        or is_dask_array(x) \
+        or is_jax_array(x) \
+        or is_pydata_sparse_array(x) \
+        or hasattr(x, '__array_namespace__')
+
+def _compat_module_name():
+    assert __name__.endswith('.common._helpers')
+    return __name__.removesuffix('.common._helpers')
+
+def is_numpy_namespace(xp) -> 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'}
+
+def is_cupy_namespace(xp) -> 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'}
+
+def is_torch_namespace(xp) -> 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):
+    """
+    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'
+
+def is_dask_namespace(xp):
+    """
+    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):
+    """
+    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):
+    """
+    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):
+    """
+    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):
+    if api_version in ['2021.12', '2022.12']:
+        warnings.warn(f"The {api_version} version of the array API specification was requested but the returned namespace is actually version 2023.12")
+    elif api_version is not None and api_version not in ['2021.12', '2022.12',
+                                                         '2023.12']:
+        raise ValueError("Only the 2023.12 version of the array API specification is currently supported")
+
+def array_namespace(*xs, api_version=None, use_compat=None):
+    """
+    Get the array API compatible namespace for the arrays `xs`.
+
+    Parameters
+    ----------
+    xs: arrays
+        one or more arrays.
+
+    api_version: str
+        The newest version of the spec that you need support for (currently
+        the compat library wrapped APIs support v2023.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
+
+    """
+    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]
+
+    namespaces = set()
+    for x in xs:
+        if is_numpy_array(x):
+            from .. import numpy as numpy_namespace
+            import numpy as np
+            if use_compat is True:
+                _check_api_version(api_version)
+                namespaces.add(numpy_namespace)
+            elif use_compat is False:
+                namespaces.add(np)
+            else:
+                # numpy 2.0+ have __array_namespace__, however, they are not yet fully array API
+                # compatible.
+                namespaces.add(numpy_namespace)
+        elif is_cupy_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from .. import cupy as cupy_namespace
+                namespaces.add(cupy_namespace)
+            else:
+                import cupy as cp
+                namespaces.add(cp)
+        elif is_torch_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from .. import torch as torch_namespace
+                namespaces.add(torch_namespace)
+            else:
+                import torch
+                namespaces.add(torch)
+        elif is_dask_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from ..dask import array as dask_namespace
+                namespaces.add(dask_namespace)
+            else:
+                import dask.array as da
+                namespaces.add(da)
+        elif is_jax_array(x):
+            if use_compat is True:
+                _check_api_version(api_version)
+                raise ValueError("JAX does not have an array-api-compat wrapper")
+            elif use_compat is False:
+                import jax.numpy as jnp
+            else:
+                # 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.
+                import jax.numpy
+                if hasattr(jax.numpy, "__array_api_version__"):
+                    jnp = jax.numpy
+                else:
+                    import jax.experimental.array_api as jnp
+            namespaces.add(jnp)
+        elif is_pydata_sparse_array(x):
+            if use_compat is True:
+                _check_api_version(api_version)
+                raise ValueError("`sparse` does not have an array-api-compat wrapper")
+            else:
+                import sparse
+            # `sparse` is already an array namespace. We do not have a wrapper
+            # submodule for it.
+            namespaces.add(sparse)
+        elif hasattr(x, '__array_namespace__'):
+            if use_compat is True:
+                raise ValueError("The given array does not have an array-api-compat wrapper")
+            namespaces.add(x.__array_namespace__(api_version=api_version))
+        else:
+            # TODO: Support Python scalars?
+            raise TypeError(f"{type(x).__name__} is not a supported array type")
+
+    if not namespaces:
+        raise TypeError("Unrecognized array input")
+
+    if len(namespaces) != 1:
+        raise TypeError(f"Multiple namespaces for array inputs: {namespaces}")
+
+    xp, = namespaces
+
+    return xp
+
+# backwards compatibility alias
+get_namespace = array_namespace
+
+def _check_device(xp, device):
+    if xp == sys.modules.get('numpy'):
+        if device not in ["cpu", None]:
+            raise ValueError(f"Unsupported device for NumPy: {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):
+        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: Array, /) -> 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 jax array to determine type
+        try:
+            import numpy as np
+            if isinstance(x._meta, np.ndarray):
+                # Must be on CPU since backed by numpy
+                return "cpu"
+        except ImportError:
+            pass
+        return _DASK_DEVICE
+    elif is_jax_array(x):
+        # JAX has .device() as a method, but it is being deprecated so that it
+        # can become a property, in accordance with the standard. In order for
+        # this function to not break when JAX makes the flip, we check for
+        # both here.
+        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
+        except AttributeError:
+            return "cpu"
+        # Return the device of the constituent array
+        return device(inner)
+    return x.device
+
+# Prevent shadowing, used below
+_device = device
+
+# Based on cupy.array_api.Array.to_device
+def _cupy_to_device(x, device, /, stream=None):
+    import cupy as cp
+    from cupy.cuda import Device as _Device
+    from cupy.cuda import stream as stream_module
+    from cupy_backends.cuda.api import runtime
+
+    if device == x.device:
+        return x
+    elif device == "cpu":
+        # allowing us to use `to_device(x, "cpu")`
+        # is useful for portable test swapping between
+        # host and device backends
+        return x.get()
+    elif not isinstance(device, _Device):
+        raise ValueError(f"Unsupported device {device!r}")
+    else:
+        # see cupy/cupy#5985 for the reason how we handle device/stream here
+        prev_device = runtime.getDevice()
+        prev_stream: stream_module.Stream = None
+        if stream is not None:
+            prev_stream = stream_module.get_current_stream()
+            # stream can be an int as specified in __dlpack__, or a CuPy stream
+            if isinstance(stream, int):
+                stream = cp.cuda.ExternalStream(stream)
+            elif isinstance(stream, cp.cuda.Stream):
+                pass
+            else:
+                raise ValueError('the input stream is not recognized')
+            stream.use()
+        try:
+            runtime.setDevice(device.id)
+            arr = x.copy()
+        finally:
+            runtime.setDevice(prev_device)
+            if stream is not None:
+                prev_stream.use()
+        return arr
+
+def _torch_to_device(x, device, /, stream=None):
+    if stream is not None:
+        raise NotImplementedError
+    return x.to(device)
+
+def to_device(x: Array, device: Device, /, *, stream: Optional[Union[int, Any]] = 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: Optional[Union[int, Any]]
+        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
+        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)
+
+def size(x):
+    """
+    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 `.
+
+    """
+    if None in x.shape:
+        return None
+    return math.prod(x.shape)
+
+__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",
+    "size",
+    "to_device",
+]
+
+_all_ignore = ['sys', 'math', 'inspect', 'warnings']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfa1f1b937fddc5c2f95ef3a22850403ffd4b955
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, NamedTuple
+if TYPE_CHECKING:
+    from typing import Literal, Optional, Tuple, Union
+    from ._typing import ndarray
+
+import math
+
+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
+
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot, isdtype
+from .._internal import get_xp
+
+# These are in the main NumPy namespace but not in numpy.linalg
+def cross(x1: ndarray, x2: ndarray, /, xp, *, axis: int = -1, **kwargs) -> ndarray:
+    return xp.cross(x1, x2, axis=axis, **kwargs)
+
+def outer(x1: ndarray, x2: ndarray, /, xp, **kwargs) -> ndarray:
+    return xp.outer(x1, x2, **kwargs)
+
+class EighResult(NamedTuple):
+    eigenvalues: ndarray
+    eigenvectors: ndarray
+
+class QRResult(NamedTuple):
+    Q: ndarray
+    R: ndarray
+
+class SlogdetResult(NamedTuple):
+    sign: ndarray
+    logabsdet: ndarray
+
+class SVDResult(NamedTuple):
+    U: ndarray
+    S: ndarray
+    Vh: ndarray
+
+# These functions are the same as their NumPy counterparts except they return
+# a namedtuple.
+def eigh(x: ndarray, /, xp, **kwargs) -> EighResult:
+    return EighResult(*xp.linalg.eigh(x, **kwargs))
+
+def qr(x: ndarray, /, xp, *, mode: Literal['reduced', 'complete'] = 'reduced',
+       **kwargs) -> QRResult:
+    return QRResult(*xp.linalg.qr(x, mode=mode, **kwargs))
+
+def slogdet(x: ndarray, /, xp, **kwargs) -> SlogdetResult:
+    return SlogdetResult(*xp.linalg.slogdet(x, **kwargs))
+
+def svd(x: ndarray, /, xp, *, full_matrices: bool = True, **kwargs) -> 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: ndarray, /, xp, *, upper: bool = False, **kwargs) -> ndarray:
+    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)
+        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: ndarray,
+                /,
+                xp,
+                *,
+                rtol: Optional[Union[float, ndarray]] = None,
+                **kwargs) -> ndarray:
+    # 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 = 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: ndarray, /, xp, *, rtol: Optional[Union[float, ndarray]] = None, **kwargs) -> ndarray:
+    # 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: ndarray, /, xp, *, keepdims: bool = False, ord: Optional[Union[int, float, Literal['fro', 'nuc']]] = 'fro') -> ndarray:
+    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: ndarray, /, xp) -> Union[ndarray, Tuple[ndarray, ...]]:
+    return xp.linalg.svd(x, compute_uv=False)
+
+def vector_norm(x: ndarray, /, xp, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> ndarray:
+    # 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 = normalize_axis_tuple(axis, x.ndim)
+        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)
+        _axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim)
+        for i in _axis:
+            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: ndarray, /, xp, *, offset: int = 0, **kwargs) -> ndarray:
+    return xp.diagonal(x, offset=offset, axis1=-2, axis2=-1, **kwargs)
+
+def trace(x: ndarray, /, xp, *, offset: int = 0, dtype=None, **kwargs) -> ndarray:
+    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']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..07f3850d21fade94814f9fe1e638286c72a1c552
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+__all__ = [
+    "NestedSequence",
+    "SupportsBufferProtocol",
+]
+
+from typing import (
+    Any,
+    TypeVar,
+    Protocol,
+)
+
+_T_co = TypeVar("_T_co", covariant=True)
+
+class NestedSequence(Protocol[_T_co]):
+    def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ...
+    def __len__(self, /) -> int: ...
+
+SupportsBufferProtocol = Any
+
+Array = Any
+Device = Any
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d86857618458bf422e7f16dab302b179e5d520d8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py
@@ -0,0 +1,16 @@
+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
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+
+__import__(__package__ + '.fft')
+
+from ..common._helpers import * # noqa: F401,F403
+
+__array_api_version__ = '2023.12'
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..3627fb6b97820c292c86d26b9aabcefd899cfed1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py
@@ -0,0 +1,136 @@
+from __future__ import annotations
+
+import cupy as cp
+
+from ..common import _aliases
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+    from ._typing import ndarray, Device, Dtype, NestedSequence, SupportsBufferProtocol
+
+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)
+astype = _aliases.astype
+std = get_xp(cp)(_aliases.std)
+var = get_xp(cp)(_aliases.var)
+cumulative_sum = get_xp(cp)(_aliases.cumulative_sum)
+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)
+ceil = get_xp(cp)(_aliases.ceil)
+floor = get_xp(cp)(_aliases.floor)
+trunc = get_xp(cp)(_aliases.trunc)
+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)
+
+_copy_default = object()
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: Union[
+        ndarray,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: Optional[bool] = _copy_default,
+    **kwargs,
+) -> ndarray:
+    """
+    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):
+        # cupy is like NumPy 1.26 (except without _CopyMode). See the comments
+        # in asarray in numpy/_aliases.py.
+        if copy is not _copy_default:
+            # A future version of CuPy will change the meaning of copy=False
+            # to mean no-copy. We don't know for certain what version it will
+            # be yet, so to avoid breaking that version, we use a different
+            # default value for copy so asarray(obj) with no copy kwarg will
+            # always do the copy-if-needed behavior.
+
+            # This will still need to be updated to remove the
+            # NotImplementedError for copy=False, but at least this won't
+            # break the default or existing behavior.
+            if copy is None:
+                copy = False
+            elif copy is False:
+                raise NotImplementedError("asarray(copy=False) is not yet supported in cupy")
+            kwargs['copy'] = copy
+
+        return cp.array(obj, dtype=dtype, **kwargs)
+
+# 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__ + ['__array_namespace_info__', 'asarray', 'bool',
+                              'acos', 'acosh', 'asin', 'asinh', 'atan',
+                              'atan2', 'atanh', 'bitwise_left_shift',
+                              'bitwise_invert', 'bitwise_right_shift',
+                              'concat', 'pow', 'sign']
+
+_all_ignore = ['cp', 'get_xp']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..4440807d2240fb4125229b68a4af8b562b636753
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py
@@ -0,0 +1,326 @@
+"""
+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 = np.__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}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 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 : str
+            The default device used for new CuPy arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        Device(0)
+
+        """
+        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 of str
+            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 [cuda.Device(i) for i in range(cuda.runtime.getDeviceCount())]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3d9aab67e52f3300cd96c3d0e701d1604eaccbb
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+__all__ = [
+    "ndarray",
+    "Device",
+    "Dtype",
+]
+
+import sys
+from typing import (
+    Union,
+    TYPE_CHECKING,
+)
+
+from cupy import (
+    ndarray,
+    dtype,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+)
+
+from cupy.cuda.device import Device
+
+if TYPE_CHECKING or sys.version_info >= (3, 9):
+    Dtype = dtype[Union[
+        int8,
+        int16,
+        int32,
+        int64,
+        uint8,
+        uint16,
+        uint32,
+        uint64,
+        float32,
+        float64,
+    ]]
+else:
+    Dtype = dtype
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/fft.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..307e0f7277710693063ef8c4d2cd7893275ad44a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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 = {}
+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__
+
+del get_xp
+del cp
+del fft_all
+del _fft
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fcdd498e0073ada094a20a9ae423e01cb0f8ceb
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py
@@ -0,0 +1,49 @@
+from cupy.linalg import * # noqa: F403
+# cupy.linalg doesn't have __all__. If it is added, replace this with
+#
+# from cupy.linalg import __all__ as linalg_all
+_n = {}
+exec('from cupy.linalg import *', _n)
+del _n['__builtins__']
+linalg_all = list(_n)
+del _n
+
+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__
+
+del get_xp
+del cp
+del linalg_all
+del _linalg
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b49be6cf38f1d905c75278fdb857692f11adcdea
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py
@@ -0,0 +1,9 @@
+from dask.array import * # noqa: F403
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+__array_api_version__ = '2023.12'
+
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee2d88c048b29f603e54818319cb7f7163d43b36
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py
@@ -0,0 +1,217 @@
+from __future__ import annotations
+
+from ...common import _aliases
+from ...common._helpers import _check_device
+
+from ..._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+import numpy as np
+from numpy import (
+    # Dtypes
+    iinfo,
+    finfo,
+    bool_ as bool,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    complex64,
+    complex128,
+    can_cast,
+    result_type,
+)
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+
+    from ...common._typing import Device, Dtype, Array, NestedSequence, SupportsBufferProtocol
+
+import dask.array as da
+
+isdtype = get_xp(np)(_aliases.isdtype)
+unstack = get_xp(da)(_aliases.unstack)
+astype = _aliases.astype
+
+# 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
+
+# TODO: delete the xp stuff, it shouldn't be necessary
+def _dask_arange(
+    start: Union[int, float],
+    /,
+    stop: Optional[Union[int, float]] = None,
+    step: Union[int, float] = 1,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> Array:
+    _check_device(xp, device)
+    args = [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 xp.arange(*args, dtype=dtype, **kwargs)
+
+arange = get_xp(da)(_dask_arange)
+eye = get_xp(da)(_aliases.eye)
+
+linspace = get_xp(da)(_aliases.linspace)
+eye = get_xp(da)(_aliases.eye)
+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)
+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)
+ceil = get_xp(np)(_aliases.ceil)
+floor = get_xp(np)(_aliases.floor)
+trunc = get_xp(np)(_aliases.trunc)
+matmul = get_xp(np)(_aliases.matmul)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: Union[
+        Array,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: "Optional[Union[bool, np._CopyMode]]" = None,
+    **kwargs,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    if copy is False:
+        # copy=False is not yet implemented in dask
+        raise NotImplementedError("copy=False is not yet implemented")
+    elif copy is True:
+        if isinstance(obj, da.Array) and dtype is None:
+            return obj.copy()
+        # Go through numpy, since dask copy is no-op by default
+        obj = np.array(obj, dtype=dtype, copy=True)
+        return da.array(obj, dtype=dtype)
+    else:
+        if not isinstance(obj, da.Array) or dtype is not None and obj.dtype != dtype:
+            obj = np.asarray(obj, dtype=dtype)
+            return da.from_array(obj)
+        return obj
+
+    return da.asarray(obj, dtype=dtype, **kwargs)
+
+from dask.array import (
+    # Element wise aliases
+    arccos as acos,
+    arccosh as acosh,
+    arcsin as asin,
+    arcsinh as asinh,
+    arctan as atan,
+    arctan2 as atan2,
+    arctanh as atanh,
+    left_shift as bitwise_left_shift,
+    right_shift as bitwise_right_shift,
+    invert as bitwise_invert,
+    power as pow,
+    # Other
+    concatenate as concat,
+)
+
+# 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).
+@get_xp(da)
+def clip(
+    x: Array,
+    /,
+    min: Optional[Union[int, float, Array]] = None,
+    max: Optional[Union[int, float, Array]] = None,
+    *,
+    xp,
+) -> Array:
+    def _isscalar(a):
+        return isinstance(a, (int, float, type(None)))
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    # TODO: This won't handle dask unknown shapes
+    import numpy as np
+    result_shape = np.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    if min is not None:
+        min = xp.broadcast_to(xp.asarray(min), result_shape)
+    if max is not None:
+        max = xp.broadcast_to(xp.asarray(max), result_shape)
+
+    if min is None and max is None:
+        return xp.positive(x)
+
+    if min is None:
+        return astype(xp.minimum(x, max), x.dtype)
+    if max is None:
+        return astype(xp.maximum(x, min), x.dtype)
+
+    return astype(xp.minimum(xp.maximum(x, min), max), x.dtype)
+
+# exclude these from all since dask.array has no sorting functions
+_da_unsupported = ['sort', 'argsort']
+
+_common_aliases = [alias for alias in _aliases.__all__ if alias not in _da_unsupported]
+
+__all__ = _common_aliases + ['__array_namespace_info__', 'asarray', 'acos',
+                    'acosh', 'asin', 'asinh', 'atan', 'atan2',
+                    'atanh', 'bitwise_left_shift', 'bitwise_invert',
+                    'bitwise_right_shift', 'concat', 'pow', 'iinfo', 'finfo', 'can_cast',
+                    'result_type', 'bool', 'float32', 'float64', 'int8', 'int16', 'int32', 'int64',
+                    'uint8', 'uint16', 'uint32', 'uint64',
+                    'complex64', 'complex128', 'iinfo', 'finfo',
+                    'can_cast', 'result_type']
+
+_all_ignore = ["get_xp", "da", "np"]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3b12dc960f5a7a5d5a8dfb3345c0ad1f4d470e7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py
@@ -0,0 +1,345 @@
+"""
+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 numpy import (
+    dtype,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+from ...common._helpers import _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 = np.__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):
+        """
+        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 ``False`` for Dask.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``False`` for
+          Dask.
+
+        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}
+
+        """
+        return {
+            "boolean indexing": False,
+            "data-dependent shapes": False,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        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 : str
+            The default device used for new Dask arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(self, *, device=None):
+        """
+        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 = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': dask.float64,
+         'complex floating': dask.complex128,
+         'integral': dask.int64,
+         'indexing': dask.int64}
+
+        """
+        if device not in ["cpu", _DASK_DEVICE, None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" or _DASK_DEVICE 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=None, kind=None):
+        """
+        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 = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': dask.int8,
+         'int16': dask.int16,
+         'int32': dask.int32,
+         'int64': dask.int64}
+
+        """
+        if device not in ["cpu", _DASK_DEVICE, None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" or _DASK_DEVICE 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": 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 Dask.
+
+        For Dask, this always returns ``['cpu', DASK_DEVICE]``.
+
+        Returns
+        -------
+        devices : list of str
+            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 = np.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu', DASK_DEVICE]
+
+        """
+        return ["cpu", _DASK_DEVICE]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..aebd86f7b201d9eb7cd707b25ab3fae117f2d6e5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py
@@ -0,0 +1,24 @@
+from dask.array.fft import * # noqa: F403
+# dask.array.fft doesn't have __all__. If it is added, replace this with
+#
+# from dask.array.fft import __all__ as linalg_all
+_n = {}
+exec('from dask.array.fft import *', _n)
+del _n['__builtins__']
+fft_all = list(_n)
+del _n
+
+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__ = [elem for elem in fft_all if elem != "annotations"] + ["fftfreq", "rfftfreq"]
+
+del get_xp
+del da
+del fft_all
+del _fft
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..49c26d8b819f88e226e34e02947a1ecf50c4895e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from ...common import _linalg
+from ..._internal import get_xp
+
+# Exports
+from dask.array.linalg import * # noqa: F403
+from dask.array import outer
+
+# These functions are in both the main and linalg namespaces
+from dask.array import matmul, tensordot
+from ._aliases import matrix_transpose, vecdot
+
+import dask.array as da
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from ...common._typing import Array
+    from typing import Literal
+
+# dask.array.linalg doesn't have __all__. If it is added, replace this with
+#
+# from dask.array.linalg import __all__ as linalg_all
+_n = {}
+exec('from dask.array.linalg import *', _n)
+del _n['__builtins__']
+if 'annotations' in _n:
+    del _n['annotations']
+linalg_all = list(_n)
+del _n
+
+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(x: Array, mode: Literal['reduced', 'complete'] = 'reduced',
+       **kwargs) -> 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) -> SVDResult:
+    if full_matrices:
+        raise ValueError("full_matrics=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__ = linalg_all + ["trace", "outer", "matmul", "tensordot",
+                        "matrix_transpose", "vecdot", "EighResult",
+                        "QRResult", "SlogdetResult", "SVDResult", "qr",
+                        "cholesky", "matrix_rank", "matrix_norm", "svdvals",
+                        "vector_norm", "diagonal"]
+
+_all_ignore = ['get_xp', 'da', 'linalg_all']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bdbf31293d480f8a8a266dd096e6aa92e1cc48e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py
@@ -0,0 +1,30 @@
+from numpy import * # noqa: F403
+
+# from numpy import * doesn't overwrite these builtin names
+from numpy import abs, max, min, round # noqa: F401
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# 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 # noqa: F401
+
+from ..common._helpers import * # noqa: F403
+
+try:
+    # Used in asarray(). Not present in older versions.
+    from numpy import _CopyMode # noqa: F401
+except ImportError:
+    pass
+
+__array_api_version__ = '2023.12'
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fcf4f88fcc60504f8d83f3ea5bc4757c29d23179
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0473eac96a03877fa77d3aa44652fd30333ee4dd
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b64e3a60ae850e69f005b37eb0c159254fe27442
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3fe3677f5df9117a5ae0fe5a8f446310b352378
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71492ee04ceca357b2661fdf9a2f3ba28ec2f715
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bfc98ff7ba4082a3986652b85dc15fdd85350ad
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+from ..common import _aliases
+
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+    from ._typing import ndarray, Device, Dtype, NestedSequence, SupportsBufferProtocol
+
+import numpy as np
+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)
+astype = _aliases.astype
+std = get_xp(np)(_aliases.std)
+var = get_xp(np)(_aliases.var)
+cumulative_sum = get_xp(np)(_aliases.cumulative_sum)
+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)
+ceil = get_xp(np)(_aliases.ceil)
+floor = get_xp(np)(_aliases.floor)
+trunc = get_xp(np)(_aliases.trunc)
+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)
+
+def _supports_buffer_protocol(obj):
+    try:
+        memoryview(obj)
+    except TypeError:
+        return False
+    return True
+
+# 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: Union[
+        ndarray,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: "Optional[Union[bool, np._CopyMode]]" = None,
+    **kwargs,
+) -> ndarray:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device for NumPy: {device!r}")
+
+    if hasattr(np, '_CopyMode'):
+        if copy is None:
+            copy = np._CopyMode.IF_NEEDED
+        elif copy is False:
+            copy = np._CopyMode.NEVER
+        elif copy is True:
+            copy = np._CopyMode.ALWAYS
+    else:
+        # Not present in older NumPys. In this case, we cannot really support
+        # copy=False.
+        if copy is False:
+            raise NotImplementedError("asarray(copy=False) requires a newer version of NumPy.")
+
+    return np.array(obj, copy=copy, dtype=dtype, **kwargs)
+
+# 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)
+
+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__ + ['__array_namespace_info__', 'asarray', 'bool',
+                              'acos', 'acosh', 'asin', 'asinh', 'atan',
+                              'atan2', 'atanh', 'bitwise_left_shift',
+                              'bitwise_invert', 'bitwise_right_shift',
+                              'concat', 'pow']
+
+_all_ignore = ['np', 'get_xp']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..62f7ae62ca242cc17def5703b4412823aa31abcd
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py
@@ -0,0 +1,346 @@
+"""
+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 numpy import (
+    dtype,
+    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 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}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 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 : str
+            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=None):
+        """
+        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=None, kind=None):
+        """
+        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": 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 NumPy.
+
+        For NumPy, this always returns ``['cpu']``.
+
+        Returns
+        -------
+        devices : list of str
+            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"]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5ebb5abb987572be625ee864a37e61126d36d8b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+__all__ = [
+    "ndarray",
+    "Device",
+    "Dtype",
+]
+
+import sys
+from typing import (
+    Literal,
+    Union,
+    TYPE_CHECKING,
+)
+
+from numpy import (
+    ndarray,
+    dtype,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+)
+
+Device = Literal["cpu"]
+if TYPE_CHECKING or sys.version_info >= (3, 9):
+    Dtype = dtype[Union[
+        int8,
+        int16,
+        int32,
+        int64,
+        uint8,
+        uint16,
+        uint32,
+        uint64,
+        float32,
+        float64,
+    ]]
+else:
+    Dtype = dtype
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..286675946e0fbb0aa18105d25db08ebbbd2e4d0c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py
@@ -0,0 +1,29 @@
+from numpy.fft import * # noqa: F403
+from numpy.fft import __all__ as fft_all
+
+from ..common import _fft
+from .._internal import get_xp
+
+import numpy as np
+
+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__ = fft_all + _fft.__all__
+
+del get_xp
+del np
+del fft_all
+del _fft
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f01593bd0ae619b3bea471980b4eeabfc29f319
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py
@@ -0,0 +1,90 @@
+from numpy.linalg import * # noqa: F403
+from numpy.linalg import __all__ as linalg_all
+import numpy as _np
+
+from ..common import _linalg
+from .._internal import get_xp
+
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot # noqa: F401
+
+import numpy as np
+
+cross = get_xp(np)(_linalg.cross)
+outer = get_xp(np)(_linalg.outer)
+EighResult = _linalg.EighResult
+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: _np.ndarray, x2: _np.ndarray, /) -> _np.ndarray:
+    try:
+        from numpy.linalg._linalg import (
+        _makearray, _assert_stacked_2d, _assert_stacked_square,
+        _commonType, isComplexType, _raise_linalgerror_singular
+        )
+    except ImportError:
+        from numpy.linalg.linalg import (
+        _makearray, _assert_stacked_2d, _assert_stacked_square,
+        _commonType, isComplexType, _raise_linalgerror_singular
+        )
+    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
+    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 = gufunc(x1, x2, signature=signature)
+
+    return wrap(r.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__ = linalg_all + _linalg.__all__ + ['solve']
+
+del get_xp
+del np
+del linalg_all
+del _linalg
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfa3acf8945a84c8e3fcdc892edc19d4f674cd30
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py
@@ -0,0 +1,24 @@
+from torch import * # noqa: F403
+
+# Several names are not included in the above import *
+import torch
+for n in dir(torch):
+    if (n.startswith('_')
+        or n.endswith('_')
+        or 'cuda' in n
+        or 'cpu' in n
+        or 'backward' in n):
+        continue
+    exec(n + ' = torch.' + n)
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+
+__import__(__package__ + '.fft')
+
+from ..common._helpers import * # noqa: F403
+
+__array_api_version__ = '2023.12'
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ac66bcb17e6f13a51bd6c7fd345bee23c16140f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py
@@ -0,0 +1,752 @@
+from __future__ import annotations
+
+from functools import wraps as _wraps
+from builtins import all as _builtin_all, any as _builtin_any
+
+from ..common._aliases import (matrix_transpose as _aliases_matrix_transpose,
+                               vecdot as _aliases_vecdot,
+                               clip as _aliases_clip,
+                               unstack as _aliases_unstack,
+                               cumulative_sum as _aliases_cumulative_sum,
+                               )
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+import torch
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import List, Optional, Sequence, Tuple, Union
+    from ..common._typing import Device
+    from torch import dtype as Dtype
+
+    array = torch.Tensor
+
+_int_dtypes = {
+    torch.uint8,
+    torch.int8,
+    torch.int16,
+    torch.int32,
+    torch.int64,
+}
+
+_array_api_dtypes = {
+    torch.bool,
+    *_int_dtypes,
+    torch.float32,
+    torch.float64,
+    torch.complex64,
+    torch.complex128,
+}
+
+_promotion_table  = {
+    # bool
+    (torch.bool, torch.bool): torch.bool,
+    # ints
+    (torch.int8, torch.int8): torch.int8,
+    (torch.int8, torch.int16): torch.int16,
+    (torch.int8, torch.int32): torch.int32,
+    (torch.int8, torch.int64): torch.int64,
+    (torch.int16, torch.int8): torch.int16,
+    (torch.int16, torch.int16): torch.int16,
+    (torch.int16, torch.int32): torch.int32,
+    (torch.int16, torch.int64): torch.int64,
+    (torch.int32, torch.int8): torch.int32,
+    (torch.int32, torch.int16): torch.int32,
+    (torch.int32, torch.int32): torch.int32,
+    (torch.int32, torch.int64): torch.int64,
+    (torch.int64, torch.int8): torch.int64,
+    (torch.int64, torch.int16): torch.int64,
+    (torch.int64, torch.int32): torch.int64,
+    (torch.int64, torch.int64): torch.int64,
+    # uints
+    (torch.uint8, torch.uint8): torch.uint8,
+    # ints and uints (mixed sign)
+    (torch.int8, torch.uint8): torch.int16,
+    (torch.int16, torch.uint8): torch.int16,
+    (torch.int32, torch.uint8): torch.int32,
+    (torch.int64, torch.uint8): torch.int64,
+    (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.float32): torch.float32,
+    (torch.float32, torch.float64): torch.float64,
+    (torch.float64, torch.float32): torch.float64,
+    (torch.float64, torch.float64): torch.float64,
+    # complexes
+    (torch.complex64, torch.complex64): torch.complex64,
+    (torch.complex64, torch.complex128): torch.complex128,
+    (torch.complex128, torch.complex64): torch.complex128,
+    (torch.complex128, 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,
+}
+
+
+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
+
+def result_type(*arrays_and_dtypes: Union[array, Dtype]) -> Dtype:
+    if len(arrays_and_dtypes) == 0:
+        raise TypeError("At least one array or dtype must be provided")
+    if len(arrays_and_dtypes) == 1:
+        x = arrays_and_dtypes[0]
+        if isinstance(x, torch.dtype):
+            return x
+        return x.dtype
+    if len(arrays_and_dtypes) > 2:
+        return result_type(arrays_and_dtypes[0], result_type(*arrays_and_dtypes[1:]))
+
+    x, y = arrays_and_dtypes
+    xdt = x.dtype if not isinstance(x, torch.dtype) else x
+    ydt = y.dtype if not isinstance(y, torch.dtype) else y
+
+    if (xdt, ydt) in _promotion_table:
+        return _promotion_table[xdt, ydt]
+
+    # 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_: Union[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)
+
+# 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: Optional[Union[int, Tuple[int, ...]]] = 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: Optional[Union[int, Tuple[int, ...]]] = 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)
+
+clip = get_xp(torch)(_aliases_clip)
+unstack = get_xp(torch)(_aliases_unstack)
+cumulative_sum = get_xp(torch)(_aliases_cumulative_sum)
+
+# 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) -> array:
+    return torch.sort(x, dim=axis, descending=descending, stable=stable, **kwargs).values
+
+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 prod(x: array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         dtype: Optional[Dtype] = None,
+         keepdims: bool = False,
+         **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+
+    # https://github.com/pytorch/pytorch/issues/29137. Separate from the logic
+    # below because it still needs to upcast.
+    if axis == ():
+        if dtype is None:
+            # We can't upcast uint8 according to the spec because there is no
+            # torch.uint64, so at least upcast to int64 which is what sum does
+            # when axis=None.
+            if x.dtype in [torch.int8, torch.int16, torch.int32, torch.uint8]:
+                return x.to(torch.int64)
+            return x.clone()
+        return x.to(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, ndim, keepdims)
+        return res
+
+    return torch.prod(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+
+def sum(x: array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         dtype: Optional[Dtype] = None,
+         keepdims: bool = False,
+         **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+
+    # https://github.com/pytorch/pytorch/issues/29137.
+    # Make sure it upcasts.
+    if axis == ():
+        if dtype is None:
+            # We can't upcast uint8 according to the spec because there is no
+            # torch.uint64, so at least upcast to int64 which is what sum does
+            # when axis=None.
+            if x.dtype in [torch.int8, torch.int16, torch.int32, torch.uint8]:
+                return x.to(torch.int64)
+            return x.clone()
+        return x.to(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, ndim, keepdims)
+        return res
+
+    return torch.sum(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+def any(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+    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, 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: Optional[Union[int, Tuple[int, ...]]] = None,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+    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, 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: Optional[Union[int, Tuple[int, ...]]] = None,
+         keepdims: bool = False,
+         **kwargs) -> 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: Optional[Union[int, Tuple[int, ...]]] = None,
+        correction: Union[int, float] = 0.0,
+        keepdims: bool = False,
+        **kwargs) -> 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: Optional[Union[int, Tuple[int, ...]]] = None,
+        correction: Union[int, float] = 0.0,
+        keepdims: bool = False,
+        **kwargs) -> 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: Union[Tuple[array, ...], List[array]],
+           /,
+           *,
+           axis: Optional[int] = 0,
+           **kwargs) -> 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: Union[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) -> 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: Optional[Union[int, Tuple[int, ...]]] = None, **kwargs) -> 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: Union[int, Tuple[int, ...]], *, axis: Optional[Union[int, Tuple[int, ...]]] = None, **kwargs) -> array:
+    return torch.roll(x, shift, axis, **kwargs)
+
+def nonzero(x: array, /, **kwargs) -> Tuple[array, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return torch.nonzero(x, as_tuple=True, **kwargs)
+
+def where(condition: array, x1: array, x2: array, /) -> 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: Optional[bool] = None,
+            **kwargs) -> 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: Union[int, float],
+           /,
+           stop: Optional[Union[int, float]] = None,
+           step: Union[int, float] = 1,
+           *,
+           dtype: Optional[Dtype] = None,
+           device: Optional[Device] = None,
+           **kwargs) -> 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: Optional[int] = None,
+        /,
+        *,
+        k: int = 0,
+        dtype: Optional[Dtype] = None,
+        device: Optional[Device] = None,
+        **kwargs) -> 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: Union[int, float],
+             stop: Union[int, float],
+             /,
+             num: int,
+             *,
+             dtype: Optional[Dtype] = None,
+             device: Optional[Device] = None,
+             endpoint: bool = True,
+             **kwargs) -> 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: Union[int, Tuple[int, ...]],
+         fill_value: Union[bool, int, float, complex],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> 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: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    return torch.ones(shape, dtype=dtype, device=device, **kwargs)
+
+def zeros(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    return torch.zeros(shape, dtype=dtype, device=device, **kwargs)
+
+def empty(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> 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 = 0) -> array:
+    return torch.unsqueeze(x, axis)
+
+def astype(x: array, dtype: Dtype, /, *, copy: bool = True) -> array:
+    return x.to(dtype, copy=copy)
+
+def broadcast_arrays(*arrays: array) -> List[array]:
+    shape = torch.broadcast_shapes(*[a.shape for a in arrays])
+    return [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) -> 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: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2, **kwargs) -> 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: Union[Dtype, str, Tuple[Union[Dtype, str], ...]],
+    *, _tuple=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: Optional[int] = None, **kwargs) -> array:
+    if axis is None:
+        if x.ndim != 1:
+            raise ValueError("axis must be specified when ndim > 1")
+        axis = 0
+    return torch.index_select(x, axis, indices, **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
+
+
+__all__ = ['__array_namespace_info__', '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', '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', 'sort', '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', 'sign']
+
+_all_ignore = ['torch', 'get_xp']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..264caa9e5fbbe9da3d9b9594b8d11f313d8536ef
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py
@@ -0,0 +1,358 @@
+"""
+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 = np.__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 = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 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 : str
+            The default device used for new PyTorch arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return torch.device("cpu")
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new PyTorch arrays.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for. For PyTorch, only
+            ``'cpu'`` is allowed.
+
+        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 = np.__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 : 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
+            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 = np.__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 of str
+            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 = np.__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')
+        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 devices
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c9117ee57d3534e3e72329d740632c02e936200
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    import torch
+    array = torch.Tensor
+    from typing import Union, Sequence, Literal
+
+from torch.fft import * # noqa: F403
+import torch.fft
+
+# 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,
+) -> 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,
+) -> 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,
+) -> 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,
+) -> array:
+    return torch.fft.irfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def fftshift(
+    x: array,
+    /,
+    *,
+    axes: Union[int, Sequence[int]] = None,
+    **kwargs,
+) -> array:
+    return torch.fft.fftshift(x, dim=axes, **kwargs)
+
+def ifftshift(
+    x: array,
+    /,
+    *,
+    axes: Union[int, Sequence[int]] = None,
+    **kwargs,
+) -> array:
+    return torch.fft.ifftshift(x, dim=axes, **kwargs)
+
+
+__all__ = torch.fft.__all__ + [
+    "fftn",
+    "ifftn",
+    "rfftn",
+    "irfftn",
+    "fftshift",
+    "ifftshift",
+]
+
+_all_ignore = ['torch']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..e26198b9b562ed307206dd08dd9de7c8aa2a918b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py
@@ -0,0 +1,121 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    import torch
+    array = torch.Tensor
+    from torch import dtype as Dtype
+    from typing import Optional, Union, Tuple, Literal
+    inf = float('inf')
+
+from ._aliases import _fix_promotion, sum
+
+from torch.linalg import * # noqa: F403
+
+# torch.linalg doesn't define __all__
+# from torch.linalg import __all__ as linalg_all
+from torch import linalg as torch_linalg
+linalg_all = [i for i in dir(torch_linalg) if not i.startswith('_')]
+
+# outer is implemented in torch but aren't in the linalg namespace
+from torch import outer
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot
+
+# 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) -> 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) -> 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: Optional[Dtype] = 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: Optional[Union[int, Tuple[int, ...]]] = None,
+    keepdims: bool = False,
+    ord: Union[int, float, Literal[inf, -inf]] = 2,
+    **kwargs,
+) -> 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__ = linalg_all + ['outer', 'matmul', 'matrix_transpose', 'tensordot',
+                        'cross', 'vecdot', 'solve', 'trace', 'vector_norm']
+
+_all_ignore = ['torch_linalg', 'sum']
+
+del linalg_all
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2062f7d5d6a4d9f5a3556164720a6abc4da456bc
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from ._funcs import atleast_nd, cov, create_diagonal, expand_dims, kron, sinc
+
+__version__ = "0.2.0"
+
+__all__ = [
+    "__version__",
+    "atleast_nd",
+    "cov",
+    "create_diagonal",
+    "expand_dims",
+    "kron",
+    "sinc",
+]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d117c1876cee601b0ad3ec14fa3d24b39a4caeb
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5973d0b17f2395835ced32a5146ef55aad2f54d
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce800189b46d25316c3123a22ce4ff2e7e1e81ce
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py
@@ -0,0 +1,484 @@
+from __future__ import annotations
+
+import warnings
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from ._typing import Array, ModuleType
+
+__all__ = ["atleast_nd", "cov", "create_diagonal", "expand_dims", "kron", "sinc"]
+
+
+def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType) -> Array:
+    """
+    Recursively expand the dimension of an array to at least `ndim`.
+
+    Parameters
+    ----------
+    x : array
+    ndim : int
+        The minimum number of dimensions for the result.
+    xp : array_namespace
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : 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 x.ndim < ndim:
+        x = xp.expand_dims(x, axis=0)
+        x = atleast_nd(x, ndim=ndim, xp=xp)
+    return x
+
+
+def cov(m: Array, /, *, xp: ModuleType) -> Array:
+    """
+    Estimate a covariance matrix.
+
+    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`,
+    then the covariance matrix element :math:`C_{ij}` is the covariance of
+    :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
+    of :math:`x_i`.
+
+    This provides a subset of the functionality of ``numpy.cov``.
+
+    Parameters
+    ----------
+    m : array
+        A 1-D or 2-D array containing multiple variables and observations.
+        Each row of `m` represents a variable, and each column a single
+        observation of all those variables.
+    xp : array_namespace
+        The standard-compatible namespace for `m`.
+
+    Returns
+    -------
+    res : array
+        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)
+
+    """
+    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 = _mean(m, axis=1, xp=xp)
+    fact = m.shape[1] - 1
+
+    if fact <= 0:
+        warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2)
+        fact = 0.0
+
+    m -= avg[:, None]
+    m_transpose = m.T
+    if xp.isdtype(m_transpose.dtype, "complex floating"):
+        m_transpose = xp.conj(m_transpose)
+    c = 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 create_diagonal(x: Array, /, *, offset: int = 0, xp: ModuleType) -> Array:
+    """
+    Construct a diagonal array.
+
+    Parameters
+    ----------
+    x : array
+        A 1-D array
+    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
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : array
+        A 2-D array 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 x.ndim != 1:
+        err_msg = "`x` must be 1-dimensional."
+        raise ValueError(err_msg)
+    n = x.shape[0] + abs(offset)
+    diag = xp.zeros(n**2, dtype=x.dtype)
+    i = offset if offset >= 0 else abs(offset) * n
+    diag[i : min(n * (n - offset), diag.shape[0]) : n + 1] = x
+    return xp.reshape(diag, (n, n))
+
+
+def _mean(
+    x: Array,
+    /,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+    xp: ModuleType,
+) -> Array:
+    """
+    Complex mean, https://github.com/data-apis/array-api/issues/846.
+    """
+    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 expand_dims(
+    a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType
+) -> 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
+    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
+        The standard-compatible namespace for `a`.
+
+    Returns
+    -------
+    res : 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 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)
+    for i in sorted(axis):
+        a = xp.expand_dims(a, axis=i)
+    return a
+
+
+def kron(a: Array, b: Array, /, *, xp: ModuleType) -> 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
+    xp : array_namespace
+        The standard-compatible namespace for `a` and `b`.
+
+    Returns
+    -------
+    res : 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)
+
+    """
+
+    b = xp.asarray(b)
+    singletons = (1,) * (b.ndim - a.ndim)
+    a = xp.broadcast_to(xp.asarray(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 = a.shape
+    b_shape = b.shape
+
+    # 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
+    a_shape = xp.asarray(a_shape)
+    b_shape = xp.asarray(b_shape)
+    return xp.reshape(result, tuple(xp.multiply(a_shape, b_shape)))
+
+
+def sinc(x: Array, /, *, xp: ModuleType) -> 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
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : 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
+    ----------
+    .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
+           Resource. https://mathworld.wolfram.com/SincFunction.html
+    .. [2] 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 not xp.isdtype(x.dtype, "real floating"):
+        err_msg = "`x` must have a real floating data type."
+        raise ValueError(err_msg)
+    # no scalars in `where` - array-api#807
+    y = xp.pi * xp.where(
+        x, x, xp.asarray(xp.finfo(x.dtype).smallest_normal, dtype=x.dtype)
+    )
+    return xp.sin(y) / y
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ffa13f23fc8c52abf5c65206ec1ff5a8481832c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py
@@ -0,0 +1,8 @@
+from __future__ import annotations
+
+from types import ModuleType
+from typing import Any
+
+Array = Any  # To be changed to a Protocol later (see array-api#589)
+
+__all__ = ["Array", "ModuleType"]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2418395425d7ecce9e1a4da68985c8fde93bc1c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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.2"
+
+__all__ = ["minimize", "show_versions"]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/framework.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/framework.py
new file mode 100644
index 0000000000000000000000000000000000000000..9afea66281067e27a486ff317a4bffa03ec3e68b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..01e5159e0dfebed9a78c6948cb99bfb1d744b6c7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..4891b074bfd6dd3f7d43fa95b0b845a764cac114
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py
@@ -0,0 +1,1529 @@
+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]
+
+    @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]
+
+
+_cache = {"xpt": None, "a": None, "right_scaling": None, "eigh": None}
+
+
+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.
+    """
+
+    # Compute the scaled directions from the base point to the
+    # interpolation points. We scale the directions to avoid numerical
+    # difficulties.
+    if _cache["xpt"] 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)
+
+    _cache["xpt"] = np.copy(interpolation.xpt)
+    _cache["a"] = np.copy(a)
+    _cache["right_scaling"] = np.copy(right_scaling)
+    _cache["eigh"] = (eig_values, eig_vectors)
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/problem.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/problem.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dbebce3a48067e97da2b75bd2cdd609e01029b2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/settings.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..6394822826e094a803a485556a298e342bf260ac
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01a1ad3c6f4cb5c0c9b99d1ce35fea92e7618ff5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b67fd7c813ee493b18720d1daf71324d72330b6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4a960396fb2e992cf76bac0baf171b5af9b7717
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe6b4841ddff3a04bda5cbff744e30681b6963b9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/exceptions.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..c85094894f378a8e3934ad109ea6166e33e4366b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/math.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/math.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b16ae98a0df38752815f5a69d56da20f856f9f9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/versions.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..94a0f8f5cef626354f40901cbe06a84287291c1c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/decorator.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c4ab90e3d52db448b6381bc7860f55ac8789c9c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/decorator.py
@@ -0,0 +1,399 @@
+# #########################     LICENSE     ############################ #
+
+# Copyright (c) 2005-2015, Michele Simionato
+# 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 bytecode 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
+# 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.
+
+"""
+Decorator module, see https://pypi.python.org/pypi/decorator
+for the documentation.
+"""
+import re
+import sys
+import inspect
+import operator
+import itertools
+import collections
+
+from inspect import getfullargspec
+
+__version__ = '4.0.5'
+
+
+def get_init(cls):
+    return cls.__init__
+
+
+# getargspec has been deprecated in Python 3.5
+ArgSpec = collections.namedtuple(
+    'ArgSpec', 'args varargs varkw defaults')
+
+
+def getargspec(f):
+    """A replacement for inspect.getargspec"""
+    spec = getfullargspec(f)
+    return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
+
+
+DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
+
+
+# basic functionality
+class FunctionMaker:
+    """
+    An object with the ability to create functions with a given signature.
+    It has attributes name, doc, module, signature, defaults, dict, and
+    methods update and make.
+    """
+
+    # Atomic get-and-increment provided by the GIL
+    _compile_count = itertools.count()
+
+    def __init__(self, func=None, name=None, signature=None,
+                 defaults=None, doc=None, module=None, funcdict=None):
+        self.shortsignature = signature
+        if func:
+            # func can be a class or a callable, but not an instance method
+            self.name = func.__name__
+            if self.name == '':  # small hack for lambda functions
+                self.name = '_lambda_'
+            self.doc = func.__doc__
+            self.module = func.__module__
+            if inspect.isfunction(func):
+                argspec = getfullargspec(func)
+                self.annotations = getattr(func, '__annotations__', {})
+                for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
+                          'kwonlydefaults'):
+                    setattr(self, a, getattr(argspec, a))
+                for i, arg in enumerate(self.args):
+                    setattr(self, 'arg%d' % i, arg)
+                allargs = list(self.args)
+                allshortargs = list(self.args)
+                if self.varargs:
+                    allargs.append('*' + self.varargs)
+                    allshortargs.append('*' + self.varargs)
+                elif self.kwonlyargs:
+                    allargs.append('*')  # single star syntax
+                for a in self.kwonlyargs:
+                    allargs.append(f'{a}=None')
+                    allshortargs.append(f'{a}={a}')
+                if self.varkw:
+                    allargs.append('**' + self.varkw)
+                    allshortargs.append('**' + self.varkw)
+                self.signature = ', '.join(allargs)
+                self.shortsignature = ', '.join(allshortargs)
+                self.dict = func.__dict__.copy()
+        # func=None happens when decorating a caller
+        if name:
+            self.name = name
+        if signature is not None:
+            self.signature = signature
+        if defaults:
+            self.defaults = defaults
+        if doc:
+            self.doc = doc
+        if module:
+            self.module = module
+        if funcdict:
+            self.dict = funcdict
+        # check existence required attributes
+        assert hasattr(self, 'name')
+        if not hasattr(self, 'signature'):
+            raise TypeError(f'You are decorating a non-function: {func}')
+
+    def update(self, func, **kw):
+        "Update the signature of func with the data in self"
+        func.__name__ = self.name
+        func.__doc__ = getattr(self, 'doc', None)
+        func.__dict__ = getattr(self, 'dict', {})
+        func.__defaults__ = getattr(self, 'defaults', ())
+        func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
+        func.__annotations__ = getattr(self, 'annotations', None)
+        try:
+            frame = sys._getframe(3)
+        except AttributeError:  # for IronPython and similar implementations
+            callermodule = '?'
+        else:
+            callermodule = frame.f_globals.get('__name__', '?')
+        func.__module__ = getattr(self, 'module', callermodule)
+        func.__dict__.update(kw)
+
+    def make(self, src_templ, evaldict=None, addsource=False, **attrs):
+        "Make a new function from a given template and update the signature"
+        src = src_templ % vars(self)  # expand name and signature
+        evaldict = evaldict or {}
+        mo = DEF.match(src)
+        if mo is None:
+            raise SyntaxError(f'not a valid function template\n{src}')
+        name = mo.group(1)  # extract the function name
+        names = set([name] + [arg.strip(' *') for arg in
+                              self.shortsignature.split(',')])
+        for n in names:
+            if n in ('_func_', '_call_'):
+                raise NameError(f'{n} is overridden in\n{src}')
+        if not src.endswith('\n'):  # add a newline just for safety
+            src += '\n'  # this is needed in old versions of Python
+
+        # Ensure each generated function has a unique filename for profilers
+        # (such as cProfile) that depend on the tuple of (,
+        # , ) being unique.
+        filename = '' % (next(self._compile_count),)
+        try:
+            code = compile(src, filename, 'single')
+            exec(code, evaldict)
+        except:  # noqa: E722
+            print('Error in generated code:', file=sys.stderr)
+            print(src, file=sys.stderr)
+            raise
+        func = evaldict[name]
+        if addsource:
+            attrs['__source__'] = src
+        self.update(func, **attrs)
+        return func
+
+    @classmethod
+    def create(cls, obj, body, evaldict, defaults=None,
+               doc=None, module=None, addsource=True, **attrs):
+        """
+        Create a function from the strings name, signature, and body.
+        evaldict is the evaluation dictionary. If addsource is true, an
+        attribute __source__ is added to the result. The attributes attrs
+        are added, if any.
+        """
+        if isinstance(obj, str):  # "name(signature)"
+            name, rest = obj.strip().split('(', 1)
+            signature = rest[:-1]  # strip a right parens
+            func = None
+        else:  # a function
+            name = None
+            signature = None
+            func = obj
+        self = cls(func, name, signature, defaults, doc, module)
+        ibody = '\n'.join('    ' + line for line in body.splitlines())
+        return self.make('def %(name)s(%(signature)s):\n' + ibody,
+                         evaldict, addsource, **attrs)
+
+
+def decorate(func, caller):
+    """
+    decorate(func, caller) decorates a function using a caller.
+    """
+    evaldict = func.__globals__.copy()
+    evaldict['_call_'] = caller
+    evaldict['_func_'] = func
+    fun = FunctionMaker.create(
+        func, "return _call_(_func_, %(shortsignature)s)",
+        evaldict, __wrapped__=func)
+    if hasattr(func, '__qualname__'):
+        fun.__qualname__ = func.__qualname__
+    return fun
+
+
+def decorator(caller, _func=None):
+    """decorator(caller) converts a caller function into a decorator"""
+    if _func is not None:  # return a decorated function
+        # this is obsolete behavior; you should use decorate instead
+        return decorate(_func, caller)
+    # else return a decorator function
+    if inspect.isclass(caller):
+        name = caller.__name__.lower()
+        callerfunc = get_init(caller)
+        doc = (f'decorator({caller.__name__}) converts functions/generators into ' 
+               f'factories of {caller.__name__} objects')
+    elif inspect.isfunction(caller):
+        if caller.__name__ == '':
+            name = '_lambda_'
+        else:
+            name = caller.__name__
+        callerfunc = caller
+        doc = caller.__doc__
+    else:  # assume caller is an object with a __call__ method
+        name = caller.__class__.__name__.lower()
+        callerfunc = caller.__call__.__func__
+        doc = caller.__call__.__doc__
+    evaldict = callerfunc.__globals__.copy()
+    evaldict['_call_'] = caller
+    evaldict['_decorate_'] = decorate
+    return FunctionMaker.create(
+        f'{name}(func)', 'return _decorate_(func, _call_)',
+        evaldict, doc=doc, module=caller.__module__,
+        __wrapped__=caller)
+
+
+# ####################### contextmanager ####################### #
+
+try:  # Python >= 3.2
+    from contextlib import _GeneratorContextManager
+except ImportError:  # Python >= 2.5
+    from contextlib import GeneratorContextManager as _GeneratorContextManager
+
+
+class ContextManager(_GeneratorContextManager):
+    def __call__(self, func):
+        """Context manager decorator"""
+        return FunctionMaker.create(
+            func, "with _self_: return _func_(%(shortsignature)s)",
+            dict(_self_=self, _func_=func), __wrapped__=func)
+
+
+init = getfullargspec(_GeneratorContextManager.__init__)
+n_args = len(init.args)
+if n_args == 2 and not init.varargs:  # (self, genobj) Python 2.7
+    def __init__(self, g, *a, **k):
+        return _GeneratorContextManager.__init__(self, g(*a, **k))
+    ContextManager.__init__ = __init__
+elif n_args == 2 and init.varargs:  # (self, gen, *a, **k) Python 3.4
+    pass
+elif n_args == 4:  # (self, gen, args, kwds) Python 3.5
+    def __init__(self, g, *a, **k):
+        return _GeneratorContextManager.__init__(self, g, a, k)
+    ContextManager.__init__ = __init__
+
+contextmanager = decorator(ContextManager)
+
+
+# ############################ dispatch_on ############################ #
+
+def append(a, vancestors):
+    """
+    Append ``a`` to the list of the virtual ancestors, unless it is already
+    included.
+    """
+    add = True
+    for j, va in enumerate(vancestors):
+        if issubclass(va, a):
+            add = False
+            break
+        if issubclass(a, va):
+            vancestors[j] = a
+            add = False
+    if add:
+        vancestors.append(a)
+
+
+# inspired from simplegeneric by P.J. Eby and functools.singledispatch
+def dispatch_on(*dispatch_args):
+    """
+    Factory of decorators turning a function into a generic function
+    dispatching on the given arguments.
+    """
+    assert dispatch_args, 'No dispatch args passed'
+    dispatch_str = f"({', '.join(dispatch_args)},)"
+
+    def check(arguments, wrong=operator.ne, msg=''):
+        """Make sure one passes the expected number of arguments"""
+        if wrong(len(arguments), len(dispatch_args)):
+            raise TypeError(f'Expected {len(dispatch_args)} arguments, '
+                            'got {len(arguments)}{msg}')
+
+    def gen_func_dec(func):
+        """Decorator turning a function into a generic function"""
+
+        # first check the dispatch arguments
+        argset = set(getfullargspec(func).args)
+        if not set(dispatch_args) <= argset:
+            raise NameError(f'Unknown dispatch arguments {dispatch_str}')
+
+        typemap = {}
+
+        def vancestors(*types):
+            """
+            Get a list of sets of virtual ancestors for the given types
+            """
+            check(types)
+            ras = [[] for _ in range(len(dispatch_args))]
+            for types_ in typemap:
+                for t, type_, ra in zip(types, types_, ras):
+                    if issubclass(t, type_) and type_ not in t.__mro__:
+                        append(type_, ra)
+            return [set(ra) for ra in ras]
+
+        def ancestors(*types):
+            """
+            Get a list of virtual MROs, one for each type
+            """
+            check(types)
+            lists = []
+            for t, vas in zip(types, vancestors(*types)):
+                n_vas = len(vas)
+                if n_vas > 1:
+                    raise RuntimeError(
+                        f'Ambiguous dispatch for {t}: {vas}')
+                elif n_vas == 1:
+                    va, = vas
+                    mro = type('t', (t, va), {}).__mro__[1:]
+                else:
+                    mro = t.__mro__
+                lists.append(mro[:-1])  # discard t and object
+            return lists
+
+        def register(*types):
+            """
+            Decorator to register an implementation for the given types
+            """
+            check(types)
+
+            def dec(f):
+                check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
+                typemap[types] = f
+                return f
+            return dec
+
+        def dispatch_info(*types):
+            """
+            An utility to introspect the dispatch algorithm
+            """
+            check(types)
+            lst = [tuple(a.__name__ for a in anc)
+                   for anc in itertools.product(*ancestors(*types))]
+            return lst
+
+        def _dispatch(dispatch_args, *args, **kw):
+            types = tuple(type(arg) for arg in dispatch_args)
+            try:  # fast path
+                f = typemap[types]
+            except KeyError:
+                pass
+            else:
+                return f(*args, **kw)
+            combinations = itertools.product(*ancestors(*types))
+            next(combinations)  # the first one has been already tried
+            for types_ in combinations:
+                f = typemap.get(types_)
+                if f is not None:
+                    return f(*args, **kw)
+
+            # else call the default implementation
+            return func(*args, **kw)
+
+        return FunctionMaker.create(
+            func, f'return _f_({dispatch_str}, %%(shortsignature)s)',
+            dict(_f_=_dispatch), register=register, default=func,
+            typemap=typemap, vancestors=vancestors, ancestors=ancestors,
+            dispatch_info=dispatch_info, __wrapped__=func)
+
+    gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
+    return gen_func_dec
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/deprecation.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a6ef8f39ba764b46fdc01de9281cdbf72f4736
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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]  # 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/doccer.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..538b83c482caba1d4a8a2f64e1ad56da1862e286
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/doccer.py
@@ -0,0 +1,372 @@
+"""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()
+        try:
+            newlines = [lines[0]]
+            for line in lines[1:]:
+                newlines.append(indent + line)
+            indented[name] = "\n".join(newlines)
+        except IndexError:
+            indented[name] = dstr
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..8601000890aa60527e6ec7f43e36a66dc0cb5c2d
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e397af4fb7e9bc69f31d1e39aa80716469d5470
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py
@@ -0,0 +1,110 @@
+""" 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, IS_PYPY)
+
+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()
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+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)
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+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
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+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
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5b71c8f1e13b42de2e8e612a005dec409fc025
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py
@@ -0,0 +1,67 @@
+from pytest import raises as assert_raises
+from scipy._lib._pep440 import Version, parse
+
+
+def test_main_versions():
+    assert Version('1.8.0') == Version('1.8.0')
+    for ver in ['1.9.0', '2.0.0', '1.8.1']:
+        assert Version('1.8.0') < Version(ver)
+
+    for ver in ['1.7.0', '1.7.1', '0.9.9']:
+        assert Version('1.8.0') > Version(ver)
+
+
+def test_version_1_point_10():
+    # regression test for gh-2998.
+    assert Version('1.9.0') < Version('1.10.0')
+    assert Version('1.11.0') < Version('1.11.1')
+    assert Version('1.11.0') == Version('1.11.0')
+    assert Version('1.99.11') < Version('1.99.12')
+
+
+def test_alpha_beta_rc():
+    assert Version('1.8.0rc1') == Version('1.8.0rc1')
+    for ver in ['1.8.0', '1.8.0rc2']:
+        assert Version('1.8.0rc1') < Version(ver)
+
+    for ver in ['1.8.0a2', '1.8.0b3', '1.7.2rc4']:
+        assert Version('1.8.0rc1') > Version(ver)
+
+    assert Version('1.8.0b1') > Version('1.8.0a2')
+
+
+def test_dev_version():
+    assert Version('1.9.0.dev+Unknown') < Version('1.9.0')
+    for ver in ['1.9.0', '1.9.0a1', '1.9.0b2', '1.9.0b2.dev+ffffffff', '1.9.0.dev1']:
+        assert Version('1.9.0.dev+f16acvda') < Version(ver)
+
+    assert Version('1.9.0.dev+f16acvda') == Version('1.9.0.dev+f16acvda')
+
+
+def test_dev_a_b_rc_mixed():
+    assert Version('1.9.0a2.dev+f16acvda') == Version('1.9.0a2.dev+f16acvda')
+    assert Version('1.9.0a2.dev+6acvda54') < Version('1.9.0a2')
+
+
+def test_dev0_version():
+    assert Version('1.9.0.dev0+Unknown') < Version('1.9.0')
+    for ver in ['1.9.0', '1.9.0a1', '1.9.0b2', '1.9.0b2.dev0+ffffffff']:
+        assert Version('1.9.0.dev0+f16acvda') < Version(ver)
+
+    assert Version('1.9.0.dev0+f16acvda') == Version('1.9.0.dev0+f16acvda')
+
+
+def test_dev0_a_b_rc_mixed():
+    assert Version('1.9.0a2.dev0+f16acvda') == Version('1.9.0a2.dev0+f16acvda')
+    assert Version('1.9.0a2.dev0+6acvda54') < Version('1.9.0a2')
+
+
+def test_raises():
+    for ver in ['1,9.0', '1.7.x']:
+        assert_raises(ValueError, Version, ver)
+
+def test_legacy_version():
+    # Non-PEP-440 version identifiers always compare less. For NumPy this only
+    # occurs on dev builds prior to 1.10.0 which are unsupported anyway.
+    assert parse('invalid') < Version('0.0.0')
+    assert parse('1.9.0-f16acvda') < Version('1.0.0')
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__testutils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..88db113d6d5a35c96ecc0a6a36ab42d74be49153
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ae85ef318da2b8bb104c4a87faa4e4021c01d5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py
@@ -0,0 +1,51 @@
+import threading
+import time
+import traceback
+
+from numpy.testing import assert_
+from pytest import raises as assert_raises
+
+from scipy._lib._threadsafety import ReentrancyLock, non_reentrant, ReentrancyError
+
+
+def test_parallel_threads():
+    # Check that ReentrancyLock serializes work in parallel threads.
+    #
+    # The test is not fully deterministic, and may succeed falsely if
+    # the timings go wrong.
+
+    lock = ReentrancyLock("failure")
+
+    failflag = [False]
+    exceptions_raised = []
+
+    def worker(k):
+        try:
+            with lock:
+                assert_(not failflag[0])
+                failflag[0] = True
+                time.sleep(0.1 * k)
+                assert_(failflag[0])
+                failflag[0] = False
+        except Exception:
+            exceptions_raised.append(traceback.format_exc(2))
+
+    threads = [threading.Thread(target=lambda k=k: worker(k))
+               for k in range(3)]
+    for t in threads:
+        t.start()
+    for t in threads:
+        t.join()
+
+    exceptions_raised = "\n".join(exceptions_raised)
+    assert_(not exceptions_raised, exceptions_raised)
+
+
+def test_reentering():
+    # Check that ReentrancyLock prevents re-entering from the same thread.
+
+    @non_reentrant()
+    def func(x):
+        return func(x)
+
+    assert_raises(ReentrancyError, func, 0)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a4d22ce468ec951355961cb77dda15b56899818
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py
@@ -0,0 +1,657 @@
+from multiprocessing import Pool
+from multiprocessing.pool import Pool as PWL
+import re
+import math
+from fractions import Fraction
+
+import numpy as np
+from numpy.testing import assert_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+import hypothesis.extra.numpy as npst
+from hypothesis import given, strategies, reproduce_failure  # noqa: F401
+from scipy.conftest import array_api_compatible, skip_xp_invalid_arg
+
+from scipy._lib._array_api import (xp_assert_equal, xp_assert_close, is_numpy,
+                                   xp_copy, is_array_api_strict)
+from scipy._lib._util import (_aligned_zeros, check_random_state, MapWrapper,
+                              getfullargspec_no_self, FullArgSpec,
+                              rng_integers, _validate_int, _rename_parameter,
+                              _contains_nan, _rng_html_rewrite, _lazywhere)
+from scipy import cluster, interpolate, linalg, optimize, sparse, spatial, stats
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@pytest.mark.slow
+def test__aligned_zeros():
+    niter = 10
+
+    def check(shape, dtype, order, align):
+        err_msg = repr((shape, dtype, order, align))
+        x = _aligned_zeros(shape, dtype, order, align=align)
+        if align is None:
+            align = np.dtype(dtype).alignment
+        assert_equal(x.__array_interface__['data'][0] % align, 0)
+        if hasattr(shape, '__len__'):
+            assert_equal(x.shape, shape, err_msg)
+        else:
+            assert_equal(x.shape, (shape,), err_msg)
+        assert_equal(x.dtype, dtype)
+        if order == "C":
+            assert_(x.flags.c_contiguous, err_msg)
+        elif order == "F":
+            if x.size > 0:
+                # Size-0 arrays get invalid flags on NumPy 1.5
+                assert_(x.flags.f_contiguous, err_msg)
+        elif order is None:
+            assert_(x.flags.c_contiguous, err_msg)
+        else:
+            raise ValueError()
+
+    # try various alignments
+    for align in [1, 2, 3, 4, 8, 16, 32, 64, None]:
+        for n in [0, 1, 3, 11]:
+            for order in ["C", "F", None]:
+                for dtype in [np.uint8, np.float64]:
+                    for shape in [n, (1, 2, 3, n)]:
+                        for j in range(niter):
+                            check(shape, dtype, order, align)
+
+
+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)
+
+
+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 TestContainsNaNTest:
+
+    def test_policy(self):
+        data = np.array([1, 2, 3, np.nan])
+
+        contains_nan, nan_policy = _contains_nan(data, nan_policy="propagate")
+        assert contains_nan
+        assert nan_policy == "propagate"
+
+        contains_nan, nan_policy = _contains_nan(data, nan_policy="omit")
+        assert contains_nan
+        assert nan_policy == "omit"
+
+        msg = "The input contains nan values"
+        with pytest.raises(ValueError, match=msg):
+            _contains_nan(data, nan_policy="raise")
+
+        msg = "nan_policy must be one of"
+        with pytest.raises(ValueError, match=msg):
+            _contains_nan(data, nan_policy="nan")
+
+    def test_contains_nan(self):
+        data1 = np.array([1, 2, 3])
+        assert not _contains_nan(data1)[0]
+
+        data2 = np.array([1, 2, 3, np.nan])
+        assert _contains_nan(data2)[0]
+
+        data3 = np.array([np.nan, 2, 3, np.nan])
+        assert _contains_nan(data3)[0]
+
+        data4 = np.array([[1, 2], [3, 4]])
+        assert not _contains_nan(data4)[0]
+
+        data5 = np.array([[1, 2], [3, np.nan]])
+        assert _contains_nan(data5)[0]
+
+    @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)[0]
+
+        data2 = np.array([1, 2, "3", np.nan], dtype='object')
+        assert _contains_nan(data2)[0]
+
+        data3 = np.array([["1", 2], [3, np.nan]])  # converted to string "nan"
+        assert not _contains_nan(data3)[0]
+
+        data4 = np.array([["1", 2], [3, np.nan]], dtype='object')
+        assert _contains_nan(data4)[0]
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @pytest.mark.parametrize("nan_policy", ['propagate', 'omit', 'raise'])
+    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)
+        x_nan = xp_copy(x, xp=xp)
+        x_nan[1, 2, 1] = np.nan
+
+        contains_nan, nan_policy_out = _contains_nan(x, nan_policy=nan_policy)
+        assert not contains_nan
+        assert nan_policy_out == nan_policy
+
+        if nan_policy == 'raise':
+            message = 'The input contains...'
+            with pytest.raises(ValueError, match=message):
+                _contains_nan(x_nan, nan_policy=nan_policy)
+        elif nan_policy == 'omit' and not is_numpy(xp):
+            message = "`nan_policy='omit' is incompatible..."
+            with pytest.raises(ValueError, match=message):
+                _contains_nan(x_nan, nan_policy=nan_policy)
+        elif nan_policy == 'propagate':
+            contains_nan, nan_policy_out = _contains_nan(
+                x_nan, nan_policy=nan_policy)
+            assert contains_nan
+            assert nan_policy_out == nan_policy
+
+
+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'),
+        (svds, "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)
+
+
+class TestLazywhere:
+    n_arrays = strategies.integers(min_value=1, max_value=3)
+    rng_seed = strategies.integers(min_value=1000000000, max_value=9999999999)
+    dtype = strategies.sampled_from((np.float32, np.float64))
+    p = strategies.floats(min_value=0, max_value=1)
+    data = strategies.data()
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.filterwarnings('ignore::RuntimeWarning')  # overflows, etc.
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @given(n_arrays=n_arrays, rng_seed=rng_seed, dtype=dtype, p=p, data=data)
+    @pytest.mark.thread_unsafe
+    def test_basic(self, n_arrays, rng_seed, dtype, p, data, xp):
+        mbs = npst.mutually_broadcastable_shapes(num_shapes=n_arrays+1,
+                                                 min_side=0)
+        input_shapes, result_shape = data.draw(mbs)
+        cond_shape, *shapes = input_shapes
+        elements = {'allow_subnormal': False}  # cupy/cupy#8382
+        fillvalue = xp.asarray(data.draw(npst.arrays(dtype=dtype, shape=tuple(),
+                                                     elements=elements)))
+        float_fillvalue = float(fillvalue)
+        arrays = [xp.asarray(data.draw(npst.arrays(dtype=dtype, shape=shape)))
+                  for shape in shapes]
+
+        def f(*args):
+            return sum(arg for arg in args)
+
+        def f2(*args):
+            return sum(arg for arg in args) / 2
+
+        rng = np.random.default_rng(rng_seed)
+        cond = xp.asarray(rng.random(size=cond_shape) > p)
+
+        res1 = _lazywhere(cond, arrays, f, fillvalue)
+        res2 = _lazywhere(cond, arrays, f, f2=f2)
+        if not is_array_api_strict(xp):
+            res3 = _lazywhere(cond, arrays, f, float_fillvalue)
+
+        # Ensure arrays are at least 1d to follow sane type promotion rules.
+        # This can be removed when minimum supported NumPy is 2.0
+        if xp == np:
+            cond, fillvalue, *arrays = np.atleast_1d(cond, fillvalue, *arrays)
+
+        ref1 = xp.where(cond, f(*arrays), fillvalue)
+        ref2 = xp.where(cond, f(*arrays), f2(*arrays))
+        if not is_array_api_strict(xp):
+            # Array API standard doesn't currently define behavior when fillvalue is a
+            # Python scalar. When it does, test can be run with array_api_strict, too.
+            ref3 = xp.where(cond, f(*arrays), float_fillvalue)
+
+        if xp == np:  # because we ensured arrays are at least 1d
+            ref1 = ref1.reshape(result_shape)
+            ref2 = ref2.reshape(result_shape)
+            ref3 = ref3.reshape(result_shape)
+
+        xp_assert_close(res1, ref1, rtol=2e-16)
+        xp_assert_equal(res2, ref2)
+        if not is_array_api_strict(xp):
+            xp_assert_equal(res3, ref3)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..f425eb4327fe042a3cf8eb79cf3402f23b526ae7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py
@@ -0,0 +1,191 @@
+import numpy as np
+import pytest
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import (
+    _GLOBAL_CONFIG, array_namespace, _asarray, xp_copy, xp_assert_equal, is_numpy,
+    np_compat, xp_default_dtype
+)
+from scipy._lib._array_api_no_0d import xp_assert_equal as xp_assert_equal_no_0d
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@pytest.mark.skipif(not _GLOBAL_CONFIG["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__
+
+        _GLOBAL_CONFIG["SCIPY_ARRAY_API"] = False
+        xp = array_namespace(x, y)
+        assert 'array_api_compat.numpy' in xp.__name__
+        _GLOBAL_CONFIG["SCIPY_ARRAY_API"] = True
+
+    @array_api_compatible
+    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')
+
+    def test_array_likes(self):
+        # should be no exceptions
+        array_namespace([0, 1, 2])
+        array_namespace(1, 2, 3)
+        array_namespace(1)
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    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
+            x[0] = 10
+            x[1] = 11
+            x[2] = 12
+
+            assert x[0] != y[0]
+            assert x[1] != y[1]
+            assert x[2] != y[2]
+            assert id(x) != id(y)
+
+    @array_api_compatible
+    @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 xp == np:
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="Namespaces do not match."):
+                xp_assert_equal(x, y, **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)
+
+
+    @array_api_compatible
+    def test_check_scalar(self, xp):
+        if not is_numpy(xp):
+            pytest.skip("Scalars only exist in NumPy")
+
+        # 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.)[()])
+
+
+    @array_api_compatible
+    def test_check_scalar_no_0d(self, xp):
+        if not is_numpy(xp):
+            pytest.skip("Scalars only exist in NumPy")
+
+        # 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))
+
+    @array_api_compatible
+    def test_default_dtype(self, xp):
+        assert xp_default_dtype(xp) == xp.asarray(1.).dtype
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py
new file mode 100644
index 0000000000000000000000000000000000000000..f19ca377129b925cad732dd25bf3089c646f923f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py
@@ -0,0 +1,162 @@
+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)
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py
new file mode 100644
index 0000000000000000000000000000000000000000..82021775c294c7b881b9458b57d16deaac483cc7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py
@@ -0,0 +1,204 @@
+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
+
+try:
+    import cffi
+    HAVE_CFFI = True
+except ImportError:
+    HAVE_CFFI = False
+
+
+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):
+    if not HAVE_CFFI:
+        pytest.skip("cffi not installed")
+
+    # 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():
+    if not HAVE_CFFI:
+        pytest.skip("cffi not installed")
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..794e365c0d8a5ce337765fc669d688e80240d540
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py
@@ -0,0 +1,45 @@
+"""
+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",
+    ]
+
+    @pytest.mark.thread_unsafe
+    @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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..667e6ab94346fc8b22c0ea4d4624acf33124c8c0
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py
@@ -0,0 +1,10 @@
+import pytest
+
+@pytest.mark.thread_unsafe
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..176a69698b10bd1d0d23fc57f8e8a99ce7209f0f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py
@@ -0,0 +1,143 @@
+''' Some tests for the documenting decorator and support functions '''
+
+import sys
+import pytest
+from numpy.testing import assert_equal, suppress_warnings
+
+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 suppress_warnings() as sup:
+        sup.filter(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 suppress_warnings() as sup:
+        sup.filter(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 suppress_warnings() as sup:
+        sup.filter(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 suppress_warnings() as sup:
+        sup.filter(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 suppress_warnings() as sup:
+        sup.filter(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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a35800a8198af8215e0b5624738f9ac45b0bb96
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py
@@ -0,0 +1,18 @@
+import pytest
+import sys
+import subprocess
+
+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.
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+@pytest.mark.thread_unsafe
+def test_public_modules_importable():
+    pids = [subprocess.Popen([sys.executable, '-c', f'import {module}'])
+            for module in PUBLIC_MODULES]
+    for i, pid in enumerate(pids):
+        assert pid.wait() == 0, f'Failed to import {PUBLIC_MODULES[i]}'
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..5332107cd21cdd2b6e40cc545c87138cee04ff97
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py
@@ -0,0 +1,469 @@
+"""
+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 numpy as np
+import scipy
+
+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)))
+
+
+# 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
+# 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"
+]]
+
+# 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.lsoda',
+    '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',
+]
+
+
+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'
+]
+
+
+# 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
+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 np.testing.suppress_warnings() as sup:
+        sup.filter(DeprecationWarning,"scipy.misc")
+        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'
+]
+
+
+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 np.testing.suppress_warnings() as sup:
+        sup.filter(DeprecationWarning, "scipy.misc")
+        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.filterwarnings('always', category=DeprecationWarning)
+        warnings.filterwarnings('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.thread_unsafe
+@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.lsoda', None),
+                          ('scipy.integrate.odepack', None),
+                          ('scipy.integrate.quadpack', None),
+                          ('scipy.integrate.vode', None),
+                          ('scipy.interpolate.fitpack', None),
+                          ('scipy.interpolate.fitpack2', 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.odr.models', None),
+                          ('scipy.odr.odrpack', 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.waveforms', None),
+                          ('scipy.signal.wavelets', None),
+                          ('scipy.signal.windows.windows', 'windows'),
+                          ('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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_scipy_version.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_scipy_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..68e1a43c3fb329b6a4274ba76b53a215738da6ad
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..292e7ab1739e663979f9f0b9647fb2c7c95d625c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py
@@ -0,0 +1,48 @@
+""" Test tmpdirs module """
+from os import getcwd
+from os.path import realpath, abspath, dirname, isfile, join as pjoin, exists
+
+from scipy._lib._tmpdirs import tempdir, in_tempdir, in_dir
+
+from numpy.testing import assert_, assert_equal
+
+import pytest
+
+
+MY_PATH = abspath(__file__)
+MY_DIR = dirname(MY_PATH)
+
+
+@pytest.mark.thread_unsafe
+def test_tempdir():
+    with tempdir() as tmpdir:
+        fname = pjoin(tmpdir, 'example_file.txt')
+        with open(fname, "w") as fobj:
+            fobj.write('a string\\n')
+    assert_(not exists(tmpdir))
+
+
+@pytest.mark.thread_unsafe
+def test_in_tempdir():
+    my_cwd = getcwd()
+    with in_tempdir() as tmpdir:
+        with open('test.txt', "w") as f:
+            f.write('some text')
+        assert_(isfile('test.txt'))
+        assert_(isfile(pjoin(tmpdir, 'test.txt')))
+    assert_(not exists(tmpdir))
+    assert_equal(getcwd(), my_cwd)
+
+
+@pytest.mark.thread_unsafe
+def test_given_directory():
+    # Test InGivenDirectory
+    cwd = getcwd()
+    with in_dir() as tmpdir:
+        assert_equal(tmpdir, abspath(cwd))
+        assert_equal(tmpdir, abspath(getcwd()))
+    with in_dir(MY_DIR) as tmpdir:
+        assert_equal(tmpdir, MY_DIR)
+        assert_equal(realpath(MY_DIR), realpath(abspath(getcwd())))
+    # We were deleting the given directory! Check not so now.
+    assert_(isfile(MY_PATH))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..f200b1a6e9756b17c96e5b8368271bbf61878d72
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py
@@ -0,0 +1,137 @@
+"""
+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
+            if argtext == "ignore":
+                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
+    # np.testing.suppress_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', '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 filter should not be used, instead, use\n"
+            "numpy.testing.suppress_warnings (in tests only);\n"
+            "found in:\n    {}".format(
+                "\n    ".join(bad_filters)))
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/uarray.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/_lib/uarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..b29fc713efb3e836cc179ac87ce41f87b51870ef
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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._lib._pep440 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdf939b249c17256b622c2f2756a5f34c4a128cc
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__init__.py
@@ -0,0 +1,358 @@
+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
+``grain``          one grain 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9543f18802283ab44c6d1635b0950839f0976b4a
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1bd19e51245bbdfa786b7e85173af06a91399f0e
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77ed9413772adf66f45d48267ff06c5784f63a4b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5204b4909453ab66c934fcc568e79070008a9c0
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/_codata.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..4457a8089d9c4b7ba159519e6ec1606fb7b74070
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/_codata.py
@@ -0,0 +1,2266 @@
+"""
+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
+
+__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)
+
+
+def value(key: str) -> float:
+    """
+    Value in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        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]
+
+
+def unit(key: str) -> str:
+    """
+    Unit in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    unit : Python string
+        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]
+
+
+def precision(key: str) -> float:
+    """
+    Relative precision in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        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]
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/_constants.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3a098d5469bb7195202a638022b1120ec0969bd
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/_constants.py
@@ -0,0 +1,366 @@
+"""
+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
+
+
+"""
+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
+
+
+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
+
+
+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)
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/codata.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..912e0bbf7c4f14d23ced4546b6704f7789996d97
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/constants.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..855901ba802881090b99b7e8972de741331c7ab9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..51b77c491344963c648fef90cdeaa5adac5d9a6f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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('%d %s' % (_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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b9dcd3b5355063cffb3b7a144937a95aab77955
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py
@@ -0,0 +1,90 @@
+import pytest
+
+import scipy.constants as sc
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close
+from numpy.testing import assert_allclose
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+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)
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_convert_temperature_array_like(self):
+        assert_allclose(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'),
+                        [273.15, 0.], rtol=0., atol=1e-13)
+
+
+    @skip_xp_backends(np_only=True, reason='Python int input uses NumPy backend')
+    def test_convert_temperature_errors(self, xp):
+        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")
+
+
+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]))
+
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_lambda_to_nu_array_like(self, xp):
+        assert_allclose(sc.lambda2nu([sc.speed_of_light, 1]),
+                        [1, sc.speed_of_light])
+
+
+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]))
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_nu_to_lambda_array_like(self, xp):
+        assert_allclose(sc.nu2lambda([sc.speed_of_light, 1]),
+                        [1, sc.speed_of_light])
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdd4ffebec4c57f6d399a0f76df2b66056f0b225
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py
new file mode 100644
index 0000000000000000000000000000000000000000..255fdcaf22950848f458a7ed9ada183e0a2e630e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py
@@ -0,0 +1,57 @@
+"""
+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 
+"""
+
+import argparse
+try:
+    import pooch
+except ImportError:
+    pooch = None
+
+
+if __package__ is None or __package__ == '':
+    # Running as python script, use absolute import
+    import _registry  # type: ignore
+else:
+    # Running as python module, use relative import
+    from . import _registry
+
+
+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.
+    """
+    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')
+    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)
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py
new file mode 100644
index 0000000000000000000000000000000000000000..57bb2fa6a12e753eb07a1f359ac04a29bd5c77e5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py
@@ -0,0 +1,219 @@
+from numpy import array, frombuffer, load
+from ._registry import registry, registry_urls
+
+try:
+    import pooch
+except ImportError:
+    pooch = None
+    data_fetcher = None
+else:
+    data_fetcher = pooch.create(
+        # 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"),
+
+        # 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'.")
+    # The "fetch" method returns the full path to the downloaded data file.
+    return data_fetcher.fetch(dataset_name)
+
+
+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
+
+    Parameters
+    ----------
+    None
+
+    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
+
+
+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
+
+
+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')
+    face.shape = (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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_registry.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..969384ad9843159e766100bfa9755aed8102dd09
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_utils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f644f8797d6e3256a16ec2c509eec725c726300
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/_utils.py
@@ -0,0 +1,81 @@
+import os
+import shutil
+from ._registry import method_files_map
+
+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.")
+
+
+def clear_cache(datasets=None):
+    """
+    Cleans the scipy datasets cache directory.
+
+    If a scipy.datasets method or a list/tuple of the same is
+    provided, then clear_cache removes all the data files
+    associated to the passed dataset method callable(s).
+
+    By default, it removes all the cached data files.
+
+    Parameters
+    ----------
+    datasets : callable or list/tuple of callable or None
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..243176bd89b7b6f16406d66293d1872ac2712252
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py
@@ -0,0 +1,128 @@
+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
+
+try:
+    import pooch
+except ImportError:
+    raise ImportError("Missing optional dependency 'pooch' required "
+                      "for scipy.datasets module. Please use pip or "
+                      "conda to install '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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3a7ccc4b33f27dbae7958641a89106cf9580326
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e104a071055161b69f62cec317e8a07b4466653
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py
@@ -0,0 +1,1129 @@
+# 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_sign, xp_copy, xp_take_along_axis
+
+_EERRORINCREASE = -1  # used in derivative
+
+def _derivative_iv(f, x, args, 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, atol, rtol, maxiter_int, order_int, initial_step,
+            step_factor, step_direction, preserve_shape, callback)
+
+
+def derivative(f, x, *, args=(), 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 a 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``.
+    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.
+    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).
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    step_direction : integer 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, tolerances, maxiter, order, initial_step,
+                            step_factor, step_direction, preserve_shape, callback)
+    (func, x, args, 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, 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[h0 <= 0] = xp.asarray(xp.nan, dtype=dtype)
+
+    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[ir] = work.x[ir][:, xp.newaxis] + hr[ir]
+        x_eval[ic] = work.x[ic][:, xp.newaxis] + hc[ic]
+        x_eval[il] = 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[ic] = work_fc
+        work.fs[io] = work_fo
+
+        wc, wo = _derivative_weights(work, n, xp)
+        work.df_last = xp.asarray(work.df, copy=True)
+        work.df[ic] = fc @ wc / work.h[ic]
+        work.df[io] = fo @ wo / work.h[io]
+        work.df[il] *= -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[i] = eim._ECONVERGED
+        stop[i] = True
+
+        if work.nit > 0:
+            i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
+            work.df[i], work.status[i] = xp.nan, eim._EVALUEERR
+            stop[i] = 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[i] = _EERRORINCREASE
+        stop[i] = 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))
+
+
+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 : integer 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)
+    x = xp.asarray(x)
+    int_dtype = xp.isdtype(x.dtype, 'integral')
+    x0 = xp.asarray(x, dtype=xp.asarray(1.0).dtype) if int_dtype else x
+
+    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[i, i] = 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
+
+
+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.
+    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).
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+
+    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)
+    x = xp.asarray(x)
+    dtype = x.dtype if not xp.isdtype(x.dtype, 'integral') else xp.asarray(1.).dtype
+    finfo = xp.finfo(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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..64bc8193cc237465e9427300bedfac8712963e4c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py
@@ -0,0 +1,695 @@
+import math
+import pytest
+
+import numpy as np
+
+from scipy.conftest import array_api_compatible
+import scipy._lib._elementwise_iterative_method as eim
+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, array_namespace
+
+from scipy import stats, optimize, special
+from scipy.differentiate import derivative, jacobian, hessian
+from scipy.differentiate._differentiate import _EERRORINCREASE
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+
+array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
+jax_skip_reason = 'JAX arrays do not support item assignment.'
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+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.skip_xp_backends(np_only=True)
+    @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[(x < 0) + (x > 2)] = xp.nan
+            return y
+
+        x = xp.linspace(0, 2, 10)
+        step_direction = xp.zeros_like(x)
+        step_direction[x < 0.6], step_direction[x > 1.4] = 1, -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=1e-14)
+
+    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
+            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", ('float16', 'float32', 'float64'))
+    def test_dtype(self, hdir, x, dtype, xp):
+        if dtype == 'float16' and not is_numpy(xp):
+            pytest.skip('float16 not tested for alternative backends')
+
+        # 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):
+            xp_test = array_namespace(x)  # needs `isdtype`
+            assert xp_test.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):
+        # 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)
+
+
+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)
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+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)
+        if is_numpy(xp):
+            assert len(np.unique(res.nit)) == 4
+            assert len(np.unique(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)
+            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[0, x[0] < b[0]] = xp.nan
+            x[0, x[0] > b[0] + 0.25] = xp.nan
+            x[1, x[1] > b[1]] = xp.nan
+            x[1, x[1] < b[1] - 0.1-eps] = 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))
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+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])
+        xp_test = array_namespace(z)
+
+        def f1(z):
+            x, y = xp_test.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.thread_unsafe
+    @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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c545a00b9fd63427088ac873fa3fa65678b77f71
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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 ._pocketfft.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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..55987e909527aa316291e24b24389797b644d621
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a106e990449e8c1f8fb2ca6c2f95f7cf6b9407a2
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64a744fe3b05156aff879b90ec30399bc58b1ed4
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8709b5e2ca1a3b936e3c296d87ddb8d000d21119
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c754a23f3e324b0f9dee9fd1410cceebe4320959
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fbb1554310b45678e657418673724a9d2abaca1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac5b914a17eb27754772ad40a29f69de63e64ce3
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4764e7aba32ae14e5af01b467a01d0184fdd07f7
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d66a20520151f345b44ea750c8d039ea8a4115f1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1e5cfcad5c4cbc43276e151d2da33039368630d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py
@@ -0,0 +1,196 @@
+import scipy._lib.uarray as ua
+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
+
+
+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)
+
+
+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)
+
+
+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.
+
+    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)
+
+
+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.
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3fc021c9ef9b7c2a40bf7b5138158df8e276ae6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py
@@ -0,0 +1,1630 @@
+from scipy._lib.uarray import generate_multimethod, Dispatchable
+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")
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_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),)
+
+
+@_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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..775b26a8bf5922f7fa3634ad6c8c708a96820931
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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 _pocketfft
+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'}
+
+# pocketfft 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 pocketfft.
+
+def _execute_1D(func_str, pocketfft_func, x, n, axis, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return pocketfft_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 = pocketfft_func(x, n=n, axis=axis, norm=norm)
+    return xp.asarray(y)
+
+
+def _execute_nD(func_str, pocketfft_func, x, s, axes, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+    
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return pocketfft_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 = pocketfft_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', _pocketfft.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', _pocketfft.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', _pocketfft.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', _pocketfft.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', _pocketfft.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', _pocketfft.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', _pocketfft.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', _pocketfft.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', _pocketfft.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', _pocketfft.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 _pocketfft.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 _pocketfft.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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9647c5d6ceddc73b97d95f562662ada02c1ae74
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..61bbe802bbb4a40df8ca3b653c693105b29c6578
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py
@@ -0,0 +1,223 @@
+"""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
+import numpy as np
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+
+@_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),)
+
+
+@_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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b38733aaa349c301ba7d5b83691c55204dc8991
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py
@@ -0,0 +1,200 @@
+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
+
+__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
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e08c4f61c854f9bfb9407a1951f2cf5a2af123
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py
@@ -0,0 +1,379 @@
+from functools import update_wrapper, lru_cache
+import inspect
+
+from ._pocketfft import helper as _helper
+
+import numpy as np
+from scipy._lib._array_api import array_namespace
+
+
+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.__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.__wrapped__ = _helper.prev_good_size
+prev_fast_len.__signature__ = _sig_prev_fast_len
+
+
+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 : array_like
+        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.
+
+    """
+    x = np.asarray(x)
+    return _helper._init_nd_shape_and_axes(x, shape, axes)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..1b5163d8435976c24988afbd39ded304947178cb
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0671484c9a0780df353b9b783813b6fa7492d38d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py
@@ -0,0 +1,9 @@
+""" FFT backend using pypocketfft """
+
+from .basic import *
+from .realtransforms import *
+from .helper import *
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b7140dd1f0cbcf485fafbbc1bd13e314b9f2e0f
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a36b9dfabe39c357a99d89fca2ed7355ce9c0a15
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17f7a90df26eeb679564927d67b8a9feae462735
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd0a0d3f0c5fe73d000303d0c4a65f4d0d7d668b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd2d0d33958021c431171b72f72c37363ac98e03
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py
@@ -0,0 +1,251 @@
+"""
+Discrete Fourier Transforms - basic.py
+"""
+import numpy as np
+import functools
+from . import pypocketfft 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'
+ifft = functools.partial(c2c, False)
+ifft.__name__ = 'ifft'
+
+
+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'
+ihfft = functools.partial(r2c, False)
+ihfft.__name__ = 'ihfft'
+
+
+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'
+irfft = functools.partial(c2r, False)
+irfft.__name__ = 'irfft'
+
+
+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'
+ifftn = functools.partial(c2cn, False)
+ifftn.__name__ = 'ifftn'
+
+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'
+ihfftn = functools.partial(r2cn, False)
+ihfftn.__name__ = 'ihfftn'
+
+
+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'
+irfftn = functools.partial(c2rn, False)
+irfftn.__name__ = 'irfftn'
+
+
+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'
+irfft_fftpack = functools.partial(r2r_fftpack, False)
+irfft_fftpack.__name__ = 'irfft_fftpack'
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab2fbc553ccc46a4b337060a62702ec28cb8b254
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py
@@ -0,0 +1,221 @@
+from numbers import Number
+import operator
+import os
+import threading
+import contextlib
+
+import numpy as np
+
+from scipy._lib._util import copy_if_needed
+
+# good_size is exposed (and used) from this import
+from .pypocketfft 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):
+    """Handles shape and axes arguments for nd transforms"""
+    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 pypocketfft 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
+
+
+@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)
+
+    """
+    old_workers = get_workers()
+    _config.default_workers = _workers(operator.index(workers))
+    try:
+        yield
+    finally:
+        _config.default_workers = old_workers
+
+
+def get_workers():
+    """Returns the default number of workers within the current context
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a0c616742305444d51258e650344c060129dfab
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py
@@ -0,0 +1,109 @@
+import numpy as np
+from . import pypocketfft 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 : {pypocketfft.dct, pypocketfft.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'
+idct = functools.partial(_r2r, False, pfft.dct)
+idct.__name__ = 'idct'
+
+dst = functools.partial(_r2r, True, pfft.dst)
+dst.__name__ = 'dst'
+idst = functools.partial(_r2r, False, pfft.dst)
+idst.__name__ = 'idst'
+
+
+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 : {pypocketfft.dct, pypocketfft.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'
+idctn = functools.partial(_r2rn, False, pfft.dct)
+idctn.__name__ = 'idctn'
+
+dstn = functools.partial(_r2rn, True, pfft.dst)
+dstn.__name__ = 'dstn'
+idstn = functools.partial(_r2rn, False, pfft.dst)
+idstn.__name__ = 'idstn'
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..feffc37944c24f81bba3352329cbf75743e4e280
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py
@@ -0,0 +1,1013 @@
+# 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._pocketfft 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._PYPOCKETFFT
+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 = 1e-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="size=%d" % size)
+            assert_array_almost_equal(y2, x, decimal=self.ndec,
+                                       err_msg="size=%d" % 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..38b3f0a7367a9e97a97133f62ddb5dfb223581ed
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py
@@ -0,0 +1,505 @@
+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._pocketfft.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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c7a3d683dd78d3227a7de88f5c47569d2f4e17f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py
@@ -0,0 +1,693 @@
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+import numpy as np
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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),)
+
+
+@_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=-0.5` and
+    even around :math:`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)
+
+    ``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.
+
+    References
+    ----------
+    .. [1] Wikipedia, "Discrete sine transform",
+           https://en.wikipedia.org/wiki/Discrete_sine_transform
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_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
+
+    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.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..2042453733bec54860974cc1e20ba908e8c9b94d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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 _pocketfft
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+def _execute(pocketfft_func, x, type, s, axes, norm, 
+             overwrite_x, workers, orthogonalize):
+    xp = array_namespace(x)
+    x = np.asarray(x)
+    y = pocketfft_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(_pocketfft.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(_pocketfft.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(_pocketfft.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(_pocketfft.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(_pocketfft.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(_pocketfft.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(_pocketfft.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(_pocketfft.idst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..48a7d2b3b50501b84f7c18e366ad2e66782b4ab6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..933e9c0302d46faf33b3dc015d58996e3e46c058
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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, _pocketfft, 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, _pocketfft.hfft2, _pocketfft.hfftn,  # np has no hfftn
+            np.fft.ihfft, _pocketfft.ihfft2, _pocketfft.ihfftn,
+            _pocketfft.dct, _pocketfft.idct, _pocketfft.dctn, _pocketfft.idctn,
+            _pocketfft.dst, _pocketfft.idst, _pocketfft.dstn, _pocketfft.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", 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", 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ed32d54c8936b8b36ff52ef7b639d05338a783c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py
@@ -0,0 +1,502 @@
+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.conftest import array_api_compatible
+from scipy._lib._array_api import (
+    array_namespace, xp_size, xp_assert_close, xp_assert_equal
+)
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+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):
+    if func in [fft.fft, fft.fftn, fft.fft2,
+                fft.ifft, fft.ifftn, fft.ifft2,
+                fft.hfft, fft.hfftn, fft.hfft2,
+                fft.irfft, fft.irfftn, fft.irfft2]:
+        dtype = xp.complex128
+    elif func in [fft.rfft, fft.rfftn, fft.rfft2,
+                  fft.ihfft, fft.ihfftn, fft.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:
+
+    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')
+    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])
+
+    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`')
+    def test_fft_n(self, xp):
+        x = xp.asarray([1, 2, 3], dtype=xp.complex128)
+        assert_raises(ValueError, fft.fft, x, 0)
+
+    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)
+
+    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))
+
+    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))
+
+    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))
+
+    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)
+
+    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))
+            )
+
+    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)
+
+    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))
+
+    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)
+
+    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))
+
+    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)
+
+    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)
+
+    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)
+
+    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)
+
+    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))
+
+    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)
+
+    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)]
+        xp_test = array_namespace(x)
+        for a in axes:
+            op_tr = op(xp_test.permute_dims(x, axes=a))
+            tr_op = xp_test.permute_dims(op(x, axes=a), axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn, fft.rfftn, fft.irfftn])
+    def test_axes_standard(self, op, xp):
+        self._check_axes(op, xp)
+
+    @pytest.mark.parametrize("op", [fft.hfftn, fft.ihfftn])
+    def test_axes_non_standard(self, op, xp):
+        self._check_axes(op, xp)
+
+    @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn,
+                                    fft.rfftn, 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)]
+        xp_test = array_namespace(x)
+        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_test.permute_dims(x, axes=a),
+                       s=shape[:2], axes=(0, 1))
+            tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]),
+                                         axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    @pytest.mark.parametrize("op", [fft.fft2, fft.ifft2,
+                                    fft.rfft2, fft.irfft2,
+                                    fft.hfft2, fft.ihfft2,
+                                    fft.hfftn, 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)]
+        xp_test = array_namespace(x)
+        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_test.permute_dims(x, axes=a), s=shape[:2], axes=(0, 1))
+            tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]), axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    def test_all_1d_norm_preserving(self, xp):
+        # verify that round-trip transforms are norm-preserving
+        x = xp.asarray(random(30), dtype=xp.float64)
+        xp_test = array_namespace(x)
+        x_norm = xp_test.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_test.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_test.linalg.vector_norm(tmp), x_norm)
+
+    @skip_xp_backends(np_only=True)
+    @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)
+
+    @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)
+
+    @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)
+
+    @skip_xp_backends(np_only=True,
+                      reason='array-likes only supported for NumPy backend')
+    @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, 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), op(xp.asarray(x)))
+
+
+@skip_xp_backends(np_only=True)
+@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_array_almost_equal(X_res, Y_res)
+    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'
+            )
+
+    def test_fft(self, xp):
+        a = xp.ones(self.input_shape, dtype=xp.complex128)
+        self._test_mtsame(fft.fft, a, xp=xp)
+
+    def test_ifft(self, xp):
+        a = xp.full(self.input_shape, 1+0j)
+        self._test_mtsame(fft.ifft, a, xp=xp)
+
+    def test_rfft(self, xp):
+        a = xp.ones(self.input_shape)
+        self._test_mtsame(fft.rfft, a, xp=xp)
+
+    def test_irfft(self, xp):
+        a = xp.full(self.input_shape, 1+0j)
+        self._test_mtsame(fft.irfft, a, xp=xp)
+
+    def test_hfft(self, xp):
+        a = xp.ones(self.input_shape, dtype=xp.complex64)
+        self._test_mtsame(fft.hfft, a, xp=xp)
+
+    def test_ihfft(self, xp):
+        a = xp.ones(self.input_shape)
+        self._test_mtsame(fft.ihfft, a, xp=xp)
+
+
+@skip_xp_backends(np_only=True)
+@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)
+
+
+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", [fft.fft, fft.ifft, fft.rfft, fft.irfft,
+                                  fft.fftn, fft.ifftn,
+                                  fft.rfftn, fft.irfftn, fft.hfft, fft.ihfft])
+def test_non_standard_params(func, xp):
+    if func in [fft.rfft, fft.rfftn, fft.ihfft]:
+        dtype = xp.float64
+    else:
+        dtype = xp.complex128
+
+    if xp.__name__ != 'numpy':
+        x = xp.asarray([1, 2, 3], dtype=dtype)
+        # func(x) should not raise an exception
+        func(x)
+        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", [fft.fft, fft.ifft, fft.irfft,
+                                  fft.fftn, fft.ifftn,
+                                  fft.irfftn, 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..3480e165180baf3866ca7c99a313996a2dbbca49
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py
@@ -0,0 +1,206 @@
+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.conftest import array_api_compatible
+from scipy._lib._array_api import xp_assert_close, xp_assert_less, array_namespace
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+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 = np.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)
+    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)
+    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])
+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)
+
+    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)
+
+
+
+
+@pytest.mark.thread_unsafe
+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])
+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 = np.log(r[1]/r[0])
+
+    offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
+
+    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", [fht, 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])
+def test_gh_21661(xp, n):
+    one = xp.asarray(1.0)
+    xp_test = array_namespace(one)
+    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_test.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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..4333886555ffbbb0831f830456a3290f32e317fa
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py
@@ -0,0 +1,574 @@
+"""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.conftest import array_api_compatible
+from scipy._lib._array_api import (
+    xp_assert_close, get_xp_devices, xp_device, array_namespace
+)
+from scipy import fft
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+_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}'
+
+
+@skip_xp_backends(np_only=True)
+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
+
+@skip_xp_backends(np_only=True)
+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)
+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)
+
+
+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)
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8393')
+    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)
+    
+    @skip_xp_backends('cupy', reason='cupy/cupy#8393')
+    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)
+
+
+@skip_xp_backends("cupy",
+                  reason="CuPy has not implemented the `device` param")
+@skip_xp_backends("jax.numpy",
+                  reason="JAX has not implemented the `device` param")
+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):
+        xp_test = array_namespace(xp.empty(0))
+        devices = get_xp_devices(xp)
+        for d in devices:
+            y = fft.fftfreq(9, xp=xp, device=d)
+            x = xp_test.empty(0, device=d)
+            assert xp_device(y) == xp_device(x)
+
+
+@skip_xp_backends("cupy",
+                  reason="CuPy has not implemented the `device` param")
+@skip_xp_backends("jax.numpy",
+                  reason="JAX has not implemented the `device` param")
+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):
+        xp_test = array_namespace(xp.empty(0))
+        devices = get_xp_devices(xp)
+        for d in devices:
+            y = fft.rfftfreq(9, xp=xp, device=d)
+            x = xp_test.empty(0, device=d)
+            assert xp_device(y) == xp_device(x)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a6b71b830211f8bcbe56e97ff71098be75021c8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..890dc79640aff571262f5a12f721f62f5c907069
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py
@@ -0,0 +1,249 @@
+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.conftest import array_api_compatible
+from scipy._lib._array_api import xp_copy, xp_assert_close
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+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
+
+
+@skip_xp_backends(cpu_only=True)
+@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)
+
+
+@skip_xp_backends(np_only=True,
+                  reason='`overwrite_x` only supported for NumPy backend.')
+@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)
+
+
+@skip_xp_backends(cpu_only=True)
+@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)
+
+
+@skip_xp_backends(np_only=True,
+                  reason='`overwrite_x` only supported for NumPy backend.')
+@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)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("func", ['dct', 'dst', 'dctn', '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)(x, type, norm=norm))
+    x = xp.asarray(x)
+    fft_res = getattr(fft, func)(x, type, norm=norm)
+
+    xp_assert_close(fft_res, fftpack_res)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("func", [dct, dst, dctn, 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)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func, type", [
+    (dct, 4), (dst, 1), (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)
+
+
+@skip_xp_backends('jax.numpy',
+                  reason='jax arrays do not support item assignment',
+                  cpu_only=True)
+@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)
+    x2[0] *= SQRT_2
+    x2[-1] *= SQRT_2
+
+    y1 = dct(x, type=1, norm=norm, orthogonalize=True)
+    y2 = dct(x2, type=1, norm=norm, orthogonalize=False)
+
+    y2[0] /= SQRT_2
+    y2[-1] /= SQRT_2
+    xp_assert_close(y1, y2)
+
+
+@skip_xp_backends('jax.numpy',
+                  reason='jax arrays do not support item assignment',
+                  cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func", [dct, 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)
+
+    y2[0 if func == dct else -1] /= SQRT_2
+    xp_assert_close(y1, y2)
+
+
+@skip_xp_backends('jax.numpy',
+                  reason='jax arrays do not support item assignment',
+                  cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func", [dct, dst])
+def test_orthogonalize_dcst3(func, norm, xp):
+    x = xp.asarray(np.random.rand(100))
+    x2 = xp_copy(x, xp=xp)
+    x2[0 if func == dct else -1] *= 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)
+
+@skip_xp_backends(np_only=True,
+                  reason='array-likes only supported for NumPy backend')
+@pytest.mark.parametrize("func", [dct, idct, dctn, idctn, dst, idst, dstn, idstn])
+def test_array_like(xp, 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(xp.asarray(x)))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..10f4b39e48e2d6c0b042582ca65f572bde6ba575
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/_basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..59c85ae4b364464a66489ef221f7f7ac45624694
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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 _pocketfft
+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 _pocketfft.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 _pocketfft.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 _pocketfft.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 _pocketfft.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 _pocketfft.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
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.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
+    """
+    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
+
+    """
+    return ifftn(x,shape,axes,overwrite_x)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/_helper.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..7892543732906dcd86b4c1aa9c1f249af701c137
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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._pocketfft.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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dbcc8d3979b35c1497266fea34cf565cd3d11d7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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._pocketfft.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.
+
+    """
+    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`.
+
+    """
+    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
+
+    """
+    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.
+
+    """
+    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``
+
+    """
+    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``.
+    """
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad71d517b0ac829ab71850bf67f7dc38636161f2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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 _pocketfft
+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 _pocketfft.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 _pocketfft.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 _pocketfft.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 _pocketfft.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 _pocketfft.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 _pocketfft.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 _pocketfft.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 _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..553f456fe1561c28928ecc4ebe2238459cc60443
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/helper.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcc7000c215f8a7605a2a59b5767b27b2fcd969d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecf71ad3256d48d2131c8058072da724cb001af9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/realtransforms.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a392198fccf213bc988a79058bd69515e39f510
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..2951471d2abb5c4a88ae0b44c172d3ecc0862d4d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py
@@ -0,0 +1,879 @@
+# 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="size=%d" % size)
+            assert_array_almost_equal(y2, x, decimal=self.ndec,
+                                       err_msg="size=%d" % 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e7be04f3c0291502b50b101db82d299aadc7772
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py
new file mode 100644
index 0000000000000000000000000000000000000000..e71aec9bd07cd4ef486b7e74b9589b6f1634d629
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a92729626a280c12aa3197e99b0d58ce00812d9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..876af8f18a312f88c508c6b2ae96f1e5c1dad96d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py
@@ -0,0 +1,837 @@
+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['x%d' % i] for i in range(8)]
+Y = [MDATA['y%d' % 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['dct_%d_%d' % (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['dst_%d_%d' % (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="Size %d failed" % i)
+
+    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="Size %d failed" % i)
+
+
+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="Size %d failed" % i)
+
+
+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="Size %d failed" % i)
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1533b5c60b695fce0abf08e2163dfba3bdd4fb17
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc316c71b33205689742e089c006e038978a1dc6
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09adf6b5af49a9c4a98e75e7ade37769e92b5094
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_cubature.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_cubature.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56b6c629a48265365767e6664b7d7c0ac4cd040c
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_cubature.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91bcf255bba4dfdfd3c7765a55ba557d50a586a3
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9aed2da2eb04baf985785042f2c485af35bdd82c
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..699ee78f1c035e9aaaa5032bc55eba6576c763dd
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04ffede0c4c24783e75bc2488343a93222432732
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39a93f0920ef954dd119877abc75bcbe7d5cddfa
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42e6504b041b79dc2ab876236ffb37b772d9c9e8
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8305b5734bcae14c7af97064d38b0697399219ba
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a36ac4d37fb02a8d92fdeef35bdce6f48203f503
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/odepack.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/odepack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f84fa5afc0a0606ed7fed70c21d565f5f900834f
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/odepack.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a82bded90ae76beb7ca43372ff802d0a5bea559
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69f7379092d13b9b3c3c90aeaa8a54cf9b59118b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_bvp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_bvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..74406c89a689edc3de21fcb7274c90d41b8d2dcc
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_bvp.py
@@ -0,0 +1,1154 @@
+"""Boundary value problem solver."""
+from warnings import warn
+
+import numpy as np
+from numpy.linalg import pinv
+
+from scipy.sparse import coo_matrix, csc_matrix
+from scipy.sparse.linalg import splu
+from scipy.optimize import OptimizeResult
+
+
+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_matrix, 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()))
+
+    J = coo_matrix((values, (i_jac, j_jac)))
+    return csc_matrix(J)
+
+
+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 is supposed to
+        return csc_matrix.
+    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"
+    """
+    # 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
+
+
+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,).
+    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
+    -------
+    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 : string
+        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".
+    .. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+           Boundary Value Problems for Ordinary Differential Equations".
+    .. [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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_cubature.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_cubature.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e6d8911d13eeaa2420ef65a12e9b4ba34400ca0
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_cubature.py
@@ -0,0 +1,728 @@
+import math
+import heapq
+import itertools
+
+from dataclasses import dataclass, field
+from types import ModuleType
+from typing import Any, TypeAlias
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_copy,
+    xp_broadcast_promote
+)
+from scipy._lib._util import MapWrapper
+
+from scipy.integrate._rules import (
+    ProductNestedFixed,
+    GaussKronrodQuadrature,
+    GenzMalikCubature,
+)
+from scipy.integrate._rules._base import _split_subregion
+
+__all__ = ['cubature']
+
+Array: TypeAlias = 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
+
+
+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_broadcast_promote(a, b, *points, force_floating=True)
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3c8aaa36588651ae5e48b58fbb1d443bc71fc77
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4ac0dc09ac682a9f0082a27da39a8f5f0372c72
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a8d9cae6d554af3803a656d2f35468028311640
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6072f48f6f7ba8dd38a08057e4cf194a7db423cc
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9711782377172cf034afd969af7f9494785f5b21
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..14628663b716cb64421a8d54876618dc62e26ab1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c7587d9b83f75cfb5e461d2c491f65c60679bada
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0b55014ace7f3604dc4261690aa6dc215b5ee50
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b70f0a5a86d737689f3cd3870f23b831e431f105
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a72183244b0cb1fe2dc76fc25c8956008bd7d55a
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..46db9a69dfb3e7aee5c150ac6795234cd455dfe5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py
@@ -0,0 +1,290 @@
+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 : string
+        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."
+
+    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 : string 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.
+
+    Attributes
+    ----------
+    t_min, t_max : float
+        Time range of the interpolation.
+    """
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..33b47a642b976e623edc9047f6465e328095dcd2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py
@@ -0,0 +1,478 @@
+import numpy as np
+from scipy.linalg import lu_factor, lu_solve
+from scipy.sparse import issparse, csc_matrix, eye
+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.
+    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 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_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_matrix, 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, 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 : {None, array_like, sparse 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)``).
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        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(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 = csc_matrix(sparsity)
+                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 = csc_matrix(J, dtype=y0.dtype)
+
+                def jac_wrapped(t, y):
+                    self.njev += 1
+                    return csc_matrix(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 = csc_matrix(jac, dtype=y0.dtype)
+            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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c820ad97f5a26955e20f98d80b71168dac54b0a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py
@@ -0,0 +1,451 @@
+from itertools import groupby
+from warnings import warn
+import numpy as np
+from scipy.sparse import find, coo_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 : boolean
+        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, `structure` must be csc_matrix.
+
+    Returns
+    -------
+    J : ndarray 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))
+    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 = coo_matrix((df[i, groups[j]], (i, j)), shape=(n, n)).tocsc()
+    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)
+        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))
+        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 = coo_matrix((df[i, groups_map[groups[ind[j]]]],
+                               (i, j)), shape=(n, ind.shape[0])).tocsc()
+
+        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 diff, factor
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
new file mode 100644
index 0000000000000000000000000000000000000000..f39f2f3650d321e2c475d4e220f9769139118a5e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py
new file mode 100644
index 0000000000000000000000000000000000000000..8186982e4fddbd8c1058b59c745ca66ab3a9c224
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py
@@ -0,0 +1,755 @@
+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
+
+
+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]
+
+
+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 : string 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
+    -------
+    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 : string
+        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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a5a7c530c04eddc9beff44e2d4f6df439d5ef01
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py
@@ -0,0 +1,224 @@
+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.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        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
+            self.y = solver._y
+            # 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d572b48de51ebc7e8f8fd278ce1000bdef581b5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py
@@ -0,0 +1,572 @@
+import numpy as np
+from scipy.linalg import lu_factor, lu_solve
+from scipy.sparse import csc_matrix, issparse, eye
+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.
+    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 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_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_matrix, 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, 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 : {None, array_like, sparse 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)``).
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        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)
+
+            I = eye(self.n, format='csc')
+        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 = csc_matrix(sparsity)
+                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 = csc_matrix(J)
+
+                def jac_wrapped(t, y, _=None):
+                    self.njev += 1
+                    return csc_matrix(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 = csc_matrix(jac)
+            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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py
new file mode 100644
index 0000000000000000000000000000000000000000..62a5347ffe91afc754e9b818d0b34c010d0c4d12
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py
@@ -0,0 +1,601 @@
+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.
+    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 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.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        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.
+    """
+    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.
+    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 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.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        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.
+    """
+    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.
+    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 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.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd318b9a165051293ac13b9b0e63be2df322963b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
@@ -0,0 +1,1287 @@
+from itertools import product
+from numpy.testing import (assert_, assert_allclose, assert_array_less,
+                           assert_equal, assert_no_warnings, suppress_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 coo_matrix, 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_matrix([
+        [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_matrix((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_matrix(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)
+
+@pytest.mark.thread_unsafe
+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 suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "The following arguments have no effect for a chosen "
+                       "solver: `jac`")
+            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)
+
+
+@pytest.mark.thread_unsafe
+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 suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "The following arguments have no effect for a chosen "
+                       "solver: `jac`")
+            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)
+
+
+@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_matrix(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))
+
+
+@pytest.mark.thread_unsafe
+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 suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "The following arguments have no effect for a chosen "
+                       "solver: `jac`")
+            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)
+
+
+def test_num_jac_sparse():
+    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 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])
+
+
+@pytest.mark.thread_unsafe
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py
new file mode 100644
index 0000000000000000000000000000000000000000..33cb27d0323d037c0937ab94b4de8f63b46be3d7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_lebedev.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_lebedev.py
new file mode 100644
index 0000000000000000000000000000000000000000..da200972f9d475162f84294ed335149dc86fe94b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_lebedev.py
@@ -0,0 +1,5450 @@
+# 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
+
+
+__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
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ode.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ode.py
new file mode 100644
index 0000000000000000000000000000000000000000..72d9da2495da768753f45796e8df1996cd70d382
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_ode.py
@@ -0,0 +1,1388 @@
+# 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 threading
+import warnings
+
+from numpy import asarray, array, zeros, isscalar, real, imag, vstack
+
+from . import _vode
+from . import _dop
+from . import _lsoda
+
+
+_dop_int_dtype = _dop.types.intvar.dtype
+_vode_int_dtype = _vode.types.intvar.dtype
+_lsoda_int_dtype = _lsoda.types.intvar.dtype
+
+
+# lsoda, vode and zvode are not thread-safe. VODE_LOCK protects both vode and
+# zvode; they share the `def run` implementation
+LSODA_LOCK = threading.Lock()
+VODE_LOCK = threading.Lock()
+
+
+# ------------------------------------------------------------------------------
+# 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
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "vode" integrator at the same time.
+
+        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
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "zvode" integrator at the same time.
+
+        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).
+
+        Source: http://www.netlib.org/odepack
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "lsoda" integrator at the same time.
+
+        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".
+
+    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        ]
+
+    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)
+
+    """
+
+    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
+        self._y = asarray(y, self._integrator.scalar)
+        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
+        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 is a real-valued array containing the interleaved
+        # real and imaginary parts of f.
+        self.tmp[::2] = real(f)
+        self.tmp[1::2] = imag(f)
+        return self.tmp
+
+    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)
+        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
+
+    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
+
+
+def _vode_banded_jac_wrapper(jacfunc, ml, jac_params):
+    """
+    Wrap a banded Jacobian function with a function that pads
+    the Jacobian with `ml` rows of zeros.
+    """
+
+    def jac_wrapper(t, y):
+        jac = asarray(jacfunc(t, y, *jac_params))
+        padded_jac = vstack((jac, zeros((ml, jac.shape[1]))))
+        return padded_jac
+
+    return jac_wrapper
+
+
+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
+    active_global_handle = 0
+
+    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
+
+        self.initialized = False
+
+    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,), _vode_int_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
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        if self.initialized:
+            self.check_handle()
+        else:
+            self.initialized = True
+            self.acquire_new_handle()
+
+        if self.ml is not None and self.ml > 0:
+            # Banded Jacobian. Wrap the user-provided function with one
+            # that pads the Jacobian array with the extra `self.ml` rows
+            # required by the f2py-generated wrapper.
+            jac = _vode_banded_jac_wrapper(jac, self.ml, jac_params)
+
+        args = ((f, jac, y0, t0, t1) + tuple(self.call_args) +
+                (f_params, jac_params))
+
+        with VODE_LOCK:
+            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
+    active_global_handle = 0
+
+    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,), _vode_int_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
+
+
+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)',
+                }
+
+    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
+        iwork = zeros((21,), _dop_int_dtype)
+        iwork[0] = self.nsteps
+        iwork[2] = self.verbosity
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork]
+        self.success = 1
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        x, y, iwork, 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, nr, xold, x, y, nd, icomp, con):
+        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, 'dop853', 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
+        iwork = zeros((21,), _dop_int_dtype)
+        iwork[0] = self.nsteps
+        iwork[2] = self.verbosity
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork]
+        self.success = 1
+
+
+if dop853.runner is not None:
+    IntegratorBase.integrator_classes.append(dop853)
+
+
+class lsoda(IntegratorBase):
+    runner = getattr(_lsoda, 'lsoda', None)
+    active_global_handle = 0
+
+    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)."
+    }
+
+    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
+
+    def reset(self, n, has_jac):
+        # Calculate parameters for Fortran subroutine dvode.
+        if has_jac:
+            if self.mu is None and self.ml is None:
+                jt = 1
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 4
+        else:
+            if self.mu is None and self.ml is None:
+                jt = 2
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 5
+        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
+        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,), _lsoda_int_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
+        self.initialized = False
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        if self.initialized:
+            self.check_handle()
+        else:
+            self.initialized = True
+            self.acquire_new_handle()
+        args = [f, y0, t0, t1] + self.call_args[:-1] + \
+               [jac, self.call_args[-1], f_params, 0, jac_params]
+
+        with LSODA_LOCK:
+            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 lsoda.runner:
+    IntegratorBase.integrator_classes.append(lsoda)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..75dfe925b312ae609d19ccbec27927c6c945176f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py
@@ -0,0 +1,273 @@
+# Author: Travis Oliphant
+
+__all__ = ['odeint', 'ODEintWarning']
+
+import numpy as np
+from . import _odepack
+from copy import copy
+import warnings
+
+from threading import Lock
+
+
+ODE_LOCK = Lock()
+
+
+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)."
+         }
+
+
+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)
+
+    with ODE_LOCK:
+        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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..758bac5138777dbe152c2b455b5160196d2282ca
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py
@@ -0,0 +1,682 @@
+import sys
+import copy
+import heapq
+import collections
+import functools
+import warnings
+
+import numpy as np
+
+from scipy._lib._util import MapWrapper, _FunctionWrapper
+
+
+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):
+        # 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))
+
+
+def _get_sizeof(obj):
+    try:
+        return sys.getsizeof(obj)
+    except TypeError:
+        # occurs on pypy
+        if hasattr(obj, '__sizeof__'):
+            return int(obj.__sizeof__())
+        return 64
+
+
+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})"
+
+
+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`` dictionary.
+    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 : dict
+        Returned only when ``full_output=True``.
+        Info dictionary. Is an 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,
+                       'trapz': _quadrature_trapezoid,  # alias for backcompat
+                       'trapezoid': _quadrature_trapezoid}[quadrature]
+    except KeyError as e:
+        raise ValueError(f"unknown quadrature {quadrature!r}") from e
+
+    if quadrature == "trapz":
+        msg = ("`quadrature='trapz'` is deprecated in favour of "
+               "`quadrature='trapezoid' and will raise an error from SciPy 1.16.0 "
+               "onwards.")
+        warnings.warn(msg, DeprecationWarning, stacklevel=2)
+
+    # 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 // _get_sizeof(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
+_quadrature_trapezoid.num_eval = 3
+
+
+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
+
+
+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
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d273f6d2c9943f4a35f9b0c761a944b7be84cfe
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py
@@ -0,0 +1,1279 @@
+# 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
+
+__all__ = ["quad", "dblquad", "tplquad", "nquad", "IntegrationWarning"]
+
+
+class IntegrationWarning(UserWarning):
+    """
+    Warning on issues during integration.
+    """
+    pass
+
+
+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.
+    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".
+
+    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.
+
+    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 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.
+    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,)
+
+    # 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})
+
+
+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.
+    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})
+
+
+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.
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quadrature.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quadrature.py
new file mode 100644
index 0000000000000000000000000000000000000000..44cf10b32335014cd7cb26459c8dc89ac8f851ff
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_quadrature.py
@@ -0,0 +1,1336 @@
+import numpy as np
+import numpy.typing as npt
+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_broadcast_promote
+
+
+__all__ = ['fixed_quad', 'romb',
+           'trapezoid', 'simpson',
+           'cumulative_trapezoid', 'newton_cotes',
+           'qmc_quad', 'cumulative_simpson']
+
+
+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_broadcast_promote(y, force_floating=True, xp=xp)[0].dtype
+    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()
+
+
+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
+
+    """
+    x, w = _cached_roots_legendre(n)
+    x = np.real(x)
+    if np.isinf(a) or np.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 * np.sum(w*func(y, *args), axis=-1), None
+
+
+def tupleset(t, i, value):
+    l = list(t)
+    l[i] = value
+    return tuple(l)
+
+
+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()
+
+    """
+    y = np.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 = np.asarray(x)
+        if x.ndim == 1:
+            d = np.diff(x)
+            # reshape to correct shape
+            shape = [1] * y.ndim
+            shape[axis] = -1
+            d = d.reshape(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 = np.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 = np.cumsum(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 = np.concatenate([np.full(shape, initial, dtype=res.dtype), res],
+                             axis=axis)
+
+    return res
+
+
+def _basic_simpson(y, start, stop, x, dx, axis):
+    nd = len(y.shape)
+    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 = np.sum(y[slice0] + 4.0*y[slice1] + y[slice2], axis=axis)
+        result *= dx / 3.0
+    else:
+        # Account for possibly different spacings.
+        #    Simpson's rule changes a bit.
+        h = np.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].astype(float, copy=False)
+        h1 = h[sl1].astype(float, copy=False)
+        hsum = h0 + h1
+        hprod = h0 * h1
+        h0divh1 = np.true_divide(h0, h1, out=np.zeros_like(h0), where=h1 != 0)
+        tmp = hsum/6.0 * (y[slice0] *
+                          (2.0 - np.true_divide(1.0, h0divh1,
+                                                out=np.zeros_like(h0divh1),
+                                                where=h0divh1 != 0)) +
+                          y[slice1] * (hsum *
+                                       np.true_divide(hsum, hprod,
+                                                      out=np.zeros_like(hsum),
+                                                      where=hprod != 0)) +
+                          y[slice2] * (2.0 - h0divh1))
+        result = np.sum(tmp, axis=axis)
+    return result
+
+
+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
+
+    """
+    y = np.asarray(y)
+    nd = len(y.shape)
+    N = y.shape[axis]
+    last_dx = dx
+    returnshape = 0
+    if x is not None:
+        x = np.asarray(x)
+        if len(x.shape) == 1:
+            shapex = [1] * nd
+            shapex[axis] = x.shape[0]
+            saveshape = x.shape
+            returnshape = 1
+            x = x.reshape(tuple(shapex))
+        elif len(x.shape) != len(y.shape):
+            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)
+
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            slice3 = tupleset(slice_all, axis, -3)
+
+            h = np.asarray([dx, dx], dtype=np.float64)
+            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 = np.float64(np.diff(x, axis=axis))
+                h = [np.squeeze(diffs[hm2], axis=axis),
+                     np.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 = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            num = h[1] ** 2 + 3.0 * h[0] * h[1]
+            den = 6 * h[0]
+            beta = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            num = 1 * h[1] ** 3
+            den = 6 * h[0] * (h[0] + h[1])
+            eta = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            result += alpha*y[slice1] + beta*y[slice2] - eta*y[slice3]
+
+        result += val
+    else:
+        result = _basic_simpson(y, 0, N-2, x, dx, axis)
+    if returnshape:
+        x = x.reshape(saveshape)
+    return result
+
+
+def _cumulatively_sum_simpson_integrals(
+    y: np.ndarray, 
+    dx: np.ndarray, 
+    integration_func: Callable[[np.ndarray, np.ndarray], np.ndarray],
+) -> 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 = integration_func(y[..., ::-1], dx[..., ::-1])[..., ::-1]
+    
+    shape = list(sub_integrals_h1.shape)
+    shape[-1] += 1
+    sub_integrals = np.empty(shape)
+    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 = np.cumsum(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)
+
+
+def _ensure_float_array(arr: npt.ArrayLike) -> np.ndarray:
+    arr = np.asarray(arr)
+    if np.issubdtype(arr.dtype, np.integer):
+        arr = arr.astype(float, copy=False)
+    return arr
+
+
+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.
+
+    """
+    y = _ensure_float_array(y)
+
+    # validate `axis` and standardize to work along the last axis
+    original_y = y
+    original_shape = y.shape
+    try:
+        y = np.swapaxes(y, axis, -1)
+    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 = np.swapaxes(res, axis, -1)
+
+    elif x is not None:
+        x = _ensure_float_array(x)
+        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 len(x) == original_shape[axis])):
+            raise ValueError(message)
+
+        x = np.broadcast_to(x, y.shape) if x.ndim == 1 else np.swapaxes(x, axis, -1)
+        dx = np.diff(x, axis=-1)
+        if np.any(dx <= 0):
+            raise ValueError("Input x must be strictly increasing.")
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_unequal_intervals
+        )
+
+    else:
+        dx = _ensure_float_array(dx)
+        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 = np.broadcast_to(dx, final_dx_shape)
+        dx = np.swapaxes(dx, axis, -1)
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_equal_intervals
+        )
+
+    if initial is not None:
+        initial = _ensure_float_array(initial)
+        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 = np.broadcast_to(initial, alt_initial_input_shape)
+        initial = np.swapaxes(initial, axis, -1)
+
+        res += initial
+        res = np.concatenate((initial, res), axis=-1)
+
+    res = np.swapaxes(res, -1, axis)
+    return res
+
+
+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
+
+    """
+    y = np.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 * np.asarray(dx, dtype=float)
+    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*y[slice_R].sum(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 = "%%%d.%df" % (width, precis)
+
+            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)
+    }
+
+
+def newton_cotes(rn, equal=0):
+    r"""
+    Return weights and error coefficient for Newton-Cotes integration.
+
+    Suppose we have (N+1) samples of f at the positions
+    x_0, x_1, ..., x_N. Then an N-point Newton-Cotes formula for the
+    integral between x_0 and 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):
+
+    # 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 = np.atleast_1d(a).copy()
+    b = np.atleast_1d(b).copy()
+    a, b = np.broadcast_arrays(a, 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(np.array([a, b]).T)
+        vfunc = func
+    except Exception as e:
+        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 = np.int64(n_points)
+    if n_points != n_points_int:
+        message = "`n_points` must be an integer."
+        raise TypeError(message)
+
+    n_estimates_int = np.int64(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'])
+
+
+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 : 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 : boolean, 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
+
+    """
+    args = _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log)
+    func, a, b, n_points, n_estimates, qrng, rng, log, stats = args
+
+    def sum_product(integrands, dA, log=False):
+        if log:
+            return logsumexp(integrands) + np.log(dA)
+        else:
+            return np.sum(integrands * dA)
+
+    def mean(estimates, log=False):
+        if log:
+            return logsumexp(estimates) - np.log(n_estimates)
+        else:
+            return np.mean(estimates)
+
+    def std(estimates, m=None, ddof=0, log=False):
+        m = m or mean(estimates, log)
+        if log:
+            estimates, m = np.broadcast_arrays(estimates, m)
+            temp = np.vstack((estimates, m + np.pi * 1j))
+            diff = logsumexp(temp, axis=0)
+            return np.real(0.5 * (logsumexp(2 * diff)
+                                  - np.log(n_estimates - ddof)))
+        else:
+            return np.std(estimates, ddof=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*np.log(n_estimates)
+        else:
+            return s / np.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 np.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)
+        return QMCQuadResult(-np.inf if log else 0, 0)
+
+    i_swap = b < a
+    sign = (-1)**(i_swap.sum(axis=-1))  # odd # of swaps -> negative
+    a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+
+    A = np.prod(b - a)
+    dA = A / n_points
+
+    estimates = np.zeros(n_estimates)
+    rngs = _rng_spawn(qrng.rng, n_estimates)
+    for i in range(n_estimates):
+        # Generate integral estimate
+        sample = qrng.random(n_points)
+        # 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 = stats.qmc.scale(sample, a, b).T  # (n_dim, n_points)
+        integrands = func(x)
+        estimates[i] = 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 + np.pi*1j if (log and sign < 0) else integral*sign
+    return QMCQuadResult(integral, standard_error)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c91aa324478d49a8723f05618801f9b256d07af
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80400c5e3114c23484c822876caa2f72a86fbbab
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6af8d3df235c618917589d18f5de19f6385b4cb7
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..699445a90a001bc85411a6c799680fe812a2be5c
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..615ca06d5d6f4c4ecd7c5a390b94d0b3712ab7bd
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..637e9d41f783d86654b636a10b423f9b382368ad
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_base.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a3ae5f506505c9c03b2ac8be33d301d60074681
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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.asarray([a[i], split_at[i]]) for i in range(a.shape[0])]
+    right = [xp.asarray([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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2a3518c55cf49cd14c777d243ea7e93a489f86c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_legendre.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_legendre.py
new file mode 100644
index 0000000000000000000000000000000000000000..1163aec5370fb93951402ab99ee2ae4b79158d52
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_genz_malik.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_genz_malik.py
new file mode 100644
index 0000000000000000000000000000000000000000..4873805e3364b10a3366de47c15fe3c4b306e5d6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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, https://doi.org/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py
new file mode 100644
index 0000000000000000000000000000000000000000..de1d844f88f999d96d4616d8060b0b47de1d8dbe
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py
@@ -0,0 +1,1384 @@
+# 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_real, xp_take_along_axis)
+
+
+__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`.
+#  Add heuristic to stop when improvement is too slow / antithrashing
+#  support singularities? interval subdivision? this feature will be added
+#    eventually, but do we adjust the interface now?
+#  When doing log-integration, should the tolerances control the error of the
+#    log-integral or the error of the integral?  The trouble is that `log`
+#    inherently looses some precision so it may not be possible to refine
+#    the integral further. Example: 7th moment of stats.f(15, 20)
+#  respect function evaluation limit?
+#  make public?
+
+
+def tanhsinh(f, a, b, *, args=(), 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``.
+    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.  Iteration will stop when
+        ``res.error < atol`` or  ``res.error < res.integral * rtol``. The error
+        estimate is as described in [1]_ Section 5 but with a lower bound of
+        ``eps * res.integral``. While not theoretically rigorous or
+        conservative, it is said to work well in practice. 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.
+    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 `_differentiate` (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]_.
+
+    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, preserve_shape, callback, xp) = _tanhsinh_iv(
+        f, a, b, log, maxfun, maxlevel, minlevel, atol,
+        rtol, args, 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, 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)
+        # use xp_real here to avoid cupy/cupy#8434
+        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):
+            dtype = res['integral'].dtype
+            pi = xp.asarray(xp.pi, dtype=dtype)[()]
+            j = xp.asarray(1j, dtype=xp.complex64)[()]  # minimum complex type
+            res['integral'] = res['integral'] + negative*pi*j
+        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, d5])
+        aerr = xp.max(ds, axis=0)
+        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, d5])
+        aerr = xp.max(ds, axis=0)
+        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, preserve_shape, callback):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a` and `b` must be real numbers.'
+    a, b = xp.asarray(a), xp.asarray(b)
+    a, b = xp.broadcast_arrays(a, b)
+    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,)
+    args = (xp.asarray(arg) for arg in 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, preserve_shape, callback, xp)
+
+
+def _nsum_iv(f, a, b, step, args, log, maxterms, tolerances):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a`, `b`, and `step` must be real numbers.'
+    a, b, step = xp.broadcast_arrays(xp.asarray(a), xp.asarray(b), xp.asarray(step))
+    dtype = xp.result_type(a.dtype, b.dtype, step.dtype)
+    if not xp.isdtype(dtype, 'numeric') or xp.isdtype(dtype, 'complex 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, log, maxterms_int, atol, rtol, xp
+
+
+def nsum(f, a, b, *, step=1, args=(), 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.
+    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.
+    atol, rtol : float, optional
+        Absolute termination tolerance (default: 0) and relative termination
+        tolerance (default: ``eps**0.5``, 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.
+
+    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, log, maxterms, tolerances)
+    f, a, b, step, valid_abstep, args, log, maxterms, atol, rtol, xp = tmp
+
+    # Additional elementwise algorithm input validation / standardization
+    tmp = eim._initialize(f, (a,), args, 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
+    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
+
+    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 < 0  # 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, xp.asarray(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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..fbe799fa8bfe4c5f1b2d2ed5edc07fe91db628ef
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/dop.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/dop.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf67a9a35b7d2959c2617aadc5638b577a45b9b5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/lsoda.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/lsoda.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bc1f1da3c4f0aefad9da73b6405b957ce9335b4
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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=["_lsoda"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/odepack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/odepack.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bb4c1a8c9be375df855abe6e1b30ca9711f2607
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/quadpack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/quadpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..144584988095c8855da8c34253c045f1a3940572
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test__quad_vec.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test__quad_vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..851d28f5671c3eb5821a7379547c1ba66a7e1340
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test__quad_vec.py
@@ -0,0 +1,217 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.integrate import quad_vec
+
+from multiprocessing.dummy import Pool
+
+
+quadrature_params = pytest.mark.parametrize(
+    'quadrature', [None, "gk15", "gk21", "trapezoid"])
+
+
+@quadrature_params
+def test_quad_vec_simple(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(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():
+    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)
+
+
+def _lorenzian(x):
+    return 1 / (1 + x**2)
+
+
+@pytest.mark.fail_slow(10)
+def test_quad_vec_pool():
+    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)
+
+
+def _func_with_args(x, a):
+    return x * (x + a) * np.arange(3)
+
+
+@pytest.mark.fail_slow(10)
+@pytest.mark.parametrize('extra_args', [2, (2,)])
+@pytest.mark.parametrize('workers', [1, 10])
+def test_quad_vec_pool_args(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(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():
+    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():
+    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(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])
+
+
+@pytest.mark.thread_unsafe
+def test_trapz_deprecation():
+    with pytest.deprecated_call(match="`quadrature='trapz'`"):
+        quad_vec(lambda x: x, 0, 1, quadrature="trapz")
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..358c5e3d1fcfe7ccd7e3691bd9af2f47656f4e2b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py
@@ -0,0 +1,220 @@
+import itertools
+import pytest
+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]
+    while r.successful() and r.t < tend:
+        r.integrate(r.t + dt)
+        t.append(r.t)
+        y.append(r.y)
+
+    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
+
+
+@pytest.mark.thread_unsafe
+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.
+
+    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)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ef9eb6ff0502e1113d6bea7ad1e0088633d3151
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py
@@ -0,0 +1,714 @@
+import sys
+
+try:
+    from StringIO import StringIO
+except ImportError:
+    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_matrix
+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_matrix((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
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_cubature.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_cubature.py
new file mode 100644
index 0000000000000000000000000000000000000000..899655c7631fbc86d06eb97c514761d4c882a632
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_cubature.py
@@ -0,0 +1,1389 @@
+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,
+)
+from scipy.conftest import array_api_compatible
+
+from scipy.integrate import cubature
+
+from scipy.integrate._rules import (
+    Rule, FixedRule,
+    NestedFixedRule,
+    GaussLegendreQuadrature, GaussKronrodQuadrature,
+    GenzMalikCubature,
+)
+
+from scipy.integrate._cubature import _InfiniteLimitsTransform
+
+pytestmark = [pytest.mark.usefixtures("skip_xp_backends"),]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+# 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))
+
+    # `xp` is the unwrapped namespace, so `.atan` won't work for `xp = np` and np<2.
+    xp_test = array_namespace(a)
+
+    return (
+        (-1)**ndim * 1/xp.prod(alphas, axis=-1)
+        * xp.prod(
+            xp_test.atan((a - betas)/alphas) - xp_test.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([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])
+
+
+@array_api_compatible
+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,
+        )
+
+    @skip_xp_backends(np_only=True,
+                      reason='array-likes only supported for NumPy backend')
+    def test_pass_array_like_not_array(self, xp):
+        n = np_compat.arange(5, dtype=np_compat.float64)
+        a = [0]
+        b = [2]
+
+        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_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),
+            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
+
+
+@pytest.mark.parametrize("rtol", [1e-4])
+@pytest.mark.parametrize("atol", [1e-5])
+@pytest.mark.parametrize("rule", [
+    "gk15",
+    "gk21",
+    "genz-malik",
+])
+@array_api_compatible
+class TestCubatureProblems:
+    """
+    Tests that `cubature` gives the correct answer.
+    """
+
+    @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}",
+        )
+
+    @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
+
+    @skip_xp_backends(
+        "jax.numpy",
+        reasons=["transforms make use of indexing assignment"],
+    )
+    @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,
+        )
+
+    @skip_xp_backends(
+        "jax.numpy",
+        reasons=["transforms make use of indexing assignment"],
+    )
+    @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,
+        )
+
+
+@array_api_compatible
+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,))
+
+
+@array_api_compatible
+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)
+
+
+@array_api_compatible
+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)
+
+
+@array_api_compatible
+@skip_xp_backends(
+    "jax.numpy",
+    reasons=["transforms make use of indexing assignment"],
+)
+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.
+        """
+
+        xp_compat = array_namespace(xp.empty(0))
+        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_compat),
+            xp.asarray(a, dtype=xp_compat.float64),
+            xp.asarray(b, dtype=xp_compat.float64),
+            xp=xp_compat,
+        )
+
+        for point in points:
+            transformed_point = f_transformed.inv(xp_compat.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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_integrate.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_integrate.py
new file mode 100644
index 0000000000000000000000000000000000000000..44bfecdaac0f00b413538510c61dd1317a076261
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_integrate.py
@@ -0,0 +1,840 @@
+# 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, assert_warns)
+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')
+
+    @pytest.mark.thread_unsafe
+    def test_concurrent_fail(self):
+        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)
+
+            assert_raises(RuntimeError, r.integrate, r.t + 0.1)
+
+    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)
+
+    @pytest.mark.thread_unsafe
+    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)
+        assert_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])
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_odeint_jac.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_odeint_jac.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d28ccc93f4444f3f2e0b71da01c573d4f903dbc
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_odeint_jac.py
@@ -0,0 +1,74 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+from scipy.integrate import odeint
+import scipy.integrate._test_odeint_banded as banded5x5
+
+
+def rhs(y, t):
+    dydt = np.zeros_like(y)
+    banded5x5.banded5x5(t, y, dydt)
+    return dydt
+
+
+def jac(y, t):
+    n = len(y)
+    jac = np.zeros((n, n), order='F')
+    banded5x5.banded5x5_jac(t, y, 1, 1, jac)
+    return jac
+
+
+def bjac(y, t):
+    n = len(y)
+    bjac = np.zeros((4, n), order='F')
+    banded5x5.banded5x5_bjac(t, y, 1, 1, bjac)
+    return bjac
+
+
+JACTYPE_FULL = 1
+JACTYPE_BANDED = 4
+
+
+def check_odeint(jactype):
+    if jactype == JACTYPE_FULL:
+        ml = None
+        mu = None
+        jacobian = jac
+    elif jactype == JACTYPE_BANDED:
+        ml = 2
+        mu = 1
+        jacobian = bjac
+    else:
+        raise ValueError(f"invalid jactype: {jactype!r}")
+
+    y0 = np.arange(1.0, 6.0)
+    # These tolerances must match the tolerances used in banded5x5.f.
+    rtol = 1e-11
+    atol = 1e-13
+    dt = 0.125
+    nsteps = 64
+    t = dt * np.arange(nsteps+1)
+
+    sol, info = odeint(rhs, y0, t,
+                       Dfun=jacobian, ml=ml, mu=mu,
+                       atol=atol, rtol=rtol, full_output=True)
+    yfinal = sol[-1]
+    odeint_nst = info['nst'][-1]
+    odeint_nfe = info['nfe'][-1]
+    odeint_nje = info['nje'][-1]
+
+    y1 = y0.copy()
+    # Pure Fortran solution. y1 is modified in-place.
+    nst, nfe, nje = banded5x5.banded5x5_solve(y1, nsteps, dt, jactype)
+
+    # It is likely that yfinal and y1 are *exactly* the same, but
+    # we'll be cautious and use assert_allclose.
+    assert_allclose(yfinal, y1, rtol=1e-12)
+    assert_equal((odeint_nst, odeint_nfe, odeint_nje), (nst, nfe, nje))
+
+
+def test_odeint_full_jac():
+    check_odeint(JACTYPE_FULL)
+
+
+def test_odeint_banded_jac():
+    check_odeint(JACTYPE_BANDED)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..e61a69df40f9b5975a6f02f40e6f72e34dbbf297
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py
@@ -0,0 +1,680 @@
+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)
+import pytest
+
+from scipy.integrate import quad, dblquad, tplquad, nquad
+from scipy.special import erf, erfc
+from scipy._lib._ccallback import LowLevelCallable
+
+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))
+
+
+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)
+
+
+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)
+
+
+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)
+
+    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)
+        ]
+    )
+    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
+        )
+
+    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)),
+        ],
+    )
+    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
+        )
+
+    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']
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadrature.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadrature.py
new file mode 100644
index 0000000000000000000000000000000000000000..0198b53093a79c15d2fd644956cb0d2862ca92a2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadrature.py
@@ -0,0 +1,732 @@
+# 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 array_api_compatible, skip_xp_invalid_arg
+from scipy._lib._array_api_no_0d import xp_assert_close
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+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
+        assert_allclose(got, expected, rtol=1e-12)
+
+    def test_vector(self):
+        n = 4
+        p = np.arange(1, 2*n)
+        expected = 1/(p + 1)
+        got, _ = fixed_quad(lambda x: x**p[:, None], 0, 1, n=n)
+        assert_allclose(got, expected, rtol=1e-12)
+
+
+class TestQuadrature:
+    def quad(self, x, a, b, args):
+        raise NotImplementedError
+
+    def test_romb(self):
+        assert_equal(romb(np.arange(17)), 128)
+
+    def test_romb_gh_3731(self):
+        # Check that romb makes maximal use of data points
+        x = np.arange(2**4+1)
+        y = np.cos(0.2*x)
+        val = romb(y)
+        val2, err = quad(lambda x: np.cos(0.2*x), x.min(), x.max())
+        assert_allclose(val, val2, rtol=1e-8, atol=0)
+
+    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)
+
+    def test_simpson(self):
+        y = np.arange(17)
+        assert_equal(simpson(y), 128)
+        assert_equal(simpson(y, dx=0.5), 64)
+        assert_equal(simpson(y, x=np.linspace(0, 4, 17)), 32)
+
+        # integral should be exactly 21
+        x = np.linspace(1, 4, 4)
+        def f(x):
+            return x**2
+
+        assert_allclose(simpson(f(x), x=x), 21.0)
+
+        # integral should be exactly 114
+        x = np.linspace(1, 7, 4)
+        assert_allclose(simpson(f(x), dx=2.0), 114)
+
+        # test multi-axis behaviour
+        a = np.arange(16).reshape(4, 4)
+        x = np.arange(64.).reshape(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
+                assert_allclose(r[it.multi_index], integral)
+
+        # test when integration axis only has two points
+        x = np.arange(16).reshape(8, 2)
+        y = f(x)
+        r = simpson(y, x=x, axis=-1)
+
+        integral = 0.5 * (y[:, 1] + y[:, 0]) * (x[:, 1] - x[:, 0])
+        assert_allclose(r, integral)
+
+        # odd points, test multi-axis behaviour
+        a = np.arange(25).reshape(5, 5)
+        x = np.arange(125).reshape(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
+                assert_allclose(r[it.multi_index], integral)
+
+        # Tests for checking base case
+        x = np.array([3])
+        y = np.power(x, 2)
+        assert_allclose(simpson(y, x=x, axis=0), 0.0)
+        assert_allclose(simpson(y, x=x, axis=-1), 0.0)
+
+        x = np.array([3, 3, 3, 3])
+        y = np.power(x, 2)
+        assert_allclose(simpson(y, x=x, axis=0), 0.0)
+        assert_allclose(simpson(y, x=x, axis=-1), 0.0)
+
+        x = np.array([[1, 2, 4, 8], [1, 2, 4, 8], [1, 2, 4, 8]])
+        y = np.power(x, 2)
+        zero_axis = [0.0, 0.0, 0.0, 0.0]
+        default_axis = [170 + 1/3] * 3   # 8**3 / 3 - 1/3
+        assert_allclose(simpson(y, x=x, axis=0), zero_axis)
+        # the following should be exact
+        assert_allclose(simpson(y, x=x, axis=-1), default_axis)
+
+        x = np.array([[1, 2, 4, 8], [1, 2, 4, 8], [1, 8, 16, 32]])
+        y = np.power(x, 2)
+        zero_axis = [0.0, 136.0, 1088.0, 8704.0]
+        default_axis = [170 + 1/3, 170 + 1/3, 32**3 / 3 - 1/3]
+        assert_allclose(simpson(y, x=x, axis=0), zero_axis)
+        assert_allclose(simpson(y, x=x, axis=-1), default_axis)
+
+
+    @pytest.mark.parametrize('droplast', [False, True])
+    def test_simpson_2d_integer_no_x(self, droplast):
+        # The inputs are 2d integer arrays.  The results should be
+        # identical to the results when the inputs are floating point.
+        y = np.array([[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(np.array(y, dtype=np.float64), axis=-1)
+        assert_equal(result, expected)
+
+
+class TestCumulative_trapezoid:
+    def test_1d(self):
+        x = np.linspace(-2, 2, num=5)
+        y = x
+        y_int = cumulative_trapezoid(y, x, initial=0)
+        y_expected = [0., -1.5, -2., -1.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, x, initial=None)
+        assert_allclose(y_int, y_expected[1:])
+
+    def test_y_nd_x_nd(self):
+        x = np.arange(3 * 2 * 4).reshape(3, 2, 4)
+        y = x
+        y_int = cumulative_trapezoid(y, x, initial=0)
+        y_expected = np.array([[[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]]])
+
+        assert_allclose(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_equal(y_int.shape, (3, 2, 4))
+            y_int = cumulative_trapezoid(y, x, initial=None, axis=axis)
+            assert_equal(y_int.shape, shape)
+
+    def test_y_nd_x_1d(self):
+        y = np.arange(3 * 2 * 4).reshape(3, 2, 4)
+        x = np.arange(4)**2
+        # Try with all axes
+        ys_expected = (
+            np.array([[[4., 5., 6., 7.],
+                       [8., 9., 10., 11.]],
+                      [[40., 44., 48., 52.],
+                       [56., 60., 64., 68.]]]),
+            np.array([[[2., 3., 4., 5.]],
+                      [[10., 11., 12., 13.]],
+                      [[18., 19., 20., 21.]]]),
+            np.array([[[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)
+            assert_allclose(y_int, y_expected)
+
+    def test_x_none(self):
+        y = np.linspace(-2, 2, num=5)
+
+        y_int = cumulative_trapezoid(y)
+        y_expected = [-1.5, -2., -1.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, initial=0)
+        y_expected = [0, -1.5, -2., -1.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, dx=3)
+        y_expected = [-4.5, -6., -4.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, dx=3, initial=0)
+        y_expected = [0, -4.5, -6., -4.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+    @pytest.mark.parametrize(
+        "initial", [1, 0.5]
+    )
+    def test_initial_error(self, initial):
+        """If initial is not None or 0, a ValueError is raised."""
+        y = np.linspace(0, 10, num=10)
+        with pytest.raises(ValueError, match="`initial`"):
+            cumulative_trapezoid(y, initial=initial)
+
+    def test_zero_len_y(self):
+        with pytest.raises(ValueError, match="At least one point is required"):
+            cumulative_trapezoid(y=[])
+
+
+@array_api_compatible
+class TestTrapezoid:
+    def test_simple(self, xp):
+        x = xp.arange(-10, 10, .1)
+        r = trapezoid(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))
+
+    @skip_xp_backends('jax.numpy',
+                      reasons=["JAX arrays do not support item assignment"])
+    @pytest.mark.usefixtures("skip_xp_backends")
+    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[0] /= 2
+        wx[-1] /= 2
+        wy = xp.ones_like(y) * (y[1] - y[0])
+        wy[0] /= 2
+        wy[-1] /= 2
+        wz = xp.ones_like(z) * (z[1] - z[0])
+        wz[0] /= 2
+        wz[-1] /= 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 = trapezoid(q, x=x[:, None, None], axis=0)
+        xp_assert_close(r, qx)
+        r = trapezoid(q, x=y[None,:, None], axis=1)
+        xp_assert_close(r, qy)
+        r = trapezoid(q, x=z[None, None,:], axis=2)
+        xp_assert_close(r, qz)
+
+        # 1-d `x`
+        r = trapezoid(q, x=x, axis=0)
+        xp_assert_close(r, qx)
+        r = trapezoid(q, x=y, axis=1)
+        xp_assert_close(r, qy)
+        r = trapezoid(q, x=z, axis=2)
+        xp_assert_close(r, qz)
+
+    @skip_xp_backends('jax.numpy',
+                      reasons=["JAX arrays do not support item assignment"])
+    @pytest.mark.usefixtures("skip_xp_backends")
+    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)
+
+    @skip_xp_backends(np_only=True,
+                      reasons=['array-likes only supported for NumPy backend'])
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_array_like(self, xp):
+        x = list(range(5))
+        y = [t * t for t in x]
+        xarr = xp.asarray(x, dtype=xp.float64)
+        yarr = xp.asarray(y, dtype=xp.float64)
+        res = trapezoid(y, x)
+        resarr = trapezoid(yarr, xarr)
+        xp_assert_close(res, resarr)
+
+
+class TestQMCQuad:
+    @pytest.mark.thread_unsafe
+    def test_input_validation(self):
+        message = "`func` must be callable."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad("a duck", [0, 0], [1, 1])
+
+        message = "`func` must evaluate the integrand at points..."
+        with pytest.raises(ValueError, match=message):
+            qmc_quad(lambda: 1, [0, 0], [1, 1])
+
+        def func(x):
+            assert x.ndim == 1
+            return np.sum(x)
+        message = "Exception encountered when attempting vectorized call..."
+        with pytest.warns(UserWarning, match=message):
+            qmc_quad(func, [0, 0], [1, 1])
+
+        message = "`n_points` must be an integer."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, [0, 0], [1, 1], n_points=1024.5)
+
+        message = "`n_estimates` must be an integer."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, [0, 0], [1, 1], 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, [0, 0], [1, 1], qrng="a duck")
+
+        message = "`qrng` must be initialized with dimensionality equal to "
+        with pytest.raises(ValueError, match=message):
+            qmc_quad(lambda x: 1, [0, 0], [1, 1], 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, [0, 0], [1, 1], log=10)
+
+    def basic_test(self, n_points=2**8, n_estimates=8, signs=None):
+        if signs is None:
+            signs = np.ones(2)
+        ndim = 2
+        mean = np.zeros(ndim)
+        cov = np.eye(ndim)
+
+        def func(x):
+            return stats.multivariate_normal.pdf(x.T, mean, cov)
+
+        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, a, b, 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
+        assert_allclose(res.integral, ref, 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: np.log(func(*args)), a, b,
+                          n_points=n_points, n_estimates=n_estimates,
+                          log=True, qrng=qrng)
+        assert_allclose(np.exp(logres.integral), res.integral, rtol=1e-14)
+        assert np.imag(logres.integral) == (np.pi if np.prod(signs) < 0 else 0)
+        assert_allclose(np.exp(logres.standard_error),
+                        res.standard_error, rtol=1e-14, atol=1e-16)
+
+    @pytest.mark.parametrize("n_points", [2**8, 2**12])
+    @pytest.mark.parametrize("n_estimates", [8, 16])
+    def test_basic(self, n_points, n_estimates):
+        self.basic_test(n_points, n_estimates)
+
+    @pytest.mark.parametrize("signs", [[1, 1], [-1, -1], [-1, 1], [1, -1]])
+    def test_sign(self, signs):
+        self.basic_test(signs=signs)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize("log", [False, True])
+    def test_zero(self, log):
+        message = "A lower limit was equal to an upper limit, so"
+        with pytest.warns(UserWarning, match=message):
+            res = qmc_quad(lambda x: 1, [0, 0], [0, 1], log=log)
+        assert res.integral == (-np.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
+
+
+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):
+        # 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 = rng.random()
+        x = (np.sort(rng.random(n)) if order == 2
+             else np.arange(n)*dx + rng.random())
+        i = np.arange(order + 1)[:, np.newaxis]
+        c = rng.random(order + 1)[:, np.newaxis]
+        y = np.sum(c*x**i, axis=0)
+        Y = np.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:
+            assert_allclose(res, ref, rtol=2e-15)
+        else:
+            i0 = 0 if use_initial else 1
+            # all terms are "close"
+            assert_allclose(res, ref, rtol=0.0025)
+            # only even-interval terms are "exact"
+            assert_allclose(res[i0::2], ref[i0::2], rtol=2e-15)
+
+    @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):
+        # 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 = rng.random(size=shape)
+        x, dx = None, None
+        if dx:
+            dx = rng.random(size=shape_len_1) if x_ndim > 1 else rng.random()
+        else:
+            x = (np.sort(rng.random(size=shape), axis=axis) if x_ndim > 1
+                 else np.sort(rng.random(size=shape[axis])))
+        initial = None if i_ndim is None else rng.random(size=i_shape)
+
+        # compare results
+        res = cumulative_simpson(y, x=x, dx=dx, initial=initial, axis=axis)
+        ref = cumulative_simpson_nd_reference(y, x=x, dx=dx, initial=initial, axis=axis)
+        np.testing.assert_allclose(res, 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):
+        kwargs0 = dict(y=self.y0, x=self.x0, dx=None, initial=None, axis=-1)
+        with pytest.raises(ValueError, match=message):
+            cumulative_simpson(**dict(kwargs0, **kwarg_update))
+
+    def test_special_cases(self):
+        # Test special cases not checked elsewhere
+        rng = np.random.default_rng(82456839535679456794)
+        y = rng.random(size=10)
+        res = cumulative_simpson(y, dx=0)
+        assert_equal(res, 0)
+
+        # 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.thread_unsafe
+    @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
+    ):
+        """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(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])
+        )
+        np.testing.assert_allclose(
+            res[..., 1:], ref[..., 1:] + theoretical_difference[..., 1:], atol=1e-16
+        )
+
+    @pytest.mark.thread_unsafe
+    @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
+    ):
+        """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(y, x=x)
+        ref = simpson_reference(y, x)
+        theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps(
+            y, x
+        )
+        np.testing.assert_allclose(
+            res[..., 1:], ref[..., 1:] + theoretical_difference[..., 1:]
+        )
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_tanhsinh.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_tanhsinh.py
new file mode 100644
index 0000000000000000000000000000000000000000..15782ba13efcb16cf8982adf94b8b2f74be63a18
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_tanhsinh.py
@@ -0,0 +1,1163 @@
+# mypy: disable-error-code="attr-defined"
+import os
+import pytest
+import math
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.conftest import array_api_compatible
+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
+from scipy import special, stats
+from scipy.integrate import quad_vec, nsum, tanhsinh as _tanhsinh
+from scipy.integrate._tanhsinh import _pair_cache
+from scipy.stats._discrete_distns import _gen_harmonic_gt1
+
+
+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
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends(
+    'array_api_strict', reason='Currently uses fancy indexing assignment.'
+)
+@pytest.mark.skip_xp_backends(
+    'jax.numpy', reason='JAX arrays do not support item assignment.'
+)
+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
+        xp_test = array_namespace(*limits)  # we need xp.isdtype
+        assert (xp_test.isdtype(logres.integral.dtype, "real floating") if ref > 0
+                else xp_test.isdtype(logres.integral.dtype, "complex floating"))
+
+        xp_assert_close(xp.exp(logres.error), res.error, atol=1e-16, 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 {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)
+
+        xp_test = array_namespace(a)  # need xp.stack, isdtype
+        attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel']
+        for attr in attrs:
+            ref_attr = xp_test.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_test.isdtype(res.success.dtype, 'bool')
+        assert xp_test.isdtype(res.status.dtype, 'integral')
+        assert xp_test.isdtype(res.nfev.dtype, 'integral')
+        assert xp_test.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
+        xp_test = array_namespace(xp.asarray(1.))  # need xp.atan
+
+        def f(x):
+            f.calls += 1
+            f.feval += xp_size(xp.asarray(x))
+            return x**2 * xp_test.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
+
+        # need `xp.concat`, `xp.atan`, and `xp.sort`
+        xp_test = array_namespace(xp.asarray(1.))
+
+        def f(x):
+            f.calls += 1
+            f.feval += xp_size(xp.asarray(x))
+            f.x = xp_test.concat((f.x, xp_ravel(x)))
+            return x**2 * xp_test.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_test.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_test.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)
+        xp_test = array_namespace(a, b)  # need `xp.isdtype`
+
+        def f(x):
+            assert xp_test.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=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.
+        a = complex(12, -10)
+        b = complex(12, 39)
+        def f(t):
+            return xp.sin(a * (1 - t) + b * t)
+        res = _tanhsinh(f, xp.asarray(0.), xp.asarray(1.), atol=0, rtol=0, maxlevel=10)
+        assert xp.isfinite(res.error)
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends('array_api_strict', reason='No fancy indexing.')
+@pytest.mark.skip_xp_backends('jax.numpy', reason='No mutation.')
+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_gt1(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 xp.all((res.status == -1) & xp.isnan(res.sum)
+                          & xp.isnan(res.error) & ~res.success & res.nfev == 1)
+            res = nsum(f, xp.asarray(10.), xp.asarray([np.nan, 1]))
+            assert xp.all((res.status == -1) & xp.isnan(res.sum)
+                          & xp.isnan(res.error) & ~res.success & res.nfev == 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_test = array_namespace(a)  # CuPy doesn't have `bool`
+        xp_assert_equal(res.success, xp.ones(ref.shape, dtype=xp_test.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
+        xp_test = array_namespace(a)  # torch needs broadcast_arrays
+        a, b, step = xp_test.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
+
+        xp_test = array_namespace(xp.asarray(1.))
+        assert xp_test.isdtype(res.success.dtype, 'bool')
+        assert xp_test.isdtype(res.status.dtype, 'integral')
+        assert xp_test.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.isnan(res.sum)
+        assert xp.isnan(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_gt1(np.asarray([10, xp.inf]), 2)
+        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)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/vode.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/integrate/vode.py
new file mode 100644
index 0000000000000000000000000000000000000000..f92927901084ce33cdeb006057d85dd501b13aae
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c4f97134d20b8d3acb1bea54c8384c510314aaa
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py
@@ -0,0 +1,216 @@
+"""
+========================================
+Interpolation (:mod:`scipy.interpolate`)
+========================================
+
+.. currentmodule:: scipy.interpolate
+
+Sub-package for objects used in interpolation.
+
+As listed below, this sub-package contains spline functions and classes,
+1-D and multidimensional (univariate and multivariate)
+interpolation classes, Lagrange and Taylor polynomial interpolators, and
+wrappers for `FITPACK `__
+and DFITPACK functions.
+
+Univariate interpolation
+========================
+
+.. autosummary::
+   :toctree: generated/
+
+   interp1d
+   BarycentricInterpolator
+   KroghInterpolator
+   barycentric_interpolate
+   krogh_interpolate
+   pchip_interpolate
+   CubicHermiteSpline
+   PchipInterpolator
+   Akima1DInterpolator
+   CubicSpline
+   PPoly
+   BPoly
+   FloaterHormannInterpolator
+
+
+Multivariate interpolation
+==========================
+
+Unstructured data:
+
+.. autosummary::
+   :toctree: generated/
+
+   griddata
+   LinearNDInterpolator
+   NearestNDInterpolator
+   CloughTocher2DInterpolator
+   RBFInterpolator
+   Rbf
+   interp2d
+
+For data on a grid:
+
+.. autosummary::
+   :toctree: generated/
+
+   interpn
+   RegularGridInterpolator
+   RectBivariateSpline
+
+.. seealso::
+
+    `scipy.ndimage.map_coordinates`
+
+Tensor product polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   NdPPoly
+   NdBSpline
+
+1-D Splines
+===========
+
+.. autosummary::
+   :toctree: generated/
+
+   BSpline
+   make_interp_spline
+   make_lsq_spline
+   make_smoothing_spline
+   generate_knots
+   make_splrep
+   make_splprep
+
+Functional interface to FITPACK routines:
+
+.. autosummary::
+   :toctree: generated/
+
+   splrep
+   splprep
+   splev
+   splint
+   sproot
+   spalde
+   splder
+   splantider
+   insert
+
+Object-oriented FITPACK interface:
+
+.. autosummary::
+   :toctree: generated/
+
+   UnivariateSpline
+   InterpolatedUnivariateSpline
+   LSQUnivariateSpline
+
+
+
+2-D Splines
+===========
+
+For data on a grid:
+
+.. autosummary::
+   :toctree: generated/
+
+   RectBivariateSpline
+   RectSphereBivariateSpline
+
+For unstructured data:
+
+.. autosummary::
+   :toctree: generated/
+
+   BivariateSpline
+   SmoothBivariateSpline
+   SmoothSphereBivariateSpline
+   LSQBivariateSpline
+   LSQSphereBivariateSpline
+
+Low-level interface to FITPACK functions:
+
+.. autosummary::
+   :toctree: generated/
+
+   bisplrep
+   bisplev
+
+Rational Approximation
+======================
+
+.. autosummary::
+   :toctree: generated/
+
+   pade
+   AAA
+
+Additional tools
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   lagrange
+   approximate_taylor_polynomial
+
+.. seealso::
+
+   `scipy.ndimage.map_coordinates`,
+   `scipy.ndimage.spline_filter`,
+   `scipy.signal.resample`,
+   `scipy.signal.bspline`,
+   `scipy.signal.gauss_spline`,
+   `scipy.signal.qspline1d`,
+   `scipy.signal.cspline1d`,
+   `scipy.signal.qspline1d_eval`,
+   `scipy.signal.cspline1d_eval`,
+   `scipy.signal.qspline2d`,
+   `scipy.signal.cspline2d`.
+
+``pchip`` is an alias of `PchipInterpolator` for backward compatibility
+(should not be used in new code).
+"""
+from ._interpolate import *
+from ._fitpack_py import *
+
+# New interface to fitpack library:
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1904c6ce62840fa58505af4dd5b9c08fdae9f541
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f850389549ff3509641a6f40ee967e5bee3d737b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bary_rational.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bsplines.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bsplines.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a20a65a5630b87baf613a769ffa2dbbb61f02636
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_bsplines.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f336aef2f08dd669e734de335a7d7090775a855
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_cubic.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec82740ec61b516bab772044f6f3668ba441e953
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..435d125da0563df2fb8f8424a920aed06b8bdf84
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..736a037a445312f7551eb6657a9dec32f0474ad8
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a09a49f53ad43e59eb900c3c0eeac5c1d2c5dd66
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_repro.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91f491d293c0d1b73de09760cbf334399f5a0de5
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..897739f4091e882ca1ee5e7e637c915b843461a9
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d342e1de9643573bec68aedba6ce3e40c9dc1ec5
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02d291deff614fb591e7138790631f6b50be4250
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19e5cd6a4b6fd4e989516f446ac34137ef171370
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b16e257050761d28ab5238fea191eff9576ee16e
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e9f48999d1c6c94994e476c310a8b025c6b8335
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4165700e81b1537725642f20860be20f65745644
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rgi.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07b19151790166261265b9a05ea6b460a7d26869
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37cca28658d9fdc14d5b7a289b640cc9628b8c9b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4393e594c06d6231f73d485f492149287c0d5de2
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpnd.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c159ddeafa9d690372f19e49248adb7e5fdbd65
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4071daf6dbb4651ca05996ff32a5571bf05d20e3
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c4b7e15c374d4653104087b4416cba34a7f5b48
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9609d4d16da292b25878bff232efc6c3c3195c8b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py
new file mode 100644
index 0000000000000000000000000000000000000000..be13c06e27cb8df7ec4c55993dd3937e867429e5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py
@@ -0,0 +1,715 @@
+# 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
+
+import numpy as np
+import scipy
+
+
+__all__ = ["AAA", "FloaterHormannInterpolator"]
+
+
+class _BarycentricRational:
+    """Base class for Barycentric representation of a rational function."""
+    def __init__(self, x, y, **kwargs):
+        # input validation
+        z = np.asarray(x)
+        f = np.asarray(y)
+
+        self._input_validation(z, f, **kwargs)
+
+        # 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[0]:
+            raise ValueError("`x` be the same size as the first dimension of `y`.")
+
+        if not np.all(np.isfinite(x)):
+            raise ValueError("`x` must be finite.")
+
+    def _compute_weights(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()
+
+        return np.reshape(r, z.shape + self._shape)
+
+    def poles(self):
+        """Compute the poles of the rational approximation.
+
+        Returns
+        -------
+        poles : array
+            Poles of the AAA 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._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 zeros of the rational approximation.
+
+        Returns
+        -------
+        zeros : array
+            Zeros of the AAA approximation, repeated according to their multiplicity
+            but not in any specific order.
+        """
+        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
+    >>> 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)
+
+    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
+
+    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)
+
+        # 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
+                _, s, V = scipy.linalg.svd(
+                    A[mask, : m + 1], 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)
+            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 interpolation.
+
+    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
+    ----------
+    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 : array_like, shape (n, ...)
+        Array containing values of the dependent variable. Infinite and NaN values
+        of `values` and corresponding values of `x` will be discarded.
+    d : int, optional
+        Blends ``n - d`` degree `d` polynomials together. For ``d = n - 1`` it is
+        equivalent to polynomial interpolation. Must satisfy ``0 <= d < n``,
+        defaults to 3.
+
+    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 polynomials 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 following barycentric representation of the above equation
+    is used instead 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(z):
+    ...     return 1/(1 + z**2)
+    >>> z = np.linspace(-5, 5, num=15)
+    >>> r = FloaterHormannInterpolator(z, f(z))
+    >>> p = BarycentricInterpolator(z, f(z))
+    >>> zz = np.linspace(-5, 5, num=1000)
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(zz, r(zz), label="Floater=Hormann")
+    >>> ax.plot(zz, p(zz), label="Polynomial")
+    >>> ax.legend()
+    >>> plt.show()
+    """
+    def __init__(self, points, values, *, d=3):
+        super().__init__(points, values, d=d)
+
+    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)
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d68e8d532100f4926328d68cb68d1048f4290e8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py
@@ -0,0 +1,2416 @@
+import operator
+from math import prod
+
+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
+
+
+__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:
+    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] Tom Lyche and Knut Morken, Spline methods,
+        http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/
+    .. [2] Carl de Boor, A practical guide to splines, Springer, 2001.
+
+    """
+
+    def __init__(self, t, c, k, extrapolate=True, axis=0):
+        super().__init__()
+
+        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("Need at least %d knots for degree %d" %
+                             (2*k + 2, 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.t, self.c, self.k = t, c, k
+        self.extrapolate = extrapolate
+        self.axis = axis
+        return self
+
+    @property
+    def tck(self):
+        """Equivalent to ``(self.t, self.c, self.k)`` (read-only).
+        """
+        return self.t, self.c, self.k
+
+    @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()
+
+        """
+        k = len(t) - 2
+        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):
+        """
+        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.
+        """
+        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):
+        """
+        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`.
+
+        """
+        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
+
+        out = np.empty((len(x), prod(self.c.shape[1:])), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        # if self.c is complex, so is `out`; cython code in _bspl.pyx expectes
+        # floats though, 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)
+
+        cc = self.c.view(float)
+        if self.c.ndim == 1 and self.c.dtype.kind == 'c':
+            cc = cc.reshape(self.c.shape[0], 2)
+
+        _dierckx.evaluate_spline(self.t, cc.reshape(cc.shape[0], -1),
+                              self.k, x, nu, extrapolate, out.view(float))
+
+        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 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
+
+        """
+        c = self.c.copy()
+        # pad the c array if needed
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        tck = _fitpack_impl.splder((self.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.
+
+        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.
+
+        See Also
+        --------
+        splder, splantider
+
+        """
+        c = self.c.copy()
+        # pad the c array if needed
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        tck = _fitpack_impl.splantider((self.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()
+
+        """
+        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.tck)
+                return np.asarray(integral * sign)
+
+        out = np.empty((2, prod(self.c.shape[1:])), dtype=self.c.dtype)
+
+        # 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)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                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)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+            else:
+                x = np.asarray([a, te], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+
+                x = np.asarray([ts, ts + b - te], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+        else:
+            # Evaluate the difference of antiderivatives.
+            x = np.asarray([a, b], dtype=np.float64)
+            _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                  ka, x, 0, extrapolate, out)
+            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'):
+        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 : string, 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] Tom Lyche and Knut Morken, Spline Methods, 2005, Section 3.1.2
+
+        """
+        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):
+        """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.
+
+        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.])
+
+        """
+        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)
+
+
+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 : integer
+        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 : integer
+        Number of lower diagonals of ab.
+    ku : integer
+        Number of upper diagonals of ab.
+    deriv_ords : 1D ndarray
+        Orders of derivatives known at xval
+    offset : integer, 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):
+    '''
+    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 : 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:]))
+        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:]))
+    return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
+
+
+def make_interp_spline(x, y, k=3, t=None, bc_type=None, axis=0,
+                       check_finite=True):
+    """Compute the (coefficients of) interpolating B-spline.
+
+    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 : 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
+
+    y = np.asarray(y)
+
+    axis = normalize_axis_index(axis, y.ndim)
+
+    x = _as_float_array(x, check_finite)
+    y = _as_float_array(y, check_finite)
+
+    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))
+        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))
+        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('Got %d knots, need at least %d.' %
+                         (t.size, 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)
+
+    # 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('illegal value in %d-th argument of internal gbsv' % -info)
+
+    c = np.ascontiguousarray(c.reshape((nt,) + y.shape[1:]))
+    return BSpline.construct_fast(t, c, k, axis=axis)
+
+
+def make_lsq_spline(x, y, t, k=3, w=None, axis=0, check_finite=True, *, method="qr"):
+    r"""Compute the (coefficients of) an LSQ (Least SQuared) based
+    fitting B-spline.
+
+    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 : 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.)
+
+    """
+    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 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)
+        c = cho_solve_banded((cho_decomp, lower), rhs, overwrite_b=True,
+                             check_finite=check_finite)
+    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)
+    return BSpline.construct_fast(t, c, k, axis=axis)
+
+
+######################
+# LSQ spline helpers #
+######################
+
+def _lsq_solve_qr(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.
+
+    """
+    assert y.ndim == 2
+
+    y_w = y * w[:, None]
+    A, offset, nc = _dierckx.data_matrix(x, t, k, w)
+    _dierckx.qr_reduce(A, offset, nc, y_w)         # modifies arguments in-place
+    c = _dierckx.fpback(A, nc, y_w)
+
+    return A, y_w, c
+
+
+#############################
+#  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):
+        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)
+
+    def fun(lam):
+        return _gcv(lam, X, XtWX, wE, XtE)
+
+    gcv_est = minimize_scalar(fun, bounds=(0, n), method='Bounded')
+    if gcv_est.success:
+        return gcv_est.x
+    raise ValueError(f"Unable to find minimum of the GCV "
+                     f"function: {gcv_est.message}")
+
+
+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
+
+
+def make_smoothing_spline(x, y, w=None, lam=None):
+    r"""
+    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.
+
+    Returns
+    -------
+    func : a BSpline object.
+        A callable 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(grid, spl(grid), label='Spline')
+    >>> plt.plot(grid, func(grid), label='Original function')
+    >>> plt.scatter(x, y, marker='.')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+
+    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 y.ndim != 1 or x.shape[0] != y.shape[0]:
+        raise ValueError('``x`` and ``y`` should be one dimensional and the'
+                         ' same size')
+
+    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')
+
+    # 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
+    c = solve_banded((2, 2), X + lam * wE, y)
+    # move back to B-spline basis using equations (2.2.10) [4]
+    c_ = np.r_[c[0] * (t[5] + t[4] - 2 * t[3]) + c[1],
+               c[0] * (t[5] - t[3]) + c[1],
+               c[1: -1],
+               c[-1] * (t[-4] - t[-6]) + c[-2],
+               c[-1] * (2 * t[-4] - t[-5] - t[-6]) + c[-2]]
+
+    return BSpline.construct_fast(t, c_, 3)
+
+
+########################
+#  FITPACK look-alikes #
+########################
+
+def fpcheck(x, t, k):
+    """ Check consistency of the data vector `x` and the knot vector `t`.
+
+    Return None if inputs are consistent, raises a ValueError otherwise.
+    """
+    # This routine is a clone of the `fpchec` Fortran routine,
+    # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f
+    # which carries the following comment:
+    #
+    # subroutine fpchec verifies the number and the position of the knots
+    #  t(j),j=1,2,...,n of a spline of degree k, in relation to the number
+    #  and the position of the data points x(i),i=1,2,...,m. if all of the
+    #  following conditions are fulfilled, the error parameter ier is set
+    #  to zero. if one of the conditions is violated ier is set to ten.
+    #      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
+    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
+    # 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, 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
+    mesg = f"Schoenberg-Whitney condition is violated with {t = } and {x =}."
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py
new file mode 100644
index 0000000000000000000000000000000000000000..3139e145916fa0637552331974ce531da625836f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py
@@ -0,0 +1,958 @@
+"""Interpolation algorithms using piecewise cubic polynomials."""
+
+from typing import Literal
+
+import numpy as np
+
+from scipy.linalg import solve, solve_banded
+
+from . import PPoly
+from ._polyint import _isscalar
+
+__all__ = ["CubicHermiteSpline", "PchipInterpolator", "pchip_interpolate",
+           "Akima1DInterpolator", "CubicSpline"]
+
+
+def prepare_input(x, y, axis, dydx=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(np.asarray, (x, y))
+    if np.issubdtype(x.dtype, np.complexfloating):
+        raise ValueError("`x` must contain real values.")
+    x = x.astype(float)
+
+    if np.issubdtype(y.dtype, np.complexfloating):
+        dtype = complex
+    else:
+        dtype = float
+
+    if dydx is not None:
+        dydx = np.asarray(dydx)
+        if y.shape != dydx.shape:
+            raise ValueError("The shapes of `y` and `dydx` must be identical.")
+        if np.issubdtype(dydx.dtype, np.complexfloating):
+            dtype = complex
+        dydx = dydx.astype(dtype, copy=False)
+
+    y = y.astype(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 np.all(np.isfinite(x)):
+        raise ValueError("`x` must contain only finite values.")
+    if not np.all(np.isfinite(y)):
+        raise ValueError("`y` must contain only finite values.")
+
+    if dydx is not None and not np.all(np.isfinite(dydx)):
+        raise ValueError("`dydx` must contain only finite values.")
+
+    dx = np.diff(x)
+    if np.any(dx <= 0):
+        raise ValueError("`x` must be strictly increasing sequence.")
+
+    y = np.moveaxis(y, axis, 0)
+    if dydx is not None:
+        dydx = np.moveaxis(dydx, axis, 0)
+
+    return x, dx, y, axis, dydx
+
+
+class CubicHermiteSpline(PPoly):
+    """Piecewise-cubic interpolator matching values and first derivatives.
+
+    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.
+
+    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
+    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):
+        if extrapolate is None:
+            extrapolate = True
+
+        x, dx, y, axis, dydx = prepare_input(x, y, axis, dydx)
+
+        dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1))
+        slope = np.diff(y, axis=0) / dxr
+        t = (dydx[:-1] + dydx[1:] - 2 * slope) / dxr
+
+        c = np.empty((4, len(x) - 1) + y.shape[1:], dtype=t.dtype)
+        c[0] = t / dxr
+        c[1] = (slope - dydx[:-1]) / dxr - t
+        c[2] = dydx[:-1]
+        c[3] = y[:-1]
+
+        super().__init__(c, x, extrapolate=extrapolate)
+        self.axis = axis
+
+
+class PchipInterpolator(CubicHermiteSpline):
+    r"""PCHIP 1-D monotonic cubic interpolation.
+
+    ``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, ...)
+        A 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, optional
+        Whether to extrapolate to out-of-bounds points based on first
+        and last intervals, or to return NaNs.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    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] see, e.g., C. Moler, Numerical Computing with Matlab, 2004.
+           :doi:`10.1137/1.9780898717952`
+
+    """
+
+    def __init__(self, x, y, axis=0, extrapolate=None):
+        x, _, y, axis, _ = prepare_input(x, y, axis)
+        if np.iscomplexobj(y):
+            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)
+        xp = x.reshape((x.shape[0],) + (1,)*(y.ndim-1))
+        dk = self._find_derivatives(xp, y)
+        super().__init__(x, y, dk, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    @staticmethod
+    def _edge_case(h0, h1, m0, m1):
+        # one-sided three-point estimate for the derivative
+        d = ((2*h0 + h1)*m0 - h0*m1) / (h0 + h1)
+
+        # try to preserve shape
+        mask = np.sign(d) != np.sign(m0)
+        mask2 = (np.sign(m0) != np.sign(m1)) & (np.abs(d) > 3.*np.abs(m0))
+        mmm = (~mask) & mask2
+
+        d[mask] = 0.
+        d[mmm] = 3.*m0[mmm]
+
+        return d
+
+    @staticmethod
+    def _find_derivatives(x, y):
+        # 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 = np.zeros_like(y)
+            dk[0] = mk
+            dk[1] = mk
+            return dk.reshape(y_shape)
+
+        smk = np.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])
+        dk[-1] = PchipInterpolator._edge_case(hk[-1], hk[-2], mk[-1], mk[-2])
+
+        return dk.reshape(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.
+
+        .. deprecated:: 1.13.0
+            Complex data is deprecated and will raise an error in
+            SciPy 1.15.0. If you are trying to use the real components of
+            the passed array, use ``np.real`` on `yi`.
+
+    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]
+
+
+class Akima1DInterpolator(CubicHermiteSpline):
+    r"""
+    Akima interpolator
+
+    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, None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points 
+        based on first and last intervals, or to return NaNs. If None, 
+        ``extrapolate`` is set to False.
+        
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    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
+        x, dx, y, axis, _ = prepare_input(x, y, axis)
+
+        if np.iscomplexobj(y):
+            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
+
+        # determine slopes between breakpoints
+        m = np.empty((x.size + 3, ) + y.shape[1:])
+        dx = dx[(slice(None), ) + (None, ) * (y.ndim - 1)]
+        m[2:-2] = np.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 = np.abs(np.diff(m, axis=0))
+        if method == "makima":
+            pm = np.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]
+        f12 = f1 + f2
+        # These are the mask of where the slope at breakpoint is defined:
+        ind = np.nonzero(f12 > 1e-9 * np.max(f12, initial=-np.inf))
+        x_ind, y_ind = ind[0], ind[1:]
+        # Set the slope at breakpoint
+        t[ind] = (f1[ind] * m[(x_ind + 1,) + y_ind] +
+                  f2[ind] * m[(x_ind + 2,) + y_ind]) / f12[ind]
+
+        super().__init__(x, y, t, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    def extend(self, c, x, right=True):
+        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.")
+
+
+class CubicSpline(CubicHermiteSpline):
+    """Cubic spline data interpolator.
+
+    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 : string 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.
+
+    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
+    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):
+        x, dx, y, axis, _ = prepare_input(x, y, axis)
+        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]
+
+                s = solve(A, b, overwrite_a=True, overwrite_b=True,
+                          check_finite=False)
+            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
+                    s1 = solve_banded((1, 1), Ac, b1, overwrite_ab=False,
+                                      overwrite_b=False, check_finite=False)
+
+                    s2 = solve_banded((1, 1), Ac, b2, overwrite_ab=False,
+                                      overwrite_b=False, check_finite=False)
+
+                    # 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])
+
+                    s = solve_banded((1, 1), A, b, overwrite_ab=True,
+                                     overwrite_b=True, check_finite=False)
+
+        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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..5f1de8a506d90631543927894cd35196744a879a
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..daa7773a0f3be6590ea9c0ab328d610efa745859
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py
@@ -0,0 +1,2394 @@
+"""
+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 threading import Lock
+
+from numpy import zeros, concatenate, ravel, diff, array
+import numpy as np
+
+from . import _fitpack_impl
+from . import _dfitpack as dfitpack
+
+
+dfitpack_int = dfitpack.types.intvar.dtype
+FITPACK_LOCK = Lock()
+
+
+# ############### 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)
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
+                                    xe=bbox[1], s=s)
+        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[10]
+        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])
+
+        args = data[:8] + (t, c, n, fpint, nrdata, data[13])
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf1(*args)
+        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
+        args = data[:6] + (s,) + data[7:]
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf1(*args)
+        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
+        with FITPACK_LOCK:
+            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
+
+        """
+        with FITPACK_LOCK:
+            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])
+
+        """
+        with FITPACK_LOCK:
+            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)
+            with FITPACK_LOCK:
+                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)`.
+
+        """
+        with FITPACK_LOCK:
+            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.
+
+        Notes
+        -----
+
+        .. versionadded:: 0.13.0
+
+        See Also
+        --------
+        splantider, derivative
+
+        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
+
+        """
+        with FITPACK_LOCK:
+            tck = _fitpack_impl.splantider(self._eval_args, n)
+        return UnivariateSpline._from_tck(tck, self.ext)
+
+
+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
+        with FITPACK_LOCK:
+            self._data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
+                                          xe=bbox[1], s=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
+"""
+
+
+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')
+        with FITPACK_LOCK:
+            if not dfitpack.fpchec(x, t, k) == 0:
+                raise ValueError(_fpchec_error_string)
+            data = dfitpack.fpcurfm1(x, y, k, t, w=w, xb=xb, xe=xe)
+        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: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0)
+        """
+        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.
+        """
+        return self.tck[:2]
+
+    def get_coeffs(self):
+        """ Return 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)
+
+        tx, ty, c = self.tck[:3]
+        kx, ky = self.degrees
+        if grid:
+            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:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by parder: {ier}")
+            else:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.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:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.pardeu(tx, ty, c, kx, ky, dx, dy, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by pardeu: {ier}")
+            else:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.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)
+        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]
+            with FITPACK_LOCK:
+                newc, ier = dfitpack.pardtc(tx, ty, c, kx, ky, dx, dy)
+            if ier != 0:
+                # This should not happen under normal conditions.
+                raise ValueError("Unexpected error code returned by"
+                                 " pardtc: %d" % 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.""",
+                    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
+        with FITPACK_LOCK:
+            return dfitpack.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}")
+
+
+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, prefer `LinearNDInterpolator`.
+    See ``https://gist.github.com/ev-br/8544371b40f414b7eaf3fe6217209bff``
+    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
+        with FITPACK_LOCK:
+            nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(
+                x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps, lwrk2=1)
+            if ier > 10:          # lwrk2 was to small, re-run
+                nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(
+                    x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps,
+                    lwrk2=ier)
+        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
+
+
+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,)')
+
+        nx = 2*kx+2+len(tx)
+        ny = 2*ky+2+len(ty)
+        # The Fortran subroutine "surfit" (called as dfitpack.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
+
+        xb, xe, yb, ye = bbox
+        with FITPACK_LOCK:
+            tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, nx, tx1, ny, ty1,
+                                                    w, xb, xe, yb, ye,
+                                                    kx, ky, eps, lwrk2=1)
+            if ier > 10:
+                tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z,
+                                                        nx, tx1, ny, ty1, w,
+                                                        xb, xe, yb, ye,
+                                                        kx, ky, eps, lwrk2=ier)
+        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
+
+
+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.
+
+    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):
+        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
+        with FITPACK_LOCK:
+            nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth(x, y, z, xb, xe, yb,
+                                                            ye, kx, ky, s)
+
+        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."""
+
+
+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
+
+        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)
+
+
+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)')
+
+        with FITPACK_LOCK:
+            nt_, tt_, np_, tp_, c, fp, ier = dfitpack.spherfit_smth(theta, phi,
+                                                                    r, w=w, s=s,
+                                                                    eps=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)
+
+
+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
+        with FITPACK_LOCK:
+            tt_, tp_, c, fp, ier = dfitpack.spherfit_lsq(theta, phi, r, tt_, tp_,
+                                                        w=w, eps=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."""
+
+
+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=dfitpack_int)
+        ider = np.array([-1, 0, -1, 0], dtype=dfitpack_int)
+        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)
+        with FITPACK_LOCK:
+            nu, tu, nv, tv, c, fp, ier = dfitpack.regrid_smth_spher(iopt, ider,
+                                                                    u.copy(),
+                                                                    v.copy(),
+                                                                    r.copy(),
+                                                                    r0, r1, s)
+
+        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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..a00ca101b591dd69b6b590278083f0bdafbd3a01
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py
@@ -0,0 +1,805 @@
+"""
+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, transpose,
+                   empty, iinfo, asarray)
+
+# Try to replace _fitpack interface with
+#  f2py-generated version
+from . import _dfitpack as dfitpack
+
+
+dfitpack_int = dfitpack.types.intvar.dtype
+
+
+def _int_overflow(x, exception, msg=None):
+    """Cast the value to an 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.type(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([], dfitpack_int), '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([], dfitpack_int), '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('Setting x[%d][%d]=x[%d][0]' %
+                                                 (i, m, i)),
+                                  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('1 <= k= %d <=5 must hold' % k)
+    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(transpose(x)), 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.shape = idim, n - k - 1
+    tcku = [t, list(c), k], u
+    if ier <= 0 and not quiet:
+        warnings.warn(RuntimeWarning(_iermess[ier][0] +
+                                     "\tk=%d n=%d m=%d fp=%f s=%f" %
+                                     (k, len(t), m, fp, 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([], dfitpack_int)}
+
+
+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('len(w)=%d is not equal to m=%d' % (len(w), 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('Given degree of the spline (k=%d) is not supported. '
+                        '(1<=k<=5)' % k)
+    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,), dfitpack_int)
+    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, c, fp, ier = dfitpack.curfit(task, x, y, w, t, wrk, iwrk,
+                                        xb, xe, k, s)
+    else:
+        n, c, fp, ier = dfitpack.percur(task, x, y, w, t, wrk, iwrk, k, s)
+    tck = (t[:n], c[:n], k)
+    if ier <= 0 and not quiet:
+        _mess = (_iermess[ier][0] + "\tk=%d n=%d m=%d fp=%f s=%f" %
+                 (k, len(t), m, fp, 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("0<=der=%d<=k=%d must hold" % (der, k))
+        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 = dfitpack.splev(t, c, k, x, ext)
+        else:
+            y, ier = dfitpack.splder(t, c, k, x, der, 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, wrk = dfitpack.splint(t, c, k, a, b)
+        if full_output:
+            return aint, wrk
+        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 = dfitpack.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 = dfitpack.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([], dfitpack_int)}
+
+
+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('len(w)=%d is not equal to m=%d' % (len(w), 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('Given degree of the spline (kx,ky=%d,%d) is not '
+                        'supported. (1<=k<=5)' % (kx, ky))
+    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"
+    lwrk1 = _int_overflow(u*v*(2 + b1 + b2) +
+                          2*(u + v + km*(m + ne) + ne - kx - ky) + b2 + 1,
+                          OverflowError,
+                          msg=msg)
+    lwrk2 = _int_overflow(u*v*(b2 + 1) + b2, OverflowError, msg=msg)
+    tx, ty, c, o = _fitpack._surfit(x, y, z, w, xb, xe, yb, ye, kx, ky,
+                                    task, s, eps, tx, ty, nxest, nyest,
+                                    wrk, lwrk1, lwrk2)
+    _curfit_cache['tx'] = tx
+    _curfit_cache['ty'] = ty
+    _curfit_cache['wrk'] = o['wrk']
+    ier, fp = o['ier'], o['fp']
+    tck = [tx, ty, c, kx, ky]
+
+    ierm = min(11, max(-3, ier))
+    if ierm <= 0 and not quiet:
+        _mess = (_iermess2[ierm][0] +
+                 "\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" %
+                 (kx, ky, len(tx), len(ty), m, fp, s))
+        warnings.warn(RuntimeWarning(_mess), stacklevel=2)
+    if ierm > 0 and not full_output:
+        if ier in [1, 2, 3, 4, 5]:
+            _mess = ("\n\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" %
+                     (kx, ky, len(tx), len(ty), m, fp, 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
+
+
+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("0 <= dx = %d < kx = %d must hold" % (dx, kx))
+    if not (0 <= dy < ky):
+        raise ValueError("0 <= dy = %d < ky = %d must hold" % (dy, ky))
+    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 = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
+    else:
+        z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y)
+
+    if ier == 10:
+        raise ValueError("Invalid input data")
+    if ier:
+        raise TypeError("An error occurred")
+    z.shape = 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 dfitpack.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):
+    # see the docstring of `_fitpack_py/splder`
+    if n < 0:
+        return splantider(tck, -n)
+
+    t, c, k = tck
+
+    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 = np.r_[c, np.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 "
+                              "and is not differentiable %d times") % n) from e
+
+    return t, c, k
+
+
+def splantider(tck, n=1):
+    # see the docstring of `_fitpack_py/splantider`
+    if n < 0:
+        return splder(tck, -n)
+
+    t, c, k = tck
+
+    # 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 = np.cumsum(c[:-k-1] * dt, axis=0) / (k + 1)
+        c = np.r_[np.zeros((1,) + c.shape[1:]),
+                  c,
+                  [c[-1]] * (k+2)]
+        # New knots
+        t = np.r_[t[0], t, t[-1]]
+        k += 1
+
+    return t, c, k
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f7a2ded7e46885b4e0e0e4ccdb8065c25742e6a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py
@@ -0,0 +1,898 @@
+__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
+
+
+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
+
+
+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
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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)
+
+
+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 (u) : 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)
+
+
+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)
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5697f3ad716500f6557175e88adead6b3b4caac
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py
@@ -0,0 +1,992 @@
+""" 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).
+         https://doi.org/10.1016/0771-050X(75)90034-0
+"""
+import warnings
+import operator
+import numpy as np
+
+from ._bsplines import (
+    _not_a_knot, make_interp_spline, BSpline, fpcheck, _lsq_solve_qr
+)
+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):
+    # FITPACK has (w*(spl(x)-y))**2; make_lsq_spline has w*(spl(x)-y)**2
+    w2 = w**2
+
+    # 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.
+    _, _, c = _lsq_solve_qr(x, y, t, k, w)
+    c = np.ascontiguousarray(c)
+    spl = BSpline(t, c, k)
+    return _compute_residuals(w2, spl(x), y)
+
+
+def _compute_residuals(w2, splx, y):
+    delta = ((splx - y)**2).sum(axis=1)
+    return w2 * delta
+
+
+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):
+    """Common input validations for generate_knots and make_splrep.
+    """
+    x = np.asarray(x, dtype=float)
+    y = np.asarray(y, dtype=float)
+
+    if w is None:
+        w = np.ones_like(x, dtype=float)
+    else:
+        w = np.asarray(w, dtype=float)
+        if w.ndim != 1:
+            raise ValueError(f"{w.ndim = } not implemented yet.")
+        if (w < 0).any():
+            raise ValueError("Weights must be non-negative")
+
+    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)
+
+    return x, y, w, k, s, xb, xe
+
+
+def generate_knots(x, y, *, w=None, xb=None, xe=None, k=3, s=0, nest=None):
+    """Replicate FITPACK's constructing the knot vector.
+
+    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.
+
+    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
+
+    """
+    if s == 0:
+        if nest is not None or w is not None:
+            raise ValueError("s == 0 is interpolation only")
+        t = _not_a_knot(x, k)
+        yield t
+        return
+
+    x, y, w, k, s, xb, xe = _validate_inputs(
+        x, y, w, k, s, xb, xe, parametric=np.ndim(y) == 2
+    )
+
+    yield from _generate_knots_impl(x, y, w=w, xb=xb, xe=xe, k=k, s=s, nest=nest)
+
+
+def _generate_knots_impl(x, y, *, w=None, xb=None, xe=None, k=3, s=0, nest=None):
+
+    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
+        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), dtype=float)
+    n = t.shape[0]
+    fp = 0.0
+    fpold = 0.0
+
+    # c  main loop for the different sets of knots. m is a safe upper bound
+    # c  for the number of trials.
+    for _ in range(m):
+        yield t
+
+        # construct the LSQ spline with this set of knots
+        fpold = fp
+        residuals = _get_residuals(x, y, t, k, w=w)
+        fp = residuals.sum()
+        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:
+                t = _not_a_knot(x, k)
+                yield t
+                return
+
+            # c  if n=nest we cannot increase the number of knots because of
+            # c  the storage capacity limitation.
+            if n >= nest:
+                yield t
+                return
+
+            # recompute if needed
+            if j < nplus - 1:
+                residuals = _get_residuals(x, y, t, k, w=w)
+
+    # 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,
+        http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/
+
+    """
+    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.)
+        https://doi.org/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 = _dierckx.fpback(AB, nc, QY)
+
+        spl = BSpline(self.t, c, self.k)
+        residuals = _compute_residuals(self.w**2, spl(self.x), self.y)
+        fp = residuals.sum()
+
+        self.spl = spl   # store it
+
+        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)
+
+
+_iermesg = {
+2: """error. a theoretically impossible result was found during
+the iteration process for finding a smoothing spline with
+fp = s. 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.
+""",
+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):
+    """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=None, xb=None, xe=None, k=3, s=0, t=None, nest=None):
+    """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
+        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=w, k=k, s=s, xb=xb, xe=xe, nest=nest)
+        t = list(gen)[-1]
+    else:
+        fpcheck(x, t, k)
+
+    if t.shape[0] == 2 * (k + 1):
+        # nothing to optimize
+        _, _, c = _lsq_solve_qr(x, y, t, k, w)
+        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
+    R, Y, _ = _lsq_solve_qr(x, y, t, k, w)
+    nc = t.shape[0] -k -1
+    p = nc / R[:, 0].sum()
+
+    # ### bespoke solver ####
+    # initial conditions
+    # f(p=inf) : LSQ spline with knots t   (XXX: reuse R, c)
+    residuals = _get_residuals(x, y, t, k, w=w)
+    fp = residuals.sum()
+    fpinf = fp - s
+
+    # f(p=0): LSQ spline without internal knots
+    residuals = _get_residuals(x, y, np.array([xb]*(k+1) + [xe]*(k+1)), k, w)
+    fp0 = residuals.sum()
+    fp0 = fp0 - s
+
+    # solve
+    bracket = (0, fp0), (np.inf, fpinf)
+    f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y)
+    _ = 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
+    return f.spl
+
+
+def make_splrep(x, y, *, w=None, xb=None, xe=None, k=3, s=0, t=None, nest=None):
+    r"""Find the B-spline representation of a 1D function.
+
+    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 conditions::
+
+            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).
+
+    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
+    """
+    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)
+
+    x, y, w, k, s, xb, xe = _validate_inputs(x, y, w, k, s, xb, xe, parametric=False)
+
+    spl = _make_splrep_impl(x, y, w=w, xb=xb, xe=xe, k=k, s=s, t=t, nest=nest)
+
+    # postprocess: squeeze out the last dimension: was added to simplify the internals.
+    spl.c = spl.c[:, 0]
+    return spl
+
+
+def make_splprep(x, *, w=None, u=None, ub=None, ue=None, k=3, s=0, t=None, nest=None):
+    r"""
+    Find a smoothed B-spline representation of a parametric N-D curve.
+
+    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 (m, ndim)
+        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).
+
+    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.
+    """
+    x = np.stack(x, axis=1)
+
+    # construct the default parametrization of the curve
+    if u is None:
+        dp = (x[1:, :] - x[:-1, :])**2
+        u = np.sqrt((dp).sum(axis=1)).cumsum()
+        u = np.r_[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, axis=1), u
+
+    u, x, w, k, s, ub, ue = _validate_inputs(u, x, w, k, s, ub, ue, parametric=True)
+
+    spl = _make_splrep_impl(u, x, w=w, xb=ub, xe=ue, k=k, s=s, t=t, nest=nest)
+
+    # 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)
+
+    return spl1, u
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..7558bd7db25cbd60206f908aabbcb6dc9c567fa4
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py
@@ -0,0 +1,2248 @@
+__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly']
+
+from math import prod
+
+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 . import _fitpack_py
+from ._polyint import _Interpolator1D
+from . import _ppoly
+from ._interpnd import _ndim_coords_from_arrays
+from ._bsplines import make_interp_spline, BSpline
+
+
+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.
+
+    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.
+
+    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, 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()
+
+    """
+
+    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)
+
+    .. 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')
+
+
+class interp1d(_Interpolator1D):
+    """
+    Interpolate a 1-D function.
+
+    .. 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
+        A 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 a 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("x and y arrays must have at "
+                             "least %d entries" % minval)
+
+        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 the slope of regions that each x_new value falls in.
+        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 two expressions rely on the specifics of the
+        # broadcasting semantics.
+        slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
+
+        # 5. Calculate the actual value for each entry in x_new.
+        y_new = slope*(x_new - 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
+
+    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."""
+    __slots__ = ('c', 'x', 'extrapolate', 'axis')
+
+    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):
+        """
+        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
+        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):
+        """
+        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 = 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):
+        """
+        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]``.
+        """
+        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):
+    """
+    Piecewise polynomial in terms of coefficients and breakpoints
+
+    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, 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 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.
+    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.
+    """
+
+    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):
+        """
+        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]``.
+        """
+        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):
+        """
+        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]
+        """
+        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):
+        """
+        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.])
+        """
+        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):
+        """
+        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
+            if extrapolate is None:
+                extrapolate = tck.extrapolate
+        else:
+            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], tck, 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):
+        """
+        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.")
+
+        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):
+    """Piecewise polynomial in terms of coefficients and breakpoints.
+
+    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, 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.
+    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
+
+    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):
+        """
+        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.
+
+        """
+        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):
+        """
+        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.
+        """
+        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, x, extrapolate, axis=self.axis)
+
+    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]
+
+        """
+        # 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])
+        return _PPolyBase.extend(self, c, x)
+    extend.__doc__ = _PPolyBase.extend.__doc__
+
+    @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.")
+
+        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):
+        """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
+
+        """
+        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 = ("Point %g has %d derivatives, point %g"
+                            " has %d derivatives, but order %d requested" % (
+                               xi[i], len(y1), xi[i+1], len(y2), orders[i]))
+                    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):
+        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``.
+
+        """
+        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):
+        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 : integer
+
+        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)
+
+        """
+        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
+
+
+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.
+
+    """
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py
new file mode 100644
index 0000000000000000000000000000000000000000..51ac566ed5ff1271a46ffafcc04c0e180f2ec3f1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py
@@ -0,0 +1,420 @@
+import itertools
+import functools
+import operator
+import numpy as np
+
+from math import prod
+
+from . import _bspl   # type: ignore[attr-defined]
+
+import scipy.sparse.linalg as ssl
+from scipy.sparse import csr_array
+
+from ._bsplines import _not_a_knot
+
+__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
+
+
+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__
+    design_matrix
+
+    See Also
+    --------
+    BSpline : a one-dimensional B-spline object
+    NdPPoly : an N-dimensional piecewise tensor product polynomial
+
+    """
+    def __init__(self, t, c, k, *, extrapolate=None):
+        self._k, self._indices_k1d, (self._t, self._len_t) = _preprocess_inputs(k, t)
+
+        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._t[d, :self._len_t[d]] for d in range(self._t.shape[0]))
+
+    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 : array_like, optional, shape (ndim,)
+            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.intc)
+        else:
+            nu = np.asarray(nu, dtype=np.intc)
+            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.intp)
+
+        num_c_tr = c1.shape[-1]  # # of trailing coefficients
+        out = np.empty(xi.shape[:-1] + (num_c_tr,), dtype=c1.dtype)
+
+        _bspl.evaluate_ndbspline(xi,
+                                 self._t,
+                                 self._len_t,
+                                 self._k,
+                                 nu,
+                                 extrapolate,
+                                 c1r,
+                                 num_c_tr,
+                                 _strides_c1,
+                                 self._indices_k1d,
+                                 out,)
+        out = out.view(self.c.dtype)
+        return out.reshape(xi_shape[:-1] + self.c.shape[ndim:])
+
+    @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.intp)[::-1].copy()
+
+        # heavy lifting happens here
+        data, indices, indptr = _bspl._colloc_nd(xvals,
+                                                _t,
+                                                len_t,
+                                                k,
+                                                _indices_k1d,
+                                                cstrides)
+        return csr_array((data, indices, indptr))
+
+
+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.int32)
+
+    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.intp).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]])
+    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.int32)
+
+    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)
+
+    # 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..78fe9d6995141ad238002e0b48feb94017dc272a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py
@@ -0,0 +1,332 @@
+"""
+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 cKDTree
+
+__all__ = ['griddata', 'NearestNDInterpolator', 'LinearNDInterpolator',
+           'CloughTocher2DInterpolator']
+
+#------------------------------------------------------------------------------
+# Nearest-neighbor interpolation
+#------------------------------------------------------------------------------
+
+
+class NearestNDInterpolator(NDInterpolatorBase):
+    """NearestNDInterpolator(x, y).
+
+    Nearest-neighbor interpolator in N > 1 dimensions.
+
+    .. versionadded:: 0.9
+
+    Methods
+    -------
+    __call__
+
+    Parameters
+    ----------
+    x : (npoints, ndims) 2-D ndarray of floats
+        Data point coordinates.
+    y : (npoints, ) 1-D ndarray of float or complex
+        Data values.
+    rescale : boolean, 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 ``cKDTree``.
+
+        .. versionadded:: 0.17.0
+
+    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.cKDTree``
+
+    .. 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 = cKDTree(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 cKDTree's query function to be explicitly set.
+            See `scipy.spatial.cKDTree.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 cKDtree
+        # 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):
+    """
+    Interpolate unstructured D-D data.
+
+    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
+
+    Returns
+    -------
+    ndarray
+        Array of interpolated values.
+
+    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
+
+    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)
+    elif method == 'cubic' and ndim == 2:
+        ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value,
+                                        rescale=rescale)
+        return ip(xi)
+    else:
+        raise ValueError("Unknown interpolation method %r for "
+                         "%d dimensional data" % (method, ndim))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py
new file mode 100644
index 0000000000000000000000000000000000000000..387ef11dde5d3ace8a15324058c10fa31899c92c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py
@@ -0,0 +1,67 @@
+from numpy import zeros, asarray, eye, poly1d, hstack, r_
+from scipy import linalg
+
+__all__ = ["pade"]
+
+def pade(an, m, n=None):
+    """
+    Return Pade approximation to a polynomial as the ratio of two polynomials.
+
+    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
+
+    """
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cec3eb9939abba36505010334911c167797b750
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py
@@ -0,0 +1,961 @@
+import warnings
+
+import numpy as np
+from scipy.special import factorial
+from scipy._lib._util import (_asarray_validated, float_factorial, check_random_state,
+                              _transition_to_rng)
+
+
+__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')
+
+    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 : integer, 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 : integer, 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):
+    """
+    Interpolating polynomial for a set of points.
+
+    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 polynomial 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]
+
+
+def approximate_taylor_polynomial(f,x,degree,scale,order=None):
+    """
+    Estimate the Taylor polynomial of f at x by polynomial fitting.
+
+    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()
+
+    """
+    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"""Interpolating polynomial for a set of points.
+
+    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 reasons of numerical stability, this function does not compute
+    the coefficients of the polynomial.
+
+    The values `yi` need to be provided before the function is
+    evaluated, but none of the preprocessing depends on them, so rapid
+    updates are possible.
+
+    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.
+    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 class 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.
+
+    Based on Berrut and Trefethen 2004, "Barycentric Lagrange Interpolation".
+
+    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, \frac{\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$"])
+    >>> axs[0].set_ylabel("$f(x)$")
+    >>> axs[1].set_ylabel("$f'(x)$")
+    >>> axs[2].set_ylabel("$f''(x)$")
+    >>> axs[3].set_ylabel("$f^{(3)}(x)$")
+    >>> axs[4].set_ylabel("$f^{(4)}(x)$")
+    >>> 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()
+    """ # 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 : integer, 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 polynomial 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed52230dd1cce678e56ca4427e10bafd07e501c0
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py
@@ -0,0 +1,290 @@
+"""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
+
+__all__ = ['Rbf']
+
+
+class Rbf:
+    """
+    Rbf(*args, **kwargs)
+
+    A class for radial basis function interpolation of functions from
+    N-D scattered data to an M-D domain.
+
+    .. 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py
new file mode 100644
index 0000000000000000000000000000000000000000..6690e6ccf7d5499db10efffb0ef1c0139a90d2ba
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py
@@ -0,0 +1,550 @@
+"""Module for RBF interpolation."""
+import warnings
+from itertools import combinations_with_replacement
+
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy.spatial import KDTree
+from scipy.special import comb
+from scipy.linalg.lapack import dgesv  # type: ignore[attr-defined]
+
+from ._rbfinterp_pythran import (_build_system,
+                                 _build_evaluation_coefficients,
+                                 _polynomial_matrix)
+
+
+__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 _monomial_powers(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, exact=True)
+    out = np.zeros((nmonos, ndim), dtype=np.dtype("long"))
+    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
+
+
+def _build_and_solve_system(y, d, smoothing, kernel, epsilon, powers):
+    """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
+        )
+    _, _, coeffs, info = dgesv(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)
+            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
+
+
+class RBFInterpolator:
+    """Radial basis function (RBF) interpolation in N 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(y, 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))
+
+    >>> xgrid = np.mgrid[-1:1:50j, -1:1:50j]
+    >>> xflat = xgrid.reshape(2, -1).T
+    >>> 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()
+
+    """
+
+    def __init__(self, y, d,
+                 neighbors=None,
+                 smoothing=0.0,
+                 kernel="thin_plate_spline",
+                 epsilon=None,
+                 degree=None):
+        y = np.asarray(y, dtype=float, order="C")
+        if y.ndim != 2:
+            raise ValueError("`y` must be a 2-dimensional array.")
+
+        ny, ndim = y.shape
+
+        d_dtype = complex if np.iscomplexobj(d) else float
+        d = np.asarray(d, dtype=d_dtype, order="C")
+        if d.shape[0] != ny:
+            raise ValueError(
+                f"Expected the first axis of `d` to have length {ny}."
+                )
+
+        d_shape = d.shape[1:]
+        d = d.reshape((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)
+
+        if np.isscalar(smoothing):
+            smoothing = np.full(ny, smoothing, dtype=float)
+        else:
+            smoothing = np.asarray(smoothing, dtype=float, order="C")
+            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 = _monomial_powers(ndim, degree)
+        # 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 = _build_and_solve_system(
+                y, d, smoothing, kernel, epsilon, powers
+                )
+
+            # 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
+
+    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
+        """
+        nx, ndim = x.shape
+        if self.neighbors is None:
+            nnei = len(y)
+        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 = np.empty((nx, self.d.shape[1]), dtype=float)
+            for i in range(0, nx, chunksize):
+                vec = _build_evaluation_coefficients(
+                    x[i:i + chunksize, :],
+                    y,
+                    self.kernel,
+                    self.epsilon,
+                    self.powers,
+                    shift,
+                    scale)
+                out[i:i + chunksize, :] = np.dot(vec, coeffs)
+        else:
+            vec = _build_evaluation_coefficients(
+                x,
+                y,
+                self.kernel,
+                self.epsilon,
+                self.powers,
+                shift,
+                scale)
+            out = np.dot(vec, coeffs)
+        return out
+
+    def __call__(self, x):
+        """Evaluate the interpolant at `x`.
+
+        Parameters
+        ----------
+        x : (Q, N) array_like
+            Evaluation point coordinates.
+
+        Returns
+        -------
+        (Q, ...) ndarray
+            Values of the interpolant at `x`.
+
+        """
+        x = np.asarray(x, dtype=float, order="C")
+        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(x.size + self.y.size + self.d.size, 1000000)
+
+        if self.neighbors is None:
+            out = self._chunk_evaluator(
+                x,
+                self.y,
+                self._shift,
+                self._scale,
+                self._coeffs,
+                memory_budget=memory_budget)
+        else:
+            # 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,
+                )
+                out[xidx] = self._chunk_evaluator(
+                    xnbr,
+                    ynbr,
+                    shift,
+                    scale,
+                    coeffs,
+                    memory_budget=memory_budget)
+
+        out = out.view(self.d_dtype)
+        out = out.reshape((nx, ) + self.d_shape)
+        return out
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e20200568ed961849b5510e8626cdbe6e5b9643
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py
@@ -0,0 +1,759 @@
+__all__ = ['RegularGridInterpolator', 'interpn']
+
+import itertools
+
+import numpy as np
+
+import scipy.sparse.linalg as ssl
+
+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(
+                    "The points in dimension %d must be strictly "
+                    "ascending or descending" % i)
+        # 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("There are %d point arrays, but values has %d "
+                         "dimensions" % (len(points), values.ndim))
+    for i, p in enumerate(points):
+        if not np.asarray(p).ndim == 1:
+            raise ValueError("The points in dimension %d must be "
+                             "1-dimensional" % i)
+        if not values.shape[i] == len(p):
+            raise ValueError("There are %d points and %d values in "
+                             "dimension %d" % (len(p), values.shape[i], i))
+
+
+class RegularGridInterpolator:
+    """
+    Interpolator on a regular or rectilinear grid in arbitrary 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.
+
+    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
+
+    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)
+        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 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 result.reshape(xi_shape[:-1] + self.values.shape[ndim:])
+
+    def _prepare_xi(self, xi):
+        ndim = len(self.grid)
+        xi = _ndim_coords_from_arrays(xi, ndim=ndim)
+        if xi.shape[-1] != len(self.grid):
+            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("One of the requested xi is out of bounds "
+                                     "in dimension %d" % 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.
+
+        .. deprecated:: 1.13.0
+            Complex data is deprecated with ``method="pchip"`` and will raise an
+            error in SciPy 1.15.0. This is because ``PchipInterpolator`` only
+            works with real values. If you are trying to use the real components of
+            the passed array, use ``np.real`` on ``values``.
+
+    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]
+
+    """
+    # 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("There are %d point arrays, but values has %d "
+                         "dimensions" % (len(points), ndim))
+    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("The requested sample points xi have dimension "
+                         "%d, but this RegularGridInterpolator has "
+                         "dimension %d" % (xi.shape[-1], 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("One of the requested xi is out of bounds "
+                                 "in dimension %d" % 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..e10da3b3fd0c69dede4767dc17b62c327818ecce
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py
@@ -0,0 +1,44 @@
+# 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
+    'bispeu',
+    'bispev',
+    'curfit',
+    'dblint',
+    'fpchec',
+    'fpcurf0',
+    'fpcurf1',
+    'fpcurfm1',
+    'parcur',
+    'parder',
+    'pardeu',
+    'pardtc',
+    'percur',
+    'regrid_smth',
+    'regrid_smth_spher',
+    'spalde',
+    'spherfit_lsq',
+    'spherfit_smth',
+    'splder',
+    'splev',
+    'splint',
+    'sproot',
+    'surfit_lsq',
+    'surfit_smth',
+    'types',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="dfitpack",
+                                   private_modules=["_dfitpack"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..6490c93fe02b4c665b032d09e2ad3c269e1f7970
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f993961f94d913d632aa3d2cc7b1348659a6a613
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py
new file mode 100644
index 0000000000000000000000000000000000000000..4288ac233fdde98dbb19aed84b916cfd15302f4c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py
@@ -0,0 +1,25 @@
+# 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',
+    'GradientEstimationWarning',
+    'LinearNDInterpolator',
+    'NDInterpolatorBase',
+    'estimate_gradients_2d_global',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="interpnd",
+                                   private_modules=["_interpnd"], all=__all__,
+                                   attribute=name)
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpolate.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..341d13954c81130cceb8afe070db023a82550e7a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/ndgriddata.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..20373eaaedaa1cdec6c7a4bc12639d9658bfa85b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/polyint.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..e81306304abffb313ab5abe09116a162642a9d67
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/rbf.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..772752ef536f4a3b47fb6f9b5d250c5d7f198d85
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bary_rational.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bary_rational.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbeea868ea24292693ced4cfb230badc3a551a89
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bary_rational.py
@@ -0,0 +1,368 @@
+# 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="same size"):
+            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)
+
+    @pytest.mark.thread_unsafe
+    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-13, 0),
+                              (lambda x: np.exp(-100*x**2), 8e-13, 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)
+
+    @pytest.mark.thread_unsafe
+    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)
+
+
+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="dimension"):
+            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 an 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
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bsplines.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8b1b2b58afcf5ad5a34babe65fff96bf268df03
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_bsplines.py
@@ -0,0 +1,3658 @@
+import os
+import operator
+import itertools
+import math
+import threading
+
+import numpy as np
+from numpy.testing import suppress_warnings
+from scipy._lib._array_api import xp_assert_equal, xp_assert_close
+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 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 _dfitpack as dfitpack
+from scipy.interpolate import _bsplines as _b
+from scipy.interpolate import _dierckx
+
+
+class TestBSpline:
+
+    def test_ctor(self):
+        # 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 = np.arange(n+k+1, dtype=np.float64)
+        c = 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_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):
+        t = [0, 1, 2, 3, 4]
+        c = [1, 2, 3]
+        k = 1
+        b = BSpline(t, c, k)
+
+        x = np.linspace(1, 3, 50)
+        xp_assert_close(c[0]*B_012(x) + c[1]*B_012(x-1) + c[2]*B_012(x-2),
+                        b(x), atol=1e-14)
+        xp_assert_close(splev(x, (t, c, k)), b(x), atol=1e-14)
+
+    def test_bernstein(self):
+        # a special knot vector: Bernstein polynomials
+        k = 3
+        t = np.asarray([0]*(k+1) + [1]*(k+1))
+        c = np.asarray([1., 2., 3., 4.])
+        bp = BPoly(c.reshape(-1, 1), [0, 1])
+        bspl = BSpline(t, c, k)
+
+        xx = np.linspace(-1., 2., 10)
+        xp_assert_close(bp(xx, extrapolate=True),
+                        bspl(xx, extrapolate=True), atol=1e-14)
+        xp_assert_close(splev(xx, (t, c, k)),
+                        bspl(xx), atol=1e-14)
+
+    def test_rndm_naive_eval(self):
+        # test random coefficient spline *on the base interval*,
+        # t[k] <= x < t[-k-1]
+        b = _make_random_spline()
+        t, c, k = b.tck
+        xx = np.linspace(t[k], t[-k-1], 50)
+        y_b = b(xx)
+
+        y_n = [_naive_eval(x, t, c, k) for x in xx]
+        xp_assert_close(y_b, y_n, atol=1e-14)
+
+        y_n2 = [_naive_eval_2(x, t, c, k) 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):
+        b = _make_random_spline()
+        b.c = np.ones_like(b.c)
+        xx = np.linspace(b.t[b.k], b.t[-b.k-1], 100)
+        xp_assert_close(b(xx), np.ones_like(xx))
+
+    def test_vectorization(self):
+        rng = np.random.RandomState(1234)
+        n, k = 22, 3
+        t = np.sort(rng.random(n))
+        c = rng.random(size=(n, 6, 7))
+        b = BSpline(t, c, k)
+        tm, tp = t[k], t[-k-1]
+        xx = tm + (tp - tm) * 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):
+        b = _make_random_spline()
+        t, c, k = b.tck
+        dt = t[-1] - t[0]
+        xx = np.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
+        xp_assert_close(b(xx, extrapolate=True),
+                splev(xx, (t, c, k), ext=0))
+
+    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):
+        rng = np.random.RandomState(1234)
+        t = np.sort(rng.random(8))
+        c = rng.random(4)
+        k = 3
+        b = BSpline(t, c, k, extrapolate='periodic')
+        n = t.size - (k + 1)
+
+        dt = t[-1] - t[0]
+        xx = np.linspace(t[k] - dt, t[n] + dt, 50)
+        xy = t[k] + (xx - t[k]) % (t[n] - t[k])
+        xp_assert_close(b(xx), splev(xy, (t, c, k)))
+
+        # Direct check
+        xx = [-1, 0, 0.5, 1]
+        xy = t[k] + (xx - t[k]) % (t[n] - t[k])
+        xp_assert_equal(b(xx, extrapolate='periodic'), b(xy, extrapolate=True))
+
+    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))
+
+    def test_basis_element_quadratic(self):
+        xx = np.linspace(-1, 4, 20)
+        b = BSpline.basis_element(t=[0, 1, 2, 3])
+        xp_assert_close(b(xx),
+                        splev(xx, (b.t, b.c, b.k)), atol=1e-14)
+        xp_assert_close(b(xx),
+                        B_0123(xx), atol=1e-14)
+
+        b = BSpline.basis_element(t=[0, 1, 1, 2])
+        xx = np.linspace(0, 2, 10)
+        xp_assert_close(b(xx),
+                np.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):
+        # nan in, nan out.
+        b = BSpline.basis_element([0, 1, 1, 2])
+        assert np.isnan(b(np.nan))
+
+    def test_derivative_method(self):
+        b = _make_random_spline(k=5)
+        t, c, k = b.tck
+        b0 = BSpline(t, c, k)
+        xx = np.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):
+        b = _make_random_spline()
+        t, c, k = b.tck
+        xx = np.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 = np.c_[c, c, c]
+        c = np.dstack((c, c))
+        b = BSpline(t, c, k)
+        xp_assert_close(b.antiderivative().derivative()(xx),
+                        b(xx), atol=1e-14, rtol=1e-14)
+
+    def test_integral(self):
+        b = BSpline.basis_element([0, 1, 2])  # x for x < 1 else 2 - x
+        xp_assert_close(b.integrate(0, 1), np.asarray(0.5))
+        xp_assert_close(b.integrate(1, 0), np.asarray(-1 * 0.5))
+        xp_assert_close(b.integrate(1, 0), np.asarray(-0.5))
+
+        # extrapolate or zeros outside of [0, 2]; default is yes
+        xp_assert_close(b.integrate(-1, 1), np.asarray(0.0))
+        xp_assert_close(b.integrate(-1, 1, extrapolate=True), np.asarray(0.0))
+        xp_assert_close(b.integrate(-1, 1, extrapolate=False), np.asarray(0.5))
+        xp_assert_close(b.integrate(1, -1, extrapolate=False), np.asarray(-1 * 0.5))
+
+        # Test ``_fitpack._splint()``
+        xp_assert_close(b.integrate(1, -1, extrapolate=False),
+                        np.asarray(_impl.splint(1, -1, b.tck)))
+
+        # Test ``extrapolate='periodic'``.
+        b.extrapolate = 'periodic'
+        i = b.antiderivative()
+        period_int = np.asarray(i(2) - i(0))
+
+        xp_assert_close(b.integrate(0, 2), period_int)
+        xp_assert_close(b.integrate(2, 0), np.asarray(-1 * period_int))
+        xp_assert_close(b.integrate(-9, -7), period_int)
+        xp_assert_close(b.integrate(-8, -4), np.asarray(2 * period_int))
+
+        xp_assert_close(b.integrate(0.5, 1.5),
+                        np.asarray(i(1.5) - i(0.5)))
+        xp_assert_close(b.integrate(1.5, 3),
+                        np.asarray(i(1) - i(0) + i(2) - i(1.5)))
+        xp_assert_close(b.integrate(1.5 + 12, 3 + 12),
+                        np.asarray(i(1) - i(0) + i(2) - i(1.5)))
+        xp_assert_close(b.integrate(1.5, 3 + 12),
+                        np.asarray(i(1) - i(0) + i(2) - i(1.5) + 6 * period_int))
+
+        xp_assert_close(b.integrate(0, -1), np.asarray(i(0) - i(1)))
+        xp_assert_close(b.integrate(-9, -10), np.asarray(i(0) - i(1)))
+        xp_assert_close(b.integrate(0, -9),
+                        np.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):
+        n, k = 22, 3
+        t = np.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 = 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):
+        k = 2
+        t = [0, 1, 2, 3, 4, 5, 6]
+        c = np.array([[-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), [spl0(2.5), spl1(2.5)])
+
+    @pytest.mark.thread_unsafe
+    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):
+        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):
+        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)
+
+    @pytest.mark.thread_unsafe
+    def test_concurrency(self):
+        # Check that no segfaults appear with concurrent access to BSpline
+        b = _make_random_spline()
+
+        def worker_fn(_, b):
+            t, _, k = b.tck
+            xx = np.linspace(t[k], t[-k-1], 10000)
+            b(xx)
+
+        _run_concurrent_barrier(10, worker_fn, b)
+
+
+    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)
+
+class TestInsert:
+
+    @pytest.mark.parametrize('xval', [0.0, 1.0, 2.5, 4, 6.5, 7.0])
+    def test_insert(self, xval):
+        # insert a knot, incl edges (0.0, 7.0) and exactly at an existing knot (4.0)
+        x = np.arange(8)
+        y = np.sin(x)**3
+        spl = make_interp_spline(x, y, k=3)
+
+        spl_1f = insert(xval, spl)     # FITPACK
+        spl_1 = spl.insert_knot(xval)
+
+        xp_assert_close(spl_1.t, spl_1f.t, atol=1e-15)
+        xp_assert_close(spl_1.c, 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 = np.r_[xx, 0.5*(x[1:] + x[:-1])]
+        xp_assert_close(spl(xx), spl_1(xx), atol=1e-15)
+
+        # ... repeat with ndim > 1
+        y1 = np.cos(x)**3
+        spl_y1 = make_interp_spline(x, y1, k=3)
+        spl_yy = make_interp_spline(x, np.c_[y, y1], 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, np.c_[spl.insert_knot(xval).c,
+                                         spl_y1.insert_knot(xval).c], atol=1e-15)
+
+        xx = x if xval != x[-1] else x[:-1]
+        xx = np.r_[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):
+        x = np.arange(8)
+        y = np.sin(x)**3
+        spl = make_interp_spline(x, y, k=3)
+
+        spl_1f = insert(xval, spl, m=m)
+        spl_1 = spl.insert_knot(xval, m)
+
+        xp_assert_close(spl_1.t, spl_1f.t, atol=1e-15)
+        xp_assert_close(spl_1.c, spl_1f.c[:-spl.k-1], atol=1e-15)
+
+        xx = x if xval != x[-1] else x[:-1]
+        xx = np.r_[xx, 0.5*(x[1:] + x[:-1])]
+        xp_assert_close(spl(xx), spl_1(xx), atol=1e-15)
+
+    def test_insert_random(self):
+        rng = np.random.default_rng(12345)
+        n, k = 11, 3
+
+        t = np.sort(rng.uniform(size=n+k+1))
+        c = rng.uniform(size=(n, 3, 2))
+        spl = BSpline(t, c, k)
+
+        xv = rng.uniform(low=t[k+1], high=t[-k-1])
+        spl_1 = spl.insert_knot(xv)
+
+        xx = 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):
+        x = np.arange(8)
+        y = np.sin(x)**3
+        tck = splrep(x, y, k=3)
+        spl = BSpline(*tck, extrapolate="periodic")
+
+        spl_1 = spl.insert_knot(xv)
+        tf, cf, k = insert(xv, spl.tck, per=True)
+
+        xp_assert_close(spl_1.t, tf, atol=1e-15)
+        xp_assert_close(spl_1.c[:-k-1], cf[:-k-1], atol=1e-15)
+
+        xx = np.random.default_rng(1234).uniform(low=0, high=7, size=41)
+        xp_assert_close(spl_1(xx), splev(xx, (tf, cf, k)), atol=1e-15)
+
+    @pytest.mark.parametrize('extrapolate', [None, 'periodic'])
+    def test_complex(self, extrapolate):
+        x = np.arange(8)*2*np.pi
+        y_re, y_im = np.sin(x), np.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)
+
+
+### stolen from @pv, verbatim
+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)
+
+
+### stolen from @pv, verbatim
+def _naive_eval(x, t, c, k):
+    """
+    Naive B-spline evaluation. Useful only for testing!
+    """
+    if x == t[k]:
+        i = k
+    else:
+        i = np.searchsorted(t, x) - 1
+    assert t[i] <= x <= t[i+1]
+    assert i >= k and i < len(t) - 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):
+    """Naive B-spline evaluation, another way."""
+    n = len(t) - (k+1)
+    assert n >= k+1
+    assert len(c) >= 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 len(c) >= 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):
+    """ A linear B-spline function B(x | 0, 1, 2)."""
+    x = np.atleast_1d(x)
+    return 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])
+
+
+def B_0123(x, der=0):
+    """A quadratic B-spline function B(x | 0, 1, 2, 3)."""
+    x = np.atleast_1d(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):
+    rng = np.random.RandomState(123)
+    t = np.sort(rng.random(n+k+1))
+    c = rng.random(n)
+    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="Invalid inputs"):
+            splprep([x])
+        with assert_raises(ValueError, match="Invalid inputs"):
+            _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="Invalid inputs"):
+            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
+
+
+class TestInterp:
+    #
+    # Test basic ways of constructing interpolating splines.
+    #
+    xx = np.linspace(0., 2.*np.pi)
+    yy = np.sin(xx)
+
+    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):
+        b = make_interp_spline(self.xx, self.yy, k=0)
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+        b = make_interp_spline(self.xx, self.yy, k=0, axis=-1)
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+
+    def test_linear(self):
+        b = make_interp_spline(self.xx, self.yy, k=1)
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+        b = make_interp_spline(self.xx, self.yy, k=1, axis=-1)
+        xp_assert_close(b(self.xx), self.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):
+        for k in [2, 3, 4, 5, 6, 7]:
+            b = make_interp_spline(self.xx, self.yy, k)
+            xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+
+    def test_periodic(self):
+        # k = 5 here for more derivatives
+        b = make_interp_spline(self.xx, self.yy, k=5, bc_type='periodic')
+        xp_assert_close(b(self.xx), self.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(self.xx[0], nu=i), b(self.xx[-1], nu=i), atol=1e-11)
+        # tests for axis=-1
+        b = make_interp_spline(self.xx, self.yy, k=5, bc_type='periodic', axis=-1)
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+        for i in range(1, 5):
+            xp_assert_close(b(self.xx[0], nu=i), b(self.xx[-1], nu=i), atol=1e-11)
+
+    @pytest.mark.parametrize('k', [2, 3, 4, 5, 6, 7])
+    def test_periodic_random(self, k):
+        # 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]
+        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):
+        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)
+        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_assert_close(b(self.xx), b1(self.xx), atol=1e-14)
+
+    def test_quadratic_deriv(self):
+        der = [(1, 8.)]  # order, value: f'(x) = 8.
+
+        # derivative at right-hand edge
+        b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(None, der))
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(
+            b(self.xx[-1], 1), der[0][1], atol=1e-14, rtol=1e-14, check_0d=False
+        )
+
+        # derivative at left-hand edge
+        b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(der, None))
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(
+            b(self.xx[0], 1), der[0][1], atol=1e-14, rtol=1e-14, check_0d=False
+        )
+
+    def test_cubic_deriv(self):
+        k = 3
+
+        # first derivatives at left & right edges:
+        der_l, der_r = [(1, 3.)], [(1, 4.)]
+        b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r))
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(np.asarray([b(self.xx[0], 1), b(self.xx[-1], 1)]),
+                        np.asarray([der_l[0][1], der_r[0][1]]), 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(self.xx, self.yy, k, bc_type=(der_l, der_r))
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+
+    def test_quintic_derivs(self):
+        k, n = 5, 7
+        x = np.arange(n).astype(np.float64)
+        y = np.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(np.asarray([b(x[0], 1), b(x[0], 2)]),
+                        np.asarray([val for (nu, val) in der_l]))
+        xp_assert_close(np.asarray([b(x[-1], 1), b(x[-1], 2)]),
+                        np.asarray([val for (nu, val) in der_r]))
+
+    @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):
+        # 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
+        t = np.r_[(self.xx[0],)*(k+1),
+                  (self.xx[1:] + self.xx[:-1]) / 2.,
+                  (self.xx[-1],)*(k+1)]
+        b = make_interp_spline(self.xx, self.yy, k, t,
+                               bc_type=([(2, 0)], [(2, 0)]))
+
+        xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(b(self.xx[0], 2), np.asarray(0.0), atol=1e-14)
+        xp_assert_close(b(self.xx[-1], 2), np.asarray(0.0), atol=1e-14)
+
+    def test_minimum_points_and_deriv(self):
+        # 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 = [0., 1.]
+        y = [0., 1.]
+        b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)]))
+
+        xx = np.linspace(0., 1.)
+        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):
+        x = np.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):
+        k = 3
+        xx = self.xx
+        yy = self.yy + 1.j*self.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)
+        xp_assert_close(
+            b(xx[0], 1), der_l[0][1], atol=1e-14, rtol=1e-14, check_0d=False
+        )
+        xp_assert_close(
+            b(xx[-1], 1), der_r[0][1], atol=1e-14, rtol=1e-14, check_0d=False
+        )
+
+        # 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):
+        x = np.arange(10).astype(int)
+        y = np.arange(10).astype(int)
+
+        # 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):
+        # Cython code chokes on non C contiguous arrays
+        xx = np.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):
+        # check_finite defaults to True; nans and such trigger a ValueError
+        x = np.arange(10).astype(float)
+        y = x**2
+
+        for z in [np.nan, np.inf, -np.inf]:
+            y[-1] = 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):
+        yy = np.c_[np.sin(self.xx), np.cos(self.xx)]
+        der_l = [(1, [1., 2.])]
+        der_r = [(1, [3., 4.])]
+
+        b = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r))
+        xp_assert_close(b(self.xx), yy, atol=1e-14, rtol=1e-14)
+        xp_assert_close(b(self.xx[0], 1), der_l[0][1], atol=1e-14, rtol=1e-14)
+        xp_assert_close(b(self.xx[-1], 1), der_r[0][1], 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):
+        yy = np.sin(self.xx)
+
+        # a single string is duplicated
+        b1 = make_interp_spline(self.xx, yy, k=3, bc_type='natural')
+        b2 = make_interp_spline(self.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(self.xx, yy, k=3,
+                                bc_type=('natural', 'clamped'))
+        b2 = make_interp_spline(self.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(self.xx, yy, k=2, bc_type=(None, 'clamped'))
+        b2 = make_interp_spline(self.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(self.xx, yy, k=3, bc_type='not-a-knot')
+        b2 = make_interp_spline(self.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(self.xx, yy, k=3, bc_type='typo')
+
+        # string aliases are handled for 2D values
+        yy = np.c_[np.sin(self.xx), np.cos(self.xx)]
+        der_l = [(1, [0., 0.])]
+        der_r = [(2, [0., 0.])]
+        b2 = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r))
+        b1 = make_interp_spline(self.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))
+
+        # now throw in some derivatives
+        d_l = [(1, np.zeros((5, 6, 7)))]
+        d_r = [(1, np.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):
+        rng = np.random.RandomState(1234)
+        k, n = 3, 7
+        x = np.sort(rng.random(size=n))
+        y = rng.random(size=n)
+        t = _not_a_knot(x, k)
+
+        b = make_interp_spline(x, y, k, t)
+        cf = make_interp_full_matr(x, y, t, k)
+        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"])
+
+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):
+        # weights = 1 is same as None
+        x, y, t, k = self.x, self.y, self.t, self.k
+        w = np.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):
+        # both methods treat weights
+        x, y, t, k = self.x, self.y, self.t, self.k
+        w = np.random.default_rng(1234).uniform(size=x.shape[0])
+
+        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 np.allclose(b_no_w.c, b_qr.c, atol=1e-14)
+
+    @parametrize_lsq_methods
+    def test_multiple_rhs(self, method):
+        x, t, k, n = self.x, self.t, self.k, self.n
+        rng = np.random.RandomState(1234)
+        y = rng.random(size=(n, 5, 6, 7))
+        b = make_lsq_spline(x, y, t, k, method=method)
+        assert b.c.shape == (t.size-k-1, 5, 6, 7)
+
+    @parametrize_lsq_methods
+    def test_multiple_rhs_2(self, method):
+        x, t, k, n = self.x, self.t, self.k, self.n
+        nrhs = 3
+        rng = np.random.RandomState(1234)
+        y = rng.random(size=(n, nrhs))
+        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 = np.vstack([bb[i].c for i in range(nrhs)]).T
+
+        xp_assert_close(coefs, b.c, atol=1e-15)
+
+    def test_multiple_rhs_3(self):
+        x, t, k, n = self.x, self.t, self.k, self.n
+        nrhs = 3
+        y = np.random.random(size=(n, nrhs))
+        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):
+        # cmplx-valued `y`
+        x, t, k = self.x, self.t, self.k
+        yc = self.y * (1. + 2.j)
+
+        b = make_lsq_spline(x, yc, t, k, method=method)
+        b_re = make_lsq_spline(x, yc.real, t, k, method=method)
+        b_im = make_lsq_spline(x, yc.imag, 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):
+        # test complex-valued y with y.ndim > 1
+
+        x, t, k = self.x, self.t, self.k
+        yc = self.y * (1. + 2.j)
+        yc = np.stack((yc, yc), axis=1)
+
+        b = make_lsq_spline(x, yc, t, k)
+        b_re = make_lsq_spline(x, yc.real, t, k)
+        b_im = make_lsq_spline(x, yc.imag, 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 = np.stack((yc, yc), axis=1)
+
+        b = make_lsq_spline(x, yc, t, k)
+        b_re = make_lsq_spline(x, yc.real, t, k)
+        b_im = make_lsq_spline(x, yc.imag, 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 dlartg
+
+    # 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, 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, y)
+
+        xp_assert_close(cc, c, atol=1e-14)
+
+
+def data_file(basename):
+    return os.path.join(os.path.abspath(os.path.dirname(__file__)),
+                        'data', basename)
+
+
+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):
+        """
+        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)
+
+        spline_GCV = make_smoothing_spline(x, y, lam=0.)
+        spline_interp = make_interp_spline(x, y, 3, bc_type='natural')
+
+        grid = np.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):
+        # 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)
+
+        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 = np.ones(n)
+            w[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)
+
+
+class TestNdBSpline:
+
+    def test_1D(self):
+        # 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))
+
+        b = BSpline(t, c, k)
+        nb = NdBSpline((t,), c, k)
+
+        xi = rng.uniform(size=21)
+        # 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):
+        # make a 2D separable spline
+        x = np.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):
+        # make a 2D separable spline w/ kx=3, ky=2
+        x = np.arange(6)
+        y = x**3
+        spl = make_interp_spline(x, y, k=3)
+
+        x = np.arange(5) + 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):
+        xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)]
+        t2, c2, k = self.make_2d_case()
+        target = [x**3 * (y**3 + 2*y) for (x, y) in xi]
+
+        # sanity check: bspline2 gives the product as constructed
+        xp_assert_close(np.asarray([bspline2(xy, t2, c2, k) for xy in xi]),
+                        np.asarray(target),
+                        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),
+                        target, atol=1e-14)
+
+        # now check on a multidim xi
+        rng = np.random.default_rng(12345)
+        xi = rng.uniform(size=(4, 3, 2)) * 5
+        result = bspl2(xi)
+        assert result.shape == (4, 3)
+
+        # also check the values
+        x, y = xi.reshape((-1, 2)).T
+        xp_assert_close(result.ravel(),
+                        x**3 * (y**3 + 2*y), atol=1e-14)
+
+    def test_2D_separable_2(self):
+        # 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()
+        c2_4 = np.dstack((c2, c2, c2, c2))   # 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,
+                        [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),  np.asarray(target)[:, None],
+                        check_shape=False,
+                        atol=5e-14)
+
+        # two trailing dimensions
+        c2_22 = c2_4.reshape((6, 6, 2, 2))
+        bspl2_22 = NdBSpline(t2, c2_22, k=3)
+
+        result = bspl2_22(xy)
+        assert result.shape == (2, 2)
+        xp_assert_close(result,
+                        [[val_single, val_single],
+                         [val_single, val_single]], 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), np.asarray(target)[:, None, None],
+                        check_shape=False,
+                        atol=5e-14)
+
+
+    def test_2D_separable_2_complex(self):
+        # 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()
+        c2 = c2 * (1 + 2j)
+        c2_4 = np.dstack((c2, c2, c2, c2))   # 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,
+                        [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):
+        t2, c2, kx, ky = self.make_2d_mixed()
+        xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)]
+        bspl2 = NdBSpline(t2, c2, k=(kx, ky))
+
+        der = bspl2(xi, nu=(1, 0))
+        xp_assert_close(der,
+                        [3*x**2 * (y**2 + 2*y) for x, y in xi], atol=1e-14)
+
+        der = bspl2(xi, nu=(1, 1))
+        xp_assert_close(der,
+                        [3*x**2 * (2*y + 2) for x, y in xi], atol=1e-14)
+
+        der = bspl2(xi, nu=(0, 0))
+        xp_assert_close(der,
+                        [x**3 * (y**2 + 2*y) for x, y in xi], atol=1e-14)
+
+        with assert_raises(ValueError):
+            # all(nu >= 0)
+            der = bspl2(xi, nu=(-1, 0))
+
+        with assert_raises(ValueError):
+            # len(nu) == ndim
+            der = bspl2(xi, nu=(-1, 0, 1))
+
+    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):
+        # make a 3D separable spline
+        x = np.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):
+        t3, c3, k = self.make_3d_case()
+        bspl3 = NdBSpline(t3, c3, k=3)
+        rng = np.random.default_rng(12345)
+        x, y, z = rng.uniform(size=(3, 11)) * 5
+        xi = [_ for _ in zip(x, y, z)]
+
+        xp_assert_close(bspl3(xi, nu=(1, 0, 0)),
+                        3*x**2 * (y**3 + 2*y) * (z**3 + 3*z + 1), atol=1e-14)
+
+        xp_assert_close(bspl3(xi, nu=(2, 0, 0)),
+                        6*x * (y**3 + 2*y) * (z**3 + 3*z + 1), atol=1e-14)
+
+        xp_assert_close(bspl3(xi, nu=(2, 1, 0)),
+                        6*x * (3*y**2 + 2) * (z**3 + 3*z + 1), atol=1e-14)
+
+        xp_assert_close(bspl3(xi, nu=(2, 1, 3)),
+                        6*x * (3*y**2 + 2) * (6), atol=1e-14)
+
+        xp_assert_close(bspl3(xi, nu=(2, 1, 4)),
+                        np.zeros(len(xi)), 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)
+
+    @pytest.mark.thread_unsafe
+    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 _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
+
+
+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):
+        x = np.arange(8, dtype=np.float64)
+        y = np.sin(x*np.pi/8)
+        t = list(generate_knots(x, y, k=k, s=0))[-1]
+
+        tt = splrep(x, y, k=k, s=0)[0]
+        xp_assert_close(t, tt, atol=1e-15)
+
+    def test_s0_1(self):
+        # with these data, naive algorithm tries to insert >= nmax knots
+        n = 10
+        x = np.arange(n)
+        y = x**3
+        knots = list(generate_knots(x, y, k=3, s=0))   # does not error out
+        xp_assert_close(knots[-1], _not_a_knot(x, 3), atol=1e-15)
+
+    def test_s0_n20(self):
+        n = 20
+        x = np.arange(n)
+        y = x**3
+        knots = list(generate_knots(x, y, k=3, s=0))
+        xp_assert_close(knots[-1], _not_a_knot(x, 3), 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):
+        # 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 = np.arange(8)
+        y = np.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.]
+        ]
+
+        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], 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):
+        # test that nest < nmax stops the process early (and we get 10 knots not 12)
+        x = np.arange(8)
+        y = np.sin(x*np.pi/8)
+        s = 1e-7
+
+        knots = list(generate_knots(x, y, k=3, s=s, nest=10))
+        xp_assert_close(knots[-1],
+                        [0., 0., 0., 0., 2., 4., 7., 7., 7., 7.], 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)
+
+    @pytest.mark.thread_unsafe
+    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 suppress_warnings() as sup:
+            r = sup.record(RuntimeWarning)
+            tck = splrep(x, y, k=3, s=1e-50)
+            assert len(r) == 1
+        xp_assert_equal(knots[-1], tck[0])
+
+
+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):
+        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
+        assert self.w.ndim == 1
+
+        # lhs
+        a_dense = BSpline(t, np.eye(t.shape[0] - k - 1), k)(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)
+        fp = np.sum(self.w**2 * (spl(self.x) - self.y)**2)
+
+        self.spl = spl   # store it
+
+        return fp - self.s
+
+
+class TestMakeSplrep:
+    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)
+
+        with assert_raises(ValueError):
+            # 0D inputs
+            make_splrep(1, 2, s=0.1)
+
+        with assert_raises(ValueError):
+            # y.ndim > 2
+            y = np.ones((x.size, 2, 2, 2))
+            make_splrep(x, y, s=0.1)
+
+        w = np.ones(12)
+        with assert_raises(ValueError):
+            # len(weights) != len(x)
+            make_splrep(x, x**3, w=w, s=0.1)
+
+        w = -np.ones(12)
+        with assert_raises(ValueError):
+            # w < 0
+            make_splrep(x, x**3, w=w, s=0.1)
+
+        w = np.ones((x.shape[0], 2))
+        with assert_raises(ValueError):
+            # w.ndim != 1
+            make_splrep(x, x**3, w=w, s=0.1)
+
+        with assert_raises(ValueError):
+            # x not ordered
+            make_splrep(x[::-1], x**3, s=0.1)
+
+        with assert_raises(TypeError):
+            # k != int(k)
+            make_splrep(x, x**3, k=2.5, s=0.1)
+
+        with assert_raises(ValueError):
+            # s < 0
+            make_splrep(x, x**3, s=-1)
+
+        with assert_raises(ValueError):
+            # nest < 2*k + 2
+            make_splrep(x, x**3, k=3, nest=2, s=0.1)
+
+        with assert_raises(ValueError):
+            # nest not None and s==0
+            make_splrep(x, x**3, s=0, nest=11)
+
+        with assert_raises(ValueError):
+            # len(x) != len(y)
+            make_splrep(np.arange(8), np.arange(9), s=0.1)
+
+    def _get_xykt(self):
+        x = np.linspace(0, 5, 11)
+        y  = np.sin(x*3.14 / 5)**2
+        k = 3
+        s = 1.7e-4
+        tt = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1))
+
+        return x, y, k, s, tt
+
+    def test_fitpack_F(self):
+        # test an implementation detail: banded/packed linalg vs full matrices
+        from scipy.interpolate._fitpack_repro import F
+
+        x, y, k, s, t = self._get_xykt()
+        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)
+
+    def test_fitpack_F_with_weights(self):
+        # repeat test_fitpack_F, with weights
+        from scipy.interpolate._fitpack_repro import F
+
+        x, y, k, s, t = self._get_xykt()
+        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):
+        x, y, k, s, tt = self._get_xykt()
+        tt = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1))
+
+        t,c,k = splrep(x, y, k=k, s=s)
+        assert all(t == tt)
+
+        spl = make_splrep(x, y, k=k, s=s)
+        xp_assert_close(c[:spl.c.size], spl.c, atol=1e-15)
+
+    def test_with_knots(self):
+        x, y, k, 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):
+        # should not fail if there are no internal knots
+        n = 10
+        x = np.arange(n)
+        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):
+        n = 10
+        x = np.arange(n)
+        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)
+
+    @pytest.mark.thread_unsafe
+    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 suppress_warnings() as sup:
+            r = sup.record(RuntimeWarning)
+            tck = splrep(x, y, k=3, s=1e-50)
+            spl = make_splrep(x, y, k=3, s=1e-50)
+            assert len(r) == 2
+            xp_assert_equal(spl.t, tck[0])
+            xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
+                            tck[1], atol=5e-13)
+
+    def test_shape(self):
+        # make sure coefficients have the right shape (not extra dims)
+        n, k = 10, 3
+        x = np.arange(n)
+        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):
+        # check that the shapes are consistent
+        n, k = 10, 3
+        x = np.arange(n)
+        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)
+
+
+class TestMakeSplprep:
+    def _get_xyk(self, m=10, k=3):
+        x = np.arange(m) * np.pi / m
+        y = [np.sin(x), np.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])
+        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)
+        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):
+        x, y, k = self._get_xyk(m=10)
+
+        spl, u = make_splprep(y)
+        xp_assert_close(spl(u), y, atol=1e-15)
+
+    def test_s_zero_vs_near_zero(self):
+        # s=0 and s \approx 0 are consistent
+        x, y, k = self._get_xyk(m=10)
+
+        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), y, atol=1e-15)
+        xp_assert_close(spl_n(u_n), 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)
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..d798f0eda4eb0c099bdf46cb4b3468628013c9d3
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py
@@ -0,0 +1,519 @@
+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._dfitpack import regrid_smth
+from scipy.interpolate._fitpack2 import dfitpack_int
+
+
+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
+
+    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)
+        self.check_1(b=1.5*np.pi, xe=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.shape = 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)
+
+
+def test_dblint():
+    # 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)
+    tck = list(rect.tck)
+    tck.extend(rect.degrees)
+
+    assert abs(dblint(0, 1, 0, 1, tck) - 1) < 1e-10
+    assert abs(dblint(0, 0.5, 0, 1, tck) - 0.25) < 1e-10
+    assert abs(dblint(0.5, 1, 0, 1, tck) - 0.75) < 1e-10
+    assert abs(dblint(-100, 100, -100, 100, tck) - 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
+
+
+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)
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack2.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..044ace830bc6af26ee12edbcc6488e46bdfbcce6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack2.py
@@ -0,0 +1,1393 @@
+# Created by Pearu Peterson, June 2003
+import itertools
+from threading import Lock
+import numpy as np
+from numpy.testing import suppress_warnings
+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
+
+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])
+
+        spl = make_splrep(x, y, k=1, s=len(x))
+        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]))
+
+    @pytest.mark.thread_unsafe
+    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.]
+        with suppress_warnings() as sup:
+            r = sup.record(
+                UserWarning,
+                r"""
+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.""")
+            UnivariateSpline(x, y, k=1)
+            assert len(r) == 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)
+
+
+class TestLSQBivariateSpline:
+    # NOTE: The systems in this test class are rank-deficient
+    @pytest.mark.thread_unsafe
+    def test_linear_constant(self):
+        x = [1,1,1,2,2,2,3,3,3]
+        y = [1,2,3,1,2,3,1,2,3]
+        z = [3,3,3,3,3,3,3,3,3]
+        s = 0.1
+        tx = [1+s,3-s]
+        ty = [1+s,3-s]
+        with suppress_warnings() as sup:
+            r = sup.record(UserWarning, "\nThe coefficients of the spline")
+            lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1)
+            assert len(r) == 1
+
+        assert_almost_equal(lut(2, 2), np.asarray(3.))
+
+    def test_bilinearity(self):
+        x = [1,1,1,2,2,2,3,3,3]
+        y = [1,2,3,1,2,3,1,2,3]
+        z = [0,7,8,3,4,7,1,3,4]
+        s = 0.1
+        tx = [1+s,3-s]
+        ty = [1+s,3-s]
+        with suppress_warnings() as sup:
+            # This seems to fail (ier=1, see ticket 1642).
+            sup.filter(UserWarning, "\nThe coefficients of the spline")
+            lut = LSQBivariateSpline(x,y,z,tx,ty,kx=1,ky=1)
+
+        tx, ty = lut.get_knots()
+        for xa, xb in zip(tx[:-1], tx[1:]):
+            for ya, yb in zip(ty[:-1], ty[1:]):
+                for t in [0.1, 0.5, 0.9]:
+                    for s in [0.3, 0.4, 0.7]:
+                        xp = xa*(1-t) + xb*t
+                        yp = ya*(1-s) + yb*s
+                        zp = (+ lut(xa, ya)*(1-t)*(1-s)
+                              + lut(xb, ya)*t*(1-s)
+                              + lut(xa, yb)*(1-t)*s
+                              + lut(xb, yb)*t*s)
+                        assert_almost_equal(lut(xp,yp), zp)
+
+    @pytest.mark.thread_unsafe
+    def test_integral(self):
+        x = [1,1,1,2,2,2,8,8,8]
+        y = [1,2,3,1,2,3,1,2,3]
+        z = array([0,7,8,3,4,7,1,3,4])
+
+        s = 0.1
+        tx = [1+s,3-s]
+        ty = [1+s,3-s]
+        with suppress_warnings() as sup:
+            r = sup.record(UserWarning, "\nThe coefficients of the spline")
+            lut = LSQBivariateSpline(x, y, z, tx, ty, kx=1, ky=1)
+            assert len(r) == 1
+        tx, ty = lut.get_knots()
+        tz = lut(tx, ty)
+        trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:]
+                    * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum()
+
+        assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-1], ty[0], ty[-1])),
+                            np.asarray(trpz))
+
+    @pytest.mark.thread_unsafe
+    def test_empty_input(self):
+        # Test whether empty inputs returns an empty output. Ticket 1014
+        x = [1,1,1,2,2,2,3,3,3]
+        y = [1,2,3,1,2,3,1,2,3]
+        z = [3,3,3,3,3,3,3,3,3]
+        s = 0.1
+        tx = [1+s,3-s]
+        ty = [1+s,3-s]
+        with suppress_warnings() as sup:
+            r = sup.record(UserWarning, "\nThe coefficients of the spline")
+            lut = LSQBivariateSpline(x, y, z, tx, ty, kx=1, ky=1)
+            assert len(r) == 1
+
+        xp_assert_equal(lut([], []), np.zeros((0,0)))
+        xp_assert_equal(lut([], [], grid=False), np.zeros((0,)))
+
+    def test_invalid_input(self):
+        s = 0.1
+        tx = [1 + s, 3 - s]
+        ty = [1 + s, 3 - s]
+
+        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)
+            LSQBivariateSpline(x, y, z, tx, ty)
+        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)
+            LSQBivariateSpline(x, y, z, tx, ty, 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)
+            LSQBivariateSpline(x, y, z, tx, ty, w=w)
+        assert "w should be positive" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            bbox = (-100, 100, -100)
+            LSQBivariateSpline(x, y, z, tx, ty, bbox=bbox)
+        assert "bbox shape should be (4,)" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            LSQBivariateSpline(x, y, z, tx, ty, 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 exc_info:
+            LSQBivariateSpline(x, y, z, tx, ty, eps=0.0)
+        assert "eps should be between (0, 1)" in str(exc_info.value)
+
+        with assert_raises(ValueError) as exc_info:
+            LSQBivariateSpline(x, y, z, tx, ty, eps=1.0)
+        assert "eps should be between (0, 1)" in str(exc_info.value)
+
+    @pytest.mark.thread_unsafe
+    def test_array_like_input(self):
+        s = 0.1
+        tx = np.array([1 + s, 3 - s])
+        ty = np.array([1 + s, 3 - s])
+        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)
+        bbox = np.array([1.0, 10.0, 1.0, 10.0])
+
+        with suppress_warnings() as sup:
+            r = sup.record(UserWarning, "\nThe coefficients of the spline")
+            # np.array input
+            spl1 = LSQBivariateSpline(x, y, z, tx, ty, w=w, bbox=bbox)
+            # list input
+            spl2 = LSQBivariateSpline(x.tolist(), y.tolist(), z.tolist(),
+                                      tx.tolist(), ty.tolist(), w=w.tolist(),
+                                      bbox=bbox)
+            xp_assert_close(spl1(2.0, 2.0), spl2(2.0, 2.0))
+            assert len(r) == 2
+
+    @pytest.mark.thread_unsafe
+    def test_unequal_length_of_knots(self):
+        """Test for the case when the input knot-location arrays in x and y are
+        of different lengths.
+        """
+        x, y = np.mgrid[0:100, 0:100]
+        x = x.ravel()
+        y = y.ravel()
+        z = 3.0 * np.ones_like(x)
+        tx = np.linspace(0.1, 98.0, 29)
+        ty = np.linspace(0.1, 98.0, 33)
+        with suppress_warnings() as sup:
+            r = sup.record(UserWarning, "\nThe coefficients of the spline")
+            lut = LSQBivariateSpline(x,y,z,tx,ty)
+            assert len(r) == 1
+
+        assert_almost_equal(lut(x, y, grid=False), z)
+
+
+class TestSmoothBivariateSpline:
+    def test_linear_constant(self):
+        x = [1,1,1,2,2,2,3,3,3]
+        y = [1,2,3,1,2,3,1,2,3]
+        z = [3,3,3,3,3,3,3,3,3]
+        lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1)
+        for t in lut.get_knots():
+            assert_array_almost_equal(t, [1, 1, 3, 3])
+
+        assert_array_almost_equal(lut.get_coeffs(), [3, 3, 3, 3])
+        assert abs(lut.get_residual()) < 1e-15
+        assert_array_almost_equal(lut([1, 1.5, 2], [1, 1.5]), [[3, 3], [3, 3], [3, 3]])
+
+    def test_linear_1d(self):
+        x = [1,1,1,2,2,2,3,3,3]
+        y = [1,2,3,1,2,3,1,2,3]
+        z = [0,0,0,2,2,2,4,4,4]
+        lut = SmoothBivariateSpline(x,y,z,kx=1,ky=1)
+        for t in lut.get_knots():
+            xp_assert_close(t, np.asarray([1.0, 1, 3, 3]))
+        assert_array_almost_equal(lut.get_coeffs(), [0, 0, 4, 4])
+        assert abs(lut.get_residual()) < 1e-15
+        assert_array_almost_equal(lut([1,1.5,2],[1,1.5]),[[0,0],[1,1],[2,2]])
+
+    @pytest.mark.thread_unsafe
+    def test_integral(self):
+        x = [1,1,1,2,2,2,4,4,4]
+        y = [1,2,3,1,2,3,1,2,3]
+        z = array([0,7,8,3,4,7,1,3,4])
+
+        with suppress_warnings() as sup:
+            # This seems to fail (ier=1, see ticket 1642).
+            sup.filter(UserWarning, "\nThe required storage space")
+            lut = SmoothBivariateSpline(x, y, z, kx=1, ky=1, s=0)
+
+        tx = [1,2,4]
+        ty = [1,2,3]
+
+        tz = lut(tx, ty)
+        trpz = .25*(diff(tx)[:,None]*diff(ty)[None,:]
+                    * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum()
+        assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-1], ty[0], ty[-1])),
+                            np.asarray(trpz))
+
+        lut2 = SmoothBivariateSpline(x, y, z, kx=2, ky=2, s=0)
+        assert_almost_equal(np.asarray(lut2.integral(tx[0], tx[-1], ty[0], ty[-1])),
+                            np.asarray(trpz),
+                            decimal=0)  # the quadratures give 23.75 and 23.85
+
+        tz = lut(tx[:-1], ty[:-1])
+        trpz = .25*(diff(tx[:-1])[:,None]*diff(ty[:-1])[None,:]
+                    * (tz[:-1,:-1]+tz[1:,:-1]+tz[:-1,1:]+tz[1:,1:])).sum()
+        assert_almost_equal(np.asarray(lut.integral(tx[0], tx[-2], ty[0], ty[-2])),
+                            np.asarray(trpz))
+
+    def test_rerun_lwrk2_too_small(self):
+        # in this setting, lwrk2 is too small in the default run. Here we
+        # check for equality with the bisplrep/bisplev output because there,
+        # an automatic re-run of the spline representation is done if ier>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))
+
+
+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:
+    def test_defaults(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]])
+        lut = RectBivariateSpline(x,y,z)
+        assert_array_almost_equal(lut(x,y),z)
+
+    def test_evaluate(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]])
+        lut = RectBivariateSpline(x,y,z)
+
+        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)
+
+    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)
+        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)
+
+    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)
+
+    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)
+        assert_array_almost_equal(lut.partial_derivative(1, 0)(x, y), dx)
+        assert_array_almost_equal(lut.partial_derivative(0, 1)(x, y), dy)
+        assert_array_almost_equal(lut.partial_derivative(1, 1)(x, y), dxdy)
+
+    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]])
+        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.partial_derivative(1, 0)(x, y,
+                                                               grid=False),
+                                  dx)
+        assert_array_almost_equal(lut.partial_derivative(0, 1)(x, y,
+                                                               grid=False),
+                                  dy)
+        assert_array_almost_equal(lut.partial_derivative(1, 1)(x, y,
+                                                               grid=False),
+                                  dxdy)
+
+    def test_partial_derivative_order_too_large(self):
+        x = array([0, 1, 2, 3, 4], dtype=float)
+        y = x.copy()
+        z = ones((x.size, y.size))
+        lut = RectBivariateSpline(x, y, z)
+        with assert_raises(ValueError):
+            lut.partial_derivative(4, 1)
+
+    def test_broadcast(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]])
+        lut = RectBivariateSpline(x,y,z)
+        xp_assert_close(lut(x, y), lut(x[:,None], y[None,:], grid=False))
+
+    def test_invalid_input(self):
+
+        with assert_raises(ValueError) as info:
+            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]])
+            RectBivariateSpline(x, y, z)
+        assert "x must be strictly increasing" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            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]])
+            RectBivariateSpline(x, y, z)
+        assert "y must be strictly increasing" in str(info.value)
+
+        with assert_raises(ValueError) as info:
+            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]])
+            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:
+            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]])
+            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:
+            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)
+            RectBivariateSpline(x, y, z, bbox=bbox)
+        assert "bbox shape should be (4,)" in str(info.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)
+
+    def test_array_like_input(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]])
+        bbox = array([1, 5, 1, 5])
+
+        spl1 = RectBivariateSpline(x, y, z, bbox=bbox)
+        spl2 = RectBivariateSpline(x.tolist(), y.tolist(), z.tolist(),
+                                   bbox=bbox.tolist())
+        assert_array_almost_equal(spl1(1.0, 1.0), spl2(1.0, 1.0))
+
+    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)
+
+
+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 suppress_warnings() as sup:
+            sup.record(UserWarning, "\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)
+        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
+
+    def test_invalid_attribute_fp(self):
+        der = self.lut_rect.partial_derivative(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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py
new file mode 100644
index 0000000000000000000000000000000000000000..48197062e0b83a9ef54e45089d9089d49b8ad367
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py
@@ -0,0 +1,64 @@
+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)
+
+        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',
+        ]
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py
new file mode 100644
index 0000000000000000000000000000000000000000..981cd99d9d56e11e8d8ce0635e7b7240c19eef1f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py
@@ -0,0 +1,440 @@
+import os
+import sys
+
+import numpy as np
+from numpy.testing import suppress_warnings
+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.thread_unsafe
+    @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="item %d" % 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 suppress_warnings() as sup:
+            sup.filter(interpnd.GradientEstimationWarning,
+                       "Gradient estimation did not converge")
+            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="Function %d" % j)
+            self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
+                                 alternate=True,
+                                 err_msg="Function (alternate) %d" % j)
+            # check rescaling
+            self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
+                                 err_msg="Function (rescaled) %d" % j, rescale=True)
+            self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
+                                 alternate=True, rescale=True,
+                                 err_msg="Function (alternate, rescaled) %d" % 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="Function %d" % j)
+            self._check_accuracy(func, tol=1e-9, atol=0.22, rtol=0,
+                                 err_msg="Function %d" % 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="Function %d" % j)
+            self._check_accuracy(func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2,
+                                 err_msg="Function %d" % 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)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..24a6907b7b050ddb0686cf8b1761bfd50eaf692a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py
@@ -0,0 +1,2586 @@
+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 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)
+
+from scipy.special import poch, gamma
+
+from scipy.interpolate import _ppoly
+
+from scipy._lib._gcutils import assert_deallocated, IS_PYPY
+from scipy._lib._testutils import _run_concurrent_barrier
+
+from scipy.integrate import nquad
+
+from scipy.special import binom
+
+
+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_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)
+
+    @pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+    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)
+        pl = lagrange(xs,ys)
+        assert_array_almost_equal(p.coeffs,pl.coeffs)
+
+
+class TestAkima1DInterpolator:
+    def test_eval(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)
+        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.array([0., 1.375, 2., 1.5, 1.953125, 2.484375,
+            4.1363636363636366866103344, 5.9803623910336236590978842,
+            5.5067291516462386624652936, 5.2031367459745245795943447,
+            4.1796554159017080820603951, 3.4110386597938129327189927,
+            3.])
+        xp_assert_close(ak(xi), yi)
+
+    def test_eval_mod(self):
+        # 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 = 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, method="makima")
+        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.array([
+            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])
+        xp_assert_close(ak(xi), yi)
+
+    def test_eval_2d(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.column_stack((y, 2. * 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.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 = np.column_stack((yi, 2. * yi))
+        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_degenerate_case_multidimensional(self):
+        # This test is for issue #5683.
+        x = np.array([0, 1, 2])
+        y = np.vstack((x, x**2)).T
+        ak = Akima1DInterpolator(x, y)
+        x_eval = np.array([0.5, 1.5])
+        y_eval = ak(x_eval)
+        xp_assert_close(y_eval, np.vstack((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)
+
+
+@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)
+
+
+class TestPPolyCommon:
+    # test basic functionality for PPoly and BPoly
+    def test_sort_check(self):
+        c = np.array([[1, 4], [2, 5], [3, 6]])
+        x = np.array([0, 1, 0.5])
+        assert_raises(ValueError, PPoly, c, x)
+        assert_raises(ValueError, BPoly, c, x)
+
+    def test_ctor_c(self):
+        # wrong shape: `c` must be at least 2D
+        with assert_raises(ValueError):
+            PPoly([1, 2], [0, 1])
+
+    def test_extend(self):
+        # 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
+
+        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):
+        # Test extending polynomial with different order one
+        np.random.seed(1234)
+
+        x = np.linspace(0, 1, 6)
+        c = np.random.rand(2, 5)
+
+        x2 = np.linspace(1, 2, 6)
+        c2 = 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 = np.linspace(0, 1, 300, endpoint=False)
+            xi2 = np.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):
+        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)
+
+        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):
+        np.random.seed(1234)
+        c = np.random.rand(8, 12, 5, 6, 7)
+        x = np.sort(np.random.rand(13))
+        xp = np.random.rand(3, 4)
+        for cls in (PPoly, BPoly):
+            p = cls(c, x)
+            assert p(xp).shape == (3, 4, 5, 6, 7)
+
+        # 'scalars'
+        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):
+        # 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))
+        xp = np.random.rand(3, 4)
+
+        for cls in (PPoly, BPoly):
+            interp = cls(c, x)
+
+            def worker_fn(_, interp, xp):
+                interp(xp)
+
+            _run_concurrent_barrier(10, worker_fn, interp, xp)
+
+
+    def test_complex_coef(self):
+        np.random.seed(12345)
+        x = np.sort(np.random.random(13))
+        c = np.random.random((8, 12)) * (1. + 0.3j)
+        c_re, c_im = c.real, c.imag
+        xp = 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(p(xp, nu).real, p_re(xp, nu))
+                xp_assert_close(p(xp, nu).imag, p_im(xp, nu))
+
+    def test_axis(self):
+        np.random.seed(12345)
+        c = np.random.rand(3, 4, 5, 6, 7, 8)
+        c_s = c.shape
+        xp = np.random.random((1, 2))
+        for axis in (0, 1, 2, 3):
+            m = c.shape[axis+1]
+            x = 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(xp)
+                targ_shape = c_s[:axis] + xp.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
+
+
+class TestPPoly:
+    def test_simple(self):
+        c = np.array([[1, 4], [2, 5], [3, 6]])
+        x = np.array([0, 0.5, 1])
+        p = PPoly(c, x)
+        xp_assert_close(p(0.3), np.asarray(1*0.3**2 + 2*0.3 + 3))
+        xp_assert_close(p(0.7), np.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6))
+
+    def test_periodic(self):
+        c = np.array([[1, 4], [2, 5], [3, 6]])
+        x = np.array([0, 0.5, 1])
+        p = PPoly(c, x, extrapolate='periodic')
+
+        xp_assert_close(p(1.3),
+                        np.asarray(1 * 0.3 ** 2 + 2 * 0.3 + 3))
+        xp_assert_close(p(-0.3),
+                        np.asarray(4 * (0.7 - 0.5) ** 2 + 5 * (0.7 - 0.5) + 6))
+
+        xp_assert_close(p(1.3, 1), np.asarray(2 * 0.3 + 2))
+        xp_assert_close(p(-0.3, 1), np.asarray(8 * (0.7 - 0.5) + 5))
+
+    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()
+
+    def test_descending(self):
+        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
+
+            pa = PPoly(ca, x, extrapolate=True)
+            pd = PPoly(cd[:, ::-1], x[::-1], extrapolate=True)
+
+            x_test = 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-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, np.sort(roots_d), rtol=1e-12)
+
+    def test_multi_shape(self):
+        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):
+        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(c, x)
+        xp_assert_close(p(0.3), np.asarray(1*0.3**2 + 2*0.3 + 3))
+        xp_assert_close(p(0.7), np.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6))
+
+    def test_vs_alternative_implementations(self):
+        rng = np.random.RandomState(1234)
+        c = rng.rand(3, 12, 22)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+
+        p = PPoly(c, x)
+
+        xp = np.r_[0.3, 0.5, 0.33, 0.6]
+        expected = _ppoly_eval_1(c, x, xp)
+        xp_assert_close(p(xp), expected)
+
+        expected = _ppoly_eval_2(c[:,:,0], x, xp)
+        xp_assert_close(p(xp)[:, 0], expected)
+
+    def test_from_spline(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0)
+        pp = PPoly.from_spline(spl)
+
+        xi = np.linspace(0, 1, 200)
+        xp_assert_close(pp(xi), splev(xi, spl))
+
+        # make sure .from_spline accepts BSpline objects
+        b = BSpline(*spl)
+        ppp = PPoly.from_spline(b)
+        xp_assert_close(ppp(xi), b(xi))
+
+        # BSpline's extrapolate attribute propagates unless overridden
+        t, c, k = spl
+        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_derivative_simple(self):
+        np.random.seed(1234)
+        c = np.array([[4, 3, 2, 1]]).T
+        dc = np.array([[3*4, 2*3, 2]]).T
+        ddc = np.array([[2*3*4, 1*2*3]]).T
+        x = np.array([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):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0)
+        pp = PPoly.from_spline(spl)
+
+        xi = np.linspace(0, 1, 200)
+        for dx in range(0, 3):
+            xp_assert_close(pp(xi, dx), splev(xi, spl, dx))
+
+    def test_derivative(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0, k=5)
+        pp = PPoly.from_spline(spl)
+
+        xi = np.linspace(0, 1, 200)
+        for dx in range(0, 10):
+            xp_assert_close(pp(xi, dx), pp.derivative(dx)(xi),
+                            err_msg="dx=%d" % (dx,))
+
+    def test_antiderivative_of_constant(self):
+        # https://github.com/scipy/scipy/issues/4216
+        p = PPoly([[1.]], [0, 1])
+        xp_assert_equal(p.antiderivative().c, PPoly([[1], [0]], [0, 1]).c)
+        xp_assert_equal(p.antiderivative().x, PPoly([[1], [0]], [0, 1]).x)
+
+    def test_antiderivative_regression_4355(self):
+        # https://github.com/scipy/scipy/issues/4355
+        p = PPoly([[1., 0.5]], [0, 1, 2])
+        q = p.antiderivative()
+        xp_assert_equal(q.c, [[1, 0.5], [0, 1]])
+        xp_assert_equal(q.x, [0.0, 1, 2])
+        xp_assert_close(p.integrate(0, 2), np.asarray(1.5))
+        xp_assert_close(np.asarray(q(2) - q(0)),
+                        np.asarray(1.5))
+
+    def test_antiderivative_simple(self):
+        np.random.seed(1234)
+        # [ p1(x) = 3*x**2 + 2*x + 1,
+        #   p2(x) = 1.6875]
+        c = np.array([[3, 2, 1], [0, 0, 1.6875]]).T
+        # [ pp1(x) = x**3 + x**2 + x,
+        #   pp2(x) = 1.6875*(x - 0.25) + pp1(0.25)]
+        ic = np.array([[1, 1, 1, 0], [0, 0, 1.6875, 0.328125]]).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 = np.array([[1/4, 1/3, 1/2, 0, 0],
+                        [0, 0, 1.6875/2, 0.328125, 0.037434895833333336]]).T
+        x = np.array([0, 0.25, 1])
+
+        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):
+        rng = np.random.RandomState(1234)
+        x = np.linspace(0, 1, 30)**2
+        y = rng.rand(len(x))
+        spl = splrep(x, y, s=0, k=5)
+        pp = PPoly.from_spline(spl)
+
+        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="dx=%d k=%d" % (dx, k))
+
+    def test_antiderivative_vs_spline(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0, k=5)
+        pp = PPoly.from_spline(spl)
+
+        for dx in range(0, 10):
+            pp2 = pp.antiderivative(dx)
+            spl2 = splantider(spl, dx)
+
+            xi = np.linspace(0, 1, 200)
+            xp_assert_close(pp2(xi), splev(xi, spl2),
+                            rtol=1e-7)
+
+    def test_antiderivative_continuity(self):
+        c = np.array([[2, 1, 2, 2], [2, 1, 3, 3]]).T
+        x = np.array([0, 0.5, 1])
+
+        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):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0, k=5)
+        pp = PPoly.from_spline(spl)
+
+        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, splint(a, b, spl), 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 np.isnan(pp.integrate(a, b, extrapolate=False)).all()
+
+    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):
+        x = np.array([1, 2, 4])
+        c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]])
+
+        P = PPoly(c, x, extrapolate='periodic')
+        I = P.antiderivative()
+
+        period_int = np.asarray(I(4) - I(1))
+
+        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), np.asarray(2 * period_int))
+
+        xp_assert_close(P.integrate(1.5, 2.5),
+                        np.asarray(I(2.5) - I(1.5)))
+        xp_assert_close(P.integrate(3.5, 5),
+                        np.asarray(I(2) - I(1) + I(4) - I(3.5)))
+        xp_assert_close(P.integrate(3.5 + 12, 5 + 12),
+                        np.asarray(I(2) - I(1) + I(4) - I(3.5)))
+        xp_assert_close(P.integrate(3.5, 5 + 12),
+                        np.asarray(I(2) - I(1) + I(4) - I(3.5) + 4 * period_int))
+        xp_assert_close(P.integrate(0, -1),
+                        np.asarray(I(2) - I(3)))
+        xp_assert_close(P.integrate(-9, -10),
+                        np.asarray(I(2) - I(3)))
+        xp_assert_close(P.integrate(0, -10),
+                        np.asarray(I(2) - I(3) - 3 * period_int))
+
+    def test_roots(self):
+        x = np.linspace(0, 1, 31)**2
+        y = np.sin(30*x)
+
+        spl = splrep(x, y, s=0, k=3)
+        pp = PPoly.from_spline(spl)
+
+        r = pp.roots()
+        r = r[(r >= 0 - 1e-15) & (r <= 1 + 1e-15)]
+        xp_assert_close(r, sproot(spl), atol=1e-15)
+
+    def test_roots_idzero(self):
+        # Roots for piecewise polynomials with identically zero
+        # sections.
+        c = np.array([[-1, 0.25], [0, 0], [-1, 0.25]]).T
+        x = np.array([0, 0.4, 0.6, 1.0])
+
+        pp = PPoly(c, x)
+        xp_assert_equal(pp.roots(),
+                        [0.25, 0.4, np.nan, 0.6 + 0.25])
+
+        # ditto for p.solve(const) with sections identically equal const
+        const = 2.
+        c1 = c.copy()
+        c1[1, :] += const
+        pp1 = PPoly(c1, x)
+
+        xp_assert_equal(pp1.solve(const),
+                        [0.25, 0.4, np.nan, 0.6 + 0.25])
+
+    def test_roots_all_zero(self):
+        # test the code path for the polynomial being identically zero everywhere
+        c = [[0], [0]]
+        x = [0, 1]
+        p = PPoly(c, x)
+        xp_assert_equal(p.roots(), [0, np.nan])
+        xp_assert_equal(p.solve(0), [0, np.nan])
+        xp_assert_equal(p.solve(1), [])
+
+        c = [[0, 0], [0, 0]]
+        x = [0, 1, 2]
+        p = PPoly(c, x)
+        xp_assert_equal(p.roots(), [0, np.nan, 1, np.nan])
+        xp_assert_equal(p.solve(0), [0, np.nan, 1, np.nan])
+        xp_assert_equal(p.solve(1), [])
+
+    def test_roots_repeated(self):
+        # Check roots repeated in multiple sections are reported only
+        # once.
+
+        # [(x + 1)**2 - 1, -x**2] ; x == 0 is a repeated root
+        c = np.array([[1, 0, -1], [-1, 0, 0]]).T
+        x = np.array([-1, 0, 1])
+
+        pp = PPoly(c, x)
+        xp_assert_equal(pp.roots(), np.asarray([-2.0, 0.0]))
+        xp_assert_equal(pp.roots(extrapolate=False), np.asarray([0.0]))
+
+    def test_roots_discont(self):
+        # Check that a discontinuity across zero is reported as root
+        c = np.array([[1], [-1]]).T
+        x = np.array([0, 0.5, 1])
+        pp = PPoly(c, x)
+        xp_assert_equal(pp.roots(), np.asarray([0.5]))
+        xp_assert_equal(pp.roots(discontinuity=False), np.asarray([]))
+
+        # ditto for a discontinuity across y:
+        xp_assert_equal(pp.solve(0.5), np.asarray([0.5]))
+        xp_assert_equal(pp.solve(0.5, discontinuity=False), np.asarray([]))
+
+        xp_assert_equal(pp.solve(1.5), np.asarray([]))
+        xp_assert_equal(pp.solve(1.5, discontinuity=False), np.asarray([]))
+
+    def test_roots_random(self):
+        # 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.unique(np.r_[0, 10 * rng.rand(30), 10])
+                c = 2*rng.rand(order+1, len(x)-1, 2, 3) - 1
+
+                pp = PPoly(c, x)
+                for y in [0, 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):
+        # [ 1 - x**2 ]
+        c = np.array([[-1, 0, 1]]).T
+        x = np.array([0, 1])
+
+        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 np.isnan(pp([-0.1, 1.1])).all()
+                assert np.isnan(pp_i([-0.1, 1.1])).all()
+                assert np.isnan(pp_d([-0.1, 1.1])).all()
+                assert pp.roots() == [1]
+            else:
+                xp_assert_close(pp([-0.1, 1.1]), [1-0.1**2, 1-1.1**2])
+                assert not np.isnan(pp_i([-0.1, 1.1])).any()
+                assert not np.isnan(pp_d([-0.1, 1.1])).any()
+                xp_assert_close(pp.roots(), np.asarray([1.0, -1.0]))
+
+
+class TestBPoly:
+    def test_simple(self):
+        x = [0, 1]
+        c = [[3]]
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.1), np.asarray(3.))
+
+    def test_simple2(self):
+        x = [0, 1]
+        c = [[3], [1]]
+        bp = BPoly(c, x)   # 3*(1-x) + 1*x
+        xp_assert_close(bp(0.1), np.asarray(3*0.9 + 1.*0.1))
+
+    def test_simple3(self):
+        x = [0, 1]
+        c = [[3], [1], [4]]
+        bp = BPoly(c, x)   # 3 * (1-x)**2 + 2 * x (1-x) + 4 * x**2
+        xp_assert_close(bp(0.2),
+                np.asarray(3 * 0.8*0.8 + 1 * 2*0.2*0.8 + 4 * 0.2*0.2))
+
+    def test_simple4(self):
+        x = [0, 1]
+        c = [[1], [1], [1], [2]]
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.3),
+                        np.asarray(    0.7**3 +
+                                   3 * 0.7**2 * 0.3 +
+                                   3 * 0.7 * 0.3**2 +
+                                   2 * 0.3**3)
+        )
+
+    def test_simple5(self):
+        x = [0, 1]
+        c = [[1], [1], [8], [2], [1]]
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.3),
+                        np.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)
+        )
+
+    def test_periodic(self):
+        x = [0, 1, 3]
+        c = [[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), np.asarray(3 * 0.6**2))
+        xp_assert_close(bp(-1.3), np.asarray(2 * (0.7/2)**2))
+
+        xp_assert_close(bp(3.4, 1), np.asarray(-6 * 0.6))
+        xp_assert_close(bp(-1.3, 1), np.asarray(2 * (0.7/2)))
+
+    def test_descending(self):
+        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(-0.1, 0.1, size=(power + 1, m))
+            # We need only to flip coefficients to get it right!
+            cd = ca[::-1].copy()
+
+            pa = BPoly(ca, x, extrapolate=True)
+            pd = BPoly(cd[:, ::-1], x[::-1], extrapolate=True)
+
+            x_test = 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):
+        rng = np.random.RandomState(1234)
+        c = rng.rand(6, 2, 1, 2, 3)
+        x = np.array([0, 0.5, 1])
+        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):
+        x = [0, 2]
+        c = [[3], [1], [4]]
+        bp = BPoly(c, x)
+        xval = 0.1
+        s = xval / 2  # s = (x - xa) / (xb - xa)
+        xp_assert_close(bp(xval),
+                        np.asarray(3 * (1-s)*(1-s) + 1 * 2*s*(1-s) + 4 * s*s)
+        )
+
+    def test_two_intervals(self):
+        x = [0, 1, 3]
+        c = [[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), np.asarray(3 * 0.6*0.6))
+        xp_assert_close(bp(1.7), np.asarray(2 * (0.7/2)**2))
+
+    def test_extrapolate_attr(self):
+        x = [0, 2]
+        c = [[3], [1], [4]]
+        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 np.isnan(bp([-0.1, 2.1])).all()
+                assert np.isnan(bp_d([-0.1, 2.1])).all()
+            else:
+                assert not np.isnan(bp([-0.1, 2.1])).any()
+                assert not np.isnan(bp_d([-0.1, 2.1])).any()
+
+
+class TestBPolyCalculus:
+    def test_derivative(self):
+        x = [0, 1, 3]
+        c = [[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), np.asarray(-6*(0.6)))
+        xp_assert_close(bp_der(1.7), np.asarray(0.7))
+
+        # derivatives in-place
+        xp_assert_close(np.asarray([bp(0.4, nu) for nu in [1, 2, 3]]),
+                        np.asarray([-6*(1-0.4), 6., 0.])
+        )
+        xp_assert_close(np.asarray([bp(1.7, nu) for nu in [1, 2, 3]]),
+                        np.asarray([0.7, 1., 0])
+        )
+
+    def test_derivative_ppoly(self):
+        # 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))
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+
+        for d in range(k):
+            bp = bp.derivative()
+            pp = pp.derivative()
+            xp = np.linspace(x[0], x[-1], 21)
+            xp_assert_close(bp(xp), pp(xp))
+
+    def test_deriv_inplace(self):
+        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))
+
+        # test both real and complex coefficients
+        for cc in [c.copy(), c*(1. + 2.j)]:
+            bp = BPoly(cc, x)
+            xp = np.linspace(x[0], x[-1], 21)
+            for i in range(k):
+                xp_assert_close(bp(xp, i), bp.derivative(i)(xp))
+
+    def test_antiderivative_simple(self):
+        # 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 = [0, 1, 3]
+        c = [[0, 0], [1, 1]]
+
+        bp = BPoly(c, x)
+        bi = bp.antiderivative()
+
+        xx = np.linspace(0, 3, 11)
+        xp_assert_close(bi(xx),
+                        np.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):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10, 2, 3))
+        bp = BPoly(c, x)
+
+        xx = np.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):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10))
+        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):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10))
+        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):
+        c = [[1]]
+        x = [0, 1]
+        b = BPoly(c, x)
+
+        # default is extrapolate=True
+        xp_assert_close(b.integrate(0, 2), np.asarray(2.),
+                        atol=1e-14, check_0d=False)
+
+        # .integrate argument overrides self.extrapolate
+        b1 = BPoly(c, x, extrapolate=False)
+        assert np.isnan(b1.integrate(0, 2))
+        xp_assert_close(b1.integrate(0, 2, extrapolate=True),
+                        np.asarray(2.), atol=1e-14, check_0d=False)
+
+    def test_integrate_periodic(self):
+        x = np.array([1, 2, 4])
+        c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]])
+
+        P = BPoly.from_power_basis(PPoly(c, x), extrapolate='periodic')
+        I = P.antiderivative()
+
+        period_int = 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), 2 * period_int)
+
+        xp_assert_close(P.integrate(1.5, 2.5), I(2.5) - I(1.5))
+        xp_assert_close(P.integrate(3.5, 5), I(2) - I(1) + I(4) - I(3.5))
+        xp_assert_close(P.integrate(3.5 + 12, 5 + 12),
+                        I(2) - I(1) + I(4) - I(3.5))
+        xp_assert_close(P.integrate(3.5, 5 + 12),
+                        I(2) - I(1) + I(4) - I(3.5) + 4 * period_int)
+
+        xp_assert_close(P.integrate(0, -1), I(2) - I(3))
+        xp_assert_close(P.integrate(-9, -10), I(2) - I(3))
+        xp_assert_close(P.integrate(0, -10), I(2) - I(3) - 3 * period_int)
+
+    def test_antider_neg(self):
+        # .derivative(-nu) ==> .andiderivative(nu) and vice versa
+        c = [[1]]
+        x = [0, 1]
+        b = BPoly(c, x)
+
+        xx = np.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)
+
+
+class TestPolyConversions:
+    def test_bp_from_pp(self):
+        x = [0, 1, 3]
+        c = [[3, 2], [1, 8], [4, 3]]
+        pp = PPoly(c, x)
+        bp = BPoly.from_power_basis(pp)
+        pp1 = PPoly.from_bernstein_basis(bp)
+
+        xp = [0.1, 1.4]
+        xp_assert_close(pp(xp), bp(xp))
+        xp_assert_close(pp(xp), pp1(xp))
+
+    def test_bp_from_pp_random(self):
+        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))
+        pp = PPoly(c, x)
+        bp = BPoly.from_power_basis(pp)
+        pp1 = PPoly.from_bernstein_basis(bp)
+
+        xp = np.linspace(x[0], x[-1], 21)
+        xp_assert_close(pp(xp), bp(xp))
+        xp_assert_close(pp(xp), pp1(xp))
+
+    def test_pp_from_bp(self):
+        x = [0, 1, 3]
+        c = [[3, 3], [1, 1], [4, 2]]
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+        bp1 = BPoly.from_power_basis(pp)
+
+        xp = [0.1, 1.4]
+        xp_assert_close(bp(xp), pp(xp))
+        xp_assert_close(bp(xp), bp1(xp))
+
+    def test_broken_conversions(self):
+        # regression test for gh-10597: from_power_basis only accepts PPoly etc.
+        x = [0, 1, 3]
+        c = [[3, 3], [1, 1], [4, 2]]
+        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)
+
+
+class TestBPolyFromDerivatives:
+    def test_make_poly_1(self):
+        c1 = BPoly._construct_from_derivatives(0, 1, [2], [3])
+        xp_assert_close(c1, [2., 3.])
+
+    def test_make_poly_2(self):
+        c1 = BPoly._construct_from_derivatives(0, 1, [1, 0], [1])
+        xp_assert_close(c1, [1., 1., 1.])
+
+        # f'(0) = 3
+        c2 = BPoly._construct_from_derivatives(0, 1, [2, 3], [1])
+        xp_assert_close(c2, [2., 7./2, 1.])
+
+        # f'(1) = 3
+        c3 = BPoly._construct_from_derivatives(0, 1, [2], [1, 3])
+        xp_assert_close(c3, [2., -0.5, 1.])
+
+    def test_make_poly_3(self):
+        # f'(0)=2, f''(0)=3
+        c1 = BPoly._construct_from_derivatives(0, 1, [1, 2, 3], [4])
+        xp_assert_close(c1, [1., 5./3, 17./6, 4.])
+
+        # f'(1)=2, f''(1)=3
+        c2 = BPoly._construct_from_derivatives(0, 1, [1], [4, 2, 3])
+        xp_assert_close(c2, [1., 19./6, 10./3, 4.])
+
+        # f'(0)=2, f'(1)=3
+        c3 = BPoly._construct_from_derivatives(0, 1, [1, 2], [4, 3])
+        xp_assert_close(c3, [1., 5./3, 3., 4.])
+
+    def test_make_poly_12(self):
+        rng = np.random.RandomState(12345)
+        ya = np.r_[0, rng.random(5)]
+        yb = np.r_[0, rng.random(5)]
+
+        c = BPoly._construct_from_derivatives(0, 1, ya, yb)
+        pp = BPoly(c[:, None], [0, 1])
+        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):
+        rng = np.random.RandomState(12345)
+        x = [0, 1]
+        k, d = 8, 5
+        c = rng.random((k, 1, 2, 3, 4))
+        bp = BPoly(c, x)
+
+        c1 = BPoly._raise_degree(c, d)
+        bp1 = BPoly(c1, x)
+
+        xp = np.linspace(0, 1, 11)
+        xp_assert_close(bp(xp), bp1(xp))
+
+    def test_xi_yi(self):
+        assert_raises(ValueError, BPoly.from_derivatives, [0, 1], [0])
+
+    def test_coords_order(self):
+        xi = [0, 0, 1]
+        yi = [[0], [0], [0]]
+        assert_raises(ValueError, BPoly.from_derivatives, xi, yi)
+
+    def test_zeros(self):
+        xi = [0, 1, 2, 3]
+        yi = [[0, 0], [0], [0, 0], [0, 0]]  # NB: will have to raise the degree
+        pp = BPoly.from_derivatives(xi, yi)
+        assert pp.c.shape == (4, 3)
+
+        ppd = pp.derivative()
+        for xp in [0., 0.1, 1., 1.1, 1.9, 2., 2.5]:
+            xp_assert_close(pp(xp), np.asarray(0.0))
+            xp_assert_close(ppd(xp), np.asarray(0.0))
+
+
+    def _make_random_mk(self, m, k):
+        # k derivatives at each breakpoint
+        rng = np.random.RandomState(1234)
+        xi = np.asarray([1. * j**2 for j in range(m+1)])
+        yi = [rng.random(k) for j in range(m+1)]
+        return xi, yi
+
+    def test_random_12(self):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k)
+        pp = BPoly.from_derivatives(xi, yi)
+
+        for order in range(k//2):
+            xp_assert_close(pp(xi), [yy[order] for yy in yi])
+            pp = pp.derivative()
+
+    def test_order_zero(self):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k)
+        assert_raises(ValueError, BPoly.from_derivatives,
+                **dict(xi=xi, yi=yi, orders=0))
+
+    def test_orders_too_high(self):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k)
+
+        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):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k)
+
+        # 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 np.allclose(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 np.allclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12))
+
+    def test_orders_local(self):
+        m, k = 7, 12
+        xi, yi = self._make_random_mk(m, k)
+
+        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 np.allclose(pp(x - 1e-12), pp(x + 1e-12))
+
+    def test_yi_trailing_dims(self):
+        rng = np.random.RandomState(1234)
+        m, k = 7, 5
+        xi = np.sort(rng.random(m+1))
+        yi = 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)))
+
+    @pytest.mark.thread_unsafe
+    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.shape = 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
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..047a940b3efcb24ec85a94a87dd1050baa01f165
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py
@@ -0,0 +1,308 @@
+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")
+
+    @pytest.mark.thread_unsafe
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py
new file mode 100644
index 0000000000000000000000000000000000000000..119b7d1c5667368b284fbf6458174ea14e71957a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py
@@ -0,0 +1,107 @@
+import numpy as np
+from scipy.interpolate import pade
+from scipy._lib._array_api import (
+    xp_assert_equal, assert_array_almost_equal
+)
+
+def test_pade_trivial():
+    nump, denomp = pade([1.0], 0)
+    xp_assert_equal(nump.c, np.asarray([1.0]))
+    xp_assert_equal(denomp.c, np.asarray([1.0]))
+
+    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]))
+
+
+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])
+
+
+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)
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3e6cb7894ea344289c12b522b45c5e0f22748e6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py
@@ -0,0 +1,972 @@
+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
+)
+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
+
+
+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)
+
+    @pytest.mark.thread_unsafe
+    def test_high_degree_warning(self):
+        with pytest.warns(UserWarning, match="40 degrees provided,"):
+            KroghInterpolator(np.arange(40), np.ones(40))
+
+    @pytest.mark.thread_unsafe
+    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
+        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())
+
+    @pytest.mark.thread_unsafe
+    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)
+
+    @pytest.mark.thread_unsafe
+    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
+
+    @pytest.mark.thread_unsafe
+    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]))
+
+
+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):
+        x = np.linspace(0, 2 * np.pi, 10)
+        y = np.cos(x)
+        S = CubicSpline(x, y, bc_type='periodic')
+        assert_almost_equal(S(1), S(1 + 2 * np.pi), 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)
+
+
+def test_CubicHermiteSpline_correctness():
+    x = [0, 2, 7]
+    y = [-1, 2, 3]
+    dydx = [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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbf.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..d824a84a80eda316b680ba4e43d0f418c774af99
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbf.py
@@ -0,0 +1,246 @@
+# 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
+
+import pytest
+
+
+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.shape = 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.shape = 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.shape = 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.shape = 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
+
+
+@pytest.mark.thread_unsafe
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d2759fdee41fa64c09bb00979f10b70e49a2855
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py
@@ -0,0 +1,534 @@
+import pickle
+import pytest
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy._lib._array_api import xp_assert_close
+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, _monomial_powers,
+    RBFInterpolator
+    )
+from scipy.interpolate import _rbfinterp_pythran
+from scipy._lib._testutils import _run_concurrent_barrier
+
+
+def _vandermonde(x, degree):
+    # Returns a matrix of monomials that span polynomials with the specified
+    # degree evaluated at x.
+    powers = _monomial_powers(x.shape[1], degree)
+    return _rbfinterp_pythran._polynomial_matrix(x, powers)
+
+
+def _1d_test_function(x):
+    # 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*(np.exp(-x) - 4*np.exp(-2*x) + 3*np.exp(-3*x))
+    return y
+
+
+def _2d_test_function(x):
+    # Franke's test function.
+    # domain ~= (0, 1) X (0, 1), range ~= (0.0, 1.2)
+    x1, x2 = x[:, 0], x[:, 1]
+    term1 = 0.75 * np.exp(-(9*x1-2)**2/4 - (9*x2-2)**2/4)
+    term2 = 0.75 * np.exp(-(9*x1+1)**2/49 - (9*x2+1)/10)
+    term3 = 0.5 * np.exp(-(9*x1-7)**2/4 - (9*x2-3)**2/4)
+    term4 = -0.2 * np.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):
+        # 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)
+        y = _1d_test_function(x)
+        xitp = 3*seq.random(50)
+        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):
+        # 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)
+        y = _2d_test_function(x)
+        xitp = seq.random(100)
+        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):
+        # 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)
+        y = _2d_test_function(x)
+        xitp = seq.random(100)
+
+        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):
+        # 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)
+
+        P = _vandermonde(x, degree)
+        Pitp = _vandermonde(xitp, degree)
+
+        poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
+
+        y = P.dot(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):
+        # 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)
+
+        P = _vandermonde(x, degree)
+        Pitp = _vandermonde(xitp, degree)
+
+        poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
+
+        y = P.dot(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):
+        # 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)
+
+        y = np.array([_2d_test_function(x),
+                      _2d_test_function(x[:, ::-1])]).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):
+        # 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) + 1j*_2d_test_function(x[:, ::-1])
+
+        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):
+        # 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)
+
+        y = _1d_test_function(x)
+        ytrue = _1d_test_function(xitp)
+        yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
+
+        mse = np.mean((yitp - ytrue)**2)
+        assert mse < 1.0e-4
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_interpolation_misfit_2d(self, kernel):
+        # 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)
+
+        y = _2d_test_function(x)
+        ytrue = _2d_test_function(xitp)
+        yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
+
+        mse = np.mean((yitp - ytrue)**2)
+        assert mse < 2.0e-4
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_smoothing_misfit(self, kernel):
+        # 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**np.linspace(-4, 1, 20)
+
+        x = 3*seq.random(100)
+        y = _1d_test_function(x) + rng.normal(0.0, noise, (100,))
+        ytrue = _1d_test_function(x)
+        rmse_within_tol = False
+        for smoothing in smoothing_range:
+            ysmooth = self.build(
+                x, y,
+                epsilon=1.0,
+                smoothing=smoothing,
+                kernel=kernel)(x)
+            rmse = np.sqrt(np.mean((ysmooth - ytrue)**2))
+            if rmse < rmse_tol:
+                rmse_within_tol = True
+                break
+
+        assert rmse_within_tol
+
+    def test_array_smoothing(self):
+        # 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.dot(poly_coeffs)
+        y_with_outlier = np.copy(y)
+        y_with_outlier[10] += 1.0
+        smoothing = np.zeros((50,))
+        smoothing[10] = 1000.0
+        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)
+        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')
+
+    @pytest.mark.thread_unsafe
+    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)
+
+    def test_rank_error(self):
+        # An error should be raised when `kernel` is "thin_plate_spline" and
+        # observations are 2-D and collinear.
+        y = np.array([[2.0, 0.0], [1.0, 0.0], [0.0, 0.0]])
+        d = np.array([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):
+        # Make sure interpolation still works with only one point (in 1, 2, and
+        # 3 dimensions).
+        for dim in [1, 2, 3]:
+            y = np.zeros((1, dim))
+            d = np.ones((1,))
+            f = self.build(y, d, kernel='linear')(y)
+            xp_assert_close(d, f)
+
+    def test_pickleable(self):
+        # 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)
+
+        y = _1d_test_function(x)
+
+        interp = self.build(x, y)
+
+        yitp1 = interp(xitp)
+        yitp2 = pickle.loads(pickle.dumps(interp))(xitp)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-16)
+
+
+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)
+
+        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)
+
+        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)
+
+
+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)
+
+        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)
+
+        interp = self.build(x, y)
+
+        def worker_fn(_, interp, xp):
+            interp(xp)
+
+        _run_concurrent_barrier(10, worker_fn, interp, xitp)
+
+
+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)
+        yitp1 = self.build(x, y)(xitp)
+        yitp2 = RBFInterpolator(x, y)(xitp)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rgi.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..54c4f380ad7d51f54a5947cfc7764a60c1fc235e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rgi.py
@@ -0,0 +1,1150 @@
+import itertools
+
+import pytest
+import numpy as np
+
+from numpy.testing import assert_warns
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_array_almost_equal
+)
+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.sparse._sputils import matrix
+from scipy._lib._util import ComplexWarning
+from scipy._lib._testutils import _run_concurrent_barrier
+
+
+parametrize_rgi_interp_methods = pytest.mark.parametrize(
+    "method", RegularGridInterpolator._ALL_METHODS
+)
+
+class TestRegularGridInterpolator:
+    def _get_sample_4d(self):
+        # create a 4-D grid of 3 points in each dimension
+        points = [(0., .5, 1.)] * 4
+        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 _get_sample_4d_2(self):
+        # create another 4-D grid of 3 points in each dimension
+        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 _get_sample_4d_3(self):
+        # 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 = np.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):
+        # create another 4-D grid of 2 points in each dimension
+        points = [(0.0, 1.0)] * 4
+        values = np.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()
+
+        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):
+        points, values = self._get_sample_4d_4()
+        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 = np.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):
+        points, values = points_values(self)
+        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):
+        points, values = self._get_sample_4d()
+        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 ]])
+        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)),
+                        np.asarray([1.0, 1, 1]), atol=1e-15)
+        xp_assert_close(interp(sample, nu=(0, 1, 0, 0)),
+                        np.asarray([10.0, 10, 10]), atol=1e-15)
+
+        # 2nd derivatives of a linear function are zero
+        xp_assert_close(interp(sample, nu=(0, 1, 1, 0)),
+                        np.asarray([0.0, 0, 0]), atol=2e-12)
+
+    @parametrize_rgi_interp_methods
+    def test_complex(self, method):
+        if method == "pchip":
+            pytest.skip("pchip does not make sense for complex data")
+        points, values = self._get_sample_4d_3()
+        values = values - 2j*values
+        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, method=method)
+        rinterp = RegularGridInterpolator(points, values.real, method=method)
+        iinterp = RegularGridInterpolator(points, values.imag, method=method)
+
+        v1 = interp(sample)
+        v2 = rinterp(sample) + 1j*iinterp(sample)
+        xp_assert_close(v1, v2)
+
+    def test_cubic_vs_pchip(self):
+        x, y = [1, 2, 3, 4], [1, 2, 3, 4]
+        xg, yg = np.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)
+
+    def test_linear_xi1d(self):
+        points, values = self._get_sample_4d_2()
+        interp = RegularGridInterpolator(points, values)
+        sample = np.asarray([0.1, 0.1, 10., 9.])
+        wanted = np.asarray([1001.1])
+        assert_array_almost_equal(interp(sample), wanted)
+
+    def test_linear_xi3d(self):
+        points, values = self._get_sample_4d()
+        interp = RegularGridInterpolator(points, values)
+        sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+        wanted = np.asarray([1001.1, 846.2, 555.5])
+        assert_array_almost_equal(interp(sample), wanted)
+
+    @pytest.mark.parametrize(
+        "sample, wanted",
+        [
+            (np.asarray([0.1, 0.1, 0.9, 0.9]), 1100.0),
+            (np.asarray([0.1, 0.1, 0.1, 0.1]), 0.0),
+            (np.asarray([0.0, 0.0, 0.0, 0.0]), 0.0),
+            (np.asarray([1.0, 1.0, 1.0, 1.0]), 1111.0),
+            (np.asarray([0.1, 0.4, 0.6, 0.9]), 1055.0),
+        ],
+    )
+    def test_nearest(self, sample, wanted):
+        points, values = self._get_sample_4d()
+        interp = RegularGridInterpolator(points, values, method="nearest")
+        wanted = np.asarray([wanted])
+        assert_array_almost_equal(interp(sample), wanted)
+
+    def test_linear_edges(self):
+        points, values = self._get_sample_4d()
+        interp = RegularGridInterpolator(points, values)
+        sample = np.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.]])
+        wanted = np.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):
+        points, values = self._get_sample_4d()
+        interp = RegularGridInterpolator(points, values)
+        sample = np.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.]])
+        assert_raises(ValueError, interp, sample, "undefmethod")
+        sample = np.asarray([[0., 0., 0.], [1., 1., 1.]])
+        assert_raises(ValueError, interp, sample)
+        sample = np.asarray([[0., 0., 0., 0.], [1., 1., 1., 1.1]])
+        assert_raises(ValueError, interp, sample)
+
+    def test_out_of_bounds_extrap(self):
+        points, values = self._get_sample_4d()
+        interp = RegularGridInterpolator(points, values, bounds_error=False,
+                                         fill_value=None)
+        sample = np.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]])
+        wanted = np.asarray([0., 1111., 11., 11.])
+        assert_array_almost_equal(interp(sample, method="nearest"), wanted)
+        wanted = np.asarray([-111.1, 1222.1, -11068., -1186.9])
+        assert_array_almost_equal(interp(sample, method="linear"), wanted)
+
+    def test_out_of_bounds_extrap2(self):
+        points, values = self._get_sample_4d_2()
+        interp = RegularGridInterpolator(points, values, bounds_error=False,
+                                         fill_value=None)
+        sample = np.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]])
+        wanted = np.asarray([0., 11., 11., 11.])
+        assert_array_almost_equal(interp(sample, method="nearest"), wanted)
+        wanted = np.asarray([-12.1, 133.1, -1069., -97.9])
+        assert_array_almost_equal(interp(sample, method="linear"), wanted)
+
+    def test_out_of_bounds_fill(self):
+        points, values = self._get_sample_4d()
+        interp = RegularGridInterpolator(points, values, bounds_error=False,
+                                         fill_value=np.nan)
+        sample = np.asarray([[-.1, -.1, -.1, -.1], [1.1, 1.1, 1.1, 1.1],
+                             [2.1, 2.1, -1.1, -1.1]])
+        wanted = np.asarray([np.nan, np.nan, np.nan])
+        assert_array_almost_equal(interp(sample, method="nearest"), wanted)
+        assert_array_almost_equal(interp(sample, method="linear"), wanted)
+        sample = np.asarray([[0.1, 0.1, 1., .9], [0.2, 0.1, .45, .8],
+                             [0.5, 0.5, .5, .5]])
+        wanted = np.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()
+        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()
+        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.)
+
+    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}
+            )
+
+    @pytest.mark.thread_unsafe
+    def test_concurrency(self):
+        points, values = self._get_sample_4d()
+        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)
+
+        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]))
+
+    @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)
+
+        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)
+
+        # 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)
+
+    @pytest.mark.thread_unsafe
+    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')
+
+    @pytest.mark.thread_unsafe
+    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 assert_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', '`__
+   for more linear algebra functions. Note that
+   although `scipy.linalg` imports most of them, 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
+   kron - Kronecker product of two arrays
+   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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56a4bfaf55828a8c254f9149b8e145fb2c4dac6a
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf61221887bdcb76794aa692fa2b7d714c84b774
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6fac6d21b5ff0601654390a2d647043aaaedaa9
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c32e53007d8e4d59226f9b762dbb58d7fbff4e6a
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d24b1eb9257c68d6f91a179c58761543db3f04d1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d8c6dd406ba7fdf36cc96ca57b28becf30f3318
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ba6b733f1a7b196ae16f4d2abeda5031a0fb290
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fe71202f8b6fcc593a57e3f4e95660944a8883e
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9d08eeb62e4b0f8e37b1163278fee7481c90b36
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c5c2e34b98e930c2aa36a2b4756a02fe66ad4f3
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a86eb6540d02a070404e1e9338efeb787ef0ea4
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b32f9ad0e3b0b11aac3ca91612a2b268556e8ab1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff01013c0be1e3d5a74e2fa1c7eb2e2dfe92e7d1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..464e9b74c2c29c82606f5f86623368cdb91d4456
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5a5db74ea357dce8bb37721b55695668242bc80
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c06269e73add46cd253f4495c9cd8dd5dfa34141
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b53a08c77bc482db8a9ecdde927f9f1fb562bf0
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f2c222f9963312983a79bdb1b8ad5ca699df32d
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e8248aaf62e85ef92eebe93f18d84ef90d80de4
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e469bba88b56f39bc6bd1af6b5e8d8b2900a27f7
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7988ed474b2242d26d4bfcaebb3bea95fed8f342
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59ca4f605b44aa4557fdc91efe13fb9712d1075f
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d926499fef44eb4e496186ecc61ab605dd9403f7
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a665c04d4751d9d9c0d18132a2be956188bd6bbb
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae0b9a8d2d24032b7495f62875f2af8cc4ec4f97
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbb423b1ab7a154b479067f20313048d63176ece
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09b08c3344d0875ba038984bf8d57a87324c228b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45158f07ade7eef4418fab24c5bace4a5ccf186a
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f5732d779ec6b221cafc68099a16277883c7fa7
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6d77e595bdf6c30cd05f129f530448371981cbb
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8412147ca5c1a81586a57d8fa0f017b04d2cbb58
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d523d676381a07930d1bd34933d531cbe1f54fa
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13e08871e843e42805820a1a488c92b3fd24f6c1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..70841fa80976c62ed7d894d824fdfbbcb4673273
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_basic.py
@@ -0,0 +1,2119 @@
+#
+# Author: Pearu Peterson, March 2002
+#
+# w/ additions by Travis Oliphant, March 2002
+#              and Jake Vanderplas, August 2012
+
+import warnings
+from warnings import warn
+from itertools import product
+import numpy as np
+from numpy import atleast_1d, atleast_2d
+from .lapack import get_lapack_funcs, _compute_lwork
+from ._misc import LinAlgError, _datacopied, LinAlgWarning
+from ._decomp import _asarray_validated
+from . import _decomp, _decomp_svd
+from ._solve_toeplitz import levinson
+from ._cythonized_array_utils import (find_det_from_lu, bandwidth, issymmetric,
+                                      ishermitian)
+
+__all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
+           'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
+           'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz']
+
+
+# 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]"
+lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
+                    for x in np.typecodes['All']}
+
+
+# Linear equations
+def _solve_check(n, info, lamch=None, rcond=None):
+    """ Check arguments during the different steps of the solution phase """
+    if info < 0:
+        raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument.')
+    elif 0 < info:
+        raise LinAlgError('Matrix is singular.')
+
+    if lamch is None:
+        return
+    E = lamch('E')
+    if rcond < E:
+        warn(f'Ill-conditioned matrix (rcond={rcond:.6g}): '
+             'result may not be accurate.',
+             LinAlgWarning, stacklevel=3)
+
+
+def _find_matrix_structure(a):
+    n = a.shape[0]
+    n_below, n_above = bandwidth(a)
+
+    if n_below == n_above == 0:
+        kind = 'diagonal'
+    elif n_above == 0:
+        kind = 'lower triangular'
+    elif n_below == 0:
+        kind = 'upper triangular'
+    elif n_above <= 1 and n_below <= 1 and n > 3:
+        kind = 'tridiagonal'
+    elif np.issubdtype(a.dtype, np.complexfloating) and ishermitian(a):
+        kind = 'hermitian'
+    elif issymmetric(a):
+        kind = 'symmetric'
+    else:
+        kind = 'general'
+
+    return kind, n_below, n_above
+
+
+def solve(a, b, lower=False, overwrite_a=False,
+          overwrite_b=False, check_finite=True, assume_a=None,
+          transposed=False):
+    """
+    Solves the linear equation set ``a @ x == b`` for the unknown ``x``
+    for square `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
+
+    ===================  ================================
+     diagonal             'diagonal'
+     tridiagonal          'tridiagonal'
+     banded               'banded'
+     upper triangular     'upper triangular'
+     lower triangular     'lower triangular'
+     symmetric            'symmetric' (or 'sym')
+     hermitian            'hermitian' (or 'her')
+     positive definite    'positive definite' (or 'pos')
+     general              'general' (or 'gen')
+    ===================  ================================
+
+    Parameters
+    ----------
+    a : (N, N) array_like
+        Square input data
+    b : (N, NRHS) array_like
+        Input data for the right hand side.
+    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, default: False
+        Allow overwriting data in `a` (may enhance performance).
+    overwrite_b : bool, default: False
+        Allow overwriting data in `b` (may enhance performance).
+    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 : (N, NRHS) ndarray
+        The solution array.
+
+    Raises
+    ------
+    ValueError
+        If size mismatches detected or input a is not square.
+    LinAlgError
+        If the matrix is singular.
+    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 ?GESV, ?SYSV, ?HESV, and ?POSV 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 import linalg
+    >>> x = linalg.solve(a, b)
+    >>> x
+    array([ 2., -2.,  9.])
+    >>> np.dot(a, x) == b
+    array([ True,  True,  True], dtype=bool)
+
+    """
+    # Flags for 1-D or N-D right-hand side
+    b_is_1D = False
+
+    # check finite after determining structure
+    a1 = atleast_2d(_asarray_validated(a, check_finite=False))
+    b1 = atleast_1d(_asarray_validated(b, check_finite=False))
+    a1, b1 = _ensure_dtype_cdsz(a1, b1)
+    n = a1.shape[0]
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if a1.shape[0] != a1.shape[1]:
+        raise ValueError('Input a needs to be a square matrix.')
+
+    if n != b1.shape[0]:
+        # Last chance to catch 1x1 scalar a and 1-D b arrays
+        if not (n == 1 and b1.size != 0):
+            raise ValueError('Input b has to have same number of rows as '
+                             'input a')
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    # regularize 1-D b arrays to 2D
+    if b1.ndim == 1:
+        if n == 1:
+            b1 = b1[None, :]
+        else:
+            b1 = b1[:, None]
+        b_is_1D = True
+
+    if assume_a not in {None, 'diagonal', 'tridiagonal', 'banded', 'lower triangular',
+                        'upper triangular', 'symmetric', 'hermitian',
+                        'positive definite', 'general', 'sym', 'her', 'pos', 'gen'}:
+        raise ValueError(f'{assume_a} is not a recognized matrix structure')
+
+    # for a real matrix, describe it as "symmetric", not "hermitian"
+    # (lapack doesn't know what to do with real hermitian matrices)
+    if assume_a in {'hermitian', 'her'} and not np.iscomplexobj(a1):
+        assume_a = 'symmetric'
+
+    n_below, n_above = None, None
+    if assume_a is None:
+        assume_a, n_below, n_above = _find_matrix_structure(a1)
+
+    # Get the correct lamch function.
+    # The LAMCH functions only exists for S and D
+    # So for complex values we have to convert to real/double.
+    if a1.dtype.char in 'fF':  # single precision
+        lamch = get_lapack_funcs('lamch', dtype='f')
+    else:
+        lamch = get_lapack_funcs('lamch', dtype='d')
+
+    # Currently we do not have the other forms of the norm calculators
+    #   lansy, lanpo, lanhe.
+    # However, in any case they only reduce computations slightly...
+    if assume_a == 'diagonal':
+        _matrix_norm = _matrix_norm_diagonal
+    elif assume_a == 'tridiagonal':
+        _matrix_norm = _matrix_norm_tridiagonal
+    elif assume_a in {'lower triangular', 'upper triangular'}:
+        _matrix_norm = _matrix_norm_triangular(assume_a)
+    else:
+        _matrix_norm = _matrix_norm_general
+
+    # Since the I-norm and 1-norm are the same for symmetric matrices
+    # we can collect them all in this one call
+    # Note however, that when issuing 'gen' and form!='none', then
+    # the I-norm should be used
+    if transposed:
+        trans = 1
+        norm = 'I'
+        if np.iscomplexobj(a1):
+            raise NotImplementedError('scipy.linalg.solve can currently '
+                                      'not solve a^T x = b or a^H x = b '
+                                      'for complex matrices.')
+    else:
+        trans = 0
+        norm = '1'
+
+    anorm = _matrix_norm(norm, a1, check_finite)
+
+    info, rcond = 0, np.inf
+
+    # Generalized case 'gesv'
+    if assume_a in {'general', 'gen'}:
+        gecon, getrf, getrs = get_lapack_funcs(('gecon', 'getrf', 'getrs'),
+                                               (a1, b1))
+        lu, ipvt, info = getrf(a1, overwrite_a=overwrite_a)
+        _solve_check(n, info)
+        x, info = getrs(lu, ipvt, b1,
+                        trans=trans, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = gecon(lu, anorm, norm=norm)
+    # Hermitian case 'hesv'
+    elif assume_a in {'hermitian', 'her'}:
+        hecon, hesv, hesv_lw = get_lapack_funcs(('hecon', 'hesv',
+                                                 'hesv_lwork'), (a1, b1))
+        lwork = _compute_lwork(hesv_lw, n, lower)
+        lu, ipvt, x, info = hesv(a1, b1, lwork=lwork,
+                                 lower=lower,
+                                 overwrite_a=overwrite_a,
+                                 overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = hecon(lu, ipvt, anorm)
+    # Symmetric case 'sysv'
+    elif assume_a in {'symmetric', 'sym'}:
+        sycon, sysv, sysv_lw = get_lapack_funcs(('sycon', 'sysv',
+                                                 'sysv_lwork'), (a1, b1))
+        lwork = _compute_lwork(sysv_lw, n, lower)
+        lu, ipvt, x, info = sysv(a1, b1, lwork=lwork,
+                                 lower=lower,
+                                 overwrite_a=overwrite_a,
+                                 overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = sycon(lu, ipvt, anorm)
+    # Diagonal case
+    elif assume_a == 'diagonal':
+        diag_a = np.diag(a1)
+        x = (b1.T / diag_a).T
+        abs_diag_a = np.abs(diag_a)
+        rcond = abs_diag_a.min() / abs_diag_a.max()
+    # Tri-diagonal case
+    elif assume_a == 'tridiagonal':
+        a1 = a1.T if transposed else a1
+        dl, d, du = np.diag(a1, -1), np.diag(a1, 0), np.diag(a1, 1)
+        _gttrf, _gttrs, _gtcon = get_lapack_funcs(('gttrf', 'gttrs', 'gtcon'), (a1, b1))
+        dl, d, du, du2, ipiv, info = _gttrf(dl, d, du)
+        _solve_check(n, info)
+        x, info = _gttrs(dl, d, du, du2, ipiv, b1, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = _gtcon(dl, d, du, du2, ipiv, anorm)
+    # Banded case
+    elif assume_a == 'banded':
+        a1, n_below, n_above = ((a1.T, n_above, n_below) if transposed
+                                else (a1, n_below, n_above))
+        n_below, n_above = bandwidth(a1) if n_below is None else (n_below, n_above)
+        ab = _to_banded(n_below, n_above, a1)
+        gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
+        # Next two lines copied from `solve_banded`
+        a2 = np.zeros((2*n_below + n_above + 1, ab.shape[1]), dtype=gbsv.dtype)
+        a2[n_below:, :] = ab
+        _, _, x, info = gbsv(n_below, n_above, a2, b1,
+                             overwrite_ab=True, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        # TODO: wrap gbcon and use to get rcond
+    # Triangular case
+    elif assume_a in {'lower triangular', 'upper triangular'}:
+        lower = assume_a == 'lower triangular'
+        x, info = _solve_triangular(a1, b1, lower=lower, overwrite_b=overwrite_b,
+                                    trans=transposed)
+        _solve_check(n, info)
+        _trcon = get_lapack_funcs(('trcon'), (a1, b1))
+        rcond, info = _trcon(a1, uplo='L' if lower else 'U')
+    # Positive definite case 'posv'
+    else:
+        pocon, posv = get_lapack_funcs(('pocon', 'posv'),
+                                       (a1, b1))
+        lu, x, info = posv(a1, b1, lower=lower,
+                           overwrite_a=overwrite_a,
+                           overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = pocon(lu, anorm)
+
+    _solve_check(n, info, lamch, rcond)
+
+    if b_is_1D:
+        x = x.ravel()
+
+    return x
+
+
+def _matrix_norm_diagonal(_, a, check_finite):
+    # Equivalent of dlange for diagonal matrix, assuming
+    # norm is either 'I' or '1' (really just not the Frobenius norm)
+    d = np.diag(a)
+    d = np.asarray_chkfinite(d) if check_finite else d
+    return np.abs(d).max()
+
+
+def _matrix_norm_tridiagonal(norm, a, check_finite):
+    # Equivalent of dlange for tridiagonal matrix, assuming
+    # norm is either 'I' or '1'
+    if norm == 'I':
+        a = a.T
+    # Context to avoid warning before error in cases like -inf + inf
+    with np.errstate(invalid='ignore'):
+        d = np.abs(np.diag(a))
+        d[1:] += np.abs(np.diag(a, 1))
+        d[:-1] += np.abs(np.diag(a, -1))
+    d = np.asarray_chkfinite(d) if check_finite else d
+    return d.max()
+
+
+def _matrix_norm_triangular(structure):
+    def fun(norm, a, check_finite):
+        a = np.asarray_chkfinite(a) if check_finite else a
+        lantr = get_lapack_funcs('lantr', (a,))
+        return lantr(norm, a, 'L' if structure == 'lower triangular' else 'U' )
+    return fun
+
+
+def _matrix_norm_general(norm, a, check_finite):
+    a = np.asarray_chkfinite(a) if check_finite else a
+    lange = get_lapack_funcs('lange', (a,))
+    return lange(norm, a)
+
+
+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
+
+
+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 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`, assuming 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``
+    lower : bool, optional
+        Use only data contained in the lower triangle of `a`.
+        Default is to use upper triangle.
+    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
+        ========  =========
+    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)
+    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("singular matrix: resolution failed at diagonal %d" %
+                          (info-1))
+    raise ValueError('illegal value in %dth argument of internal trtrs' %
+                     (-info))
+
+
+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, assuming a is banded matrix.
+
+    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   *    *
+
+    Parameters
+    ----------
+    (l, u) : (integer, integer)
+        Number of non-zero lower and upper diagonals
+    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)
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance)
+    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 ])
+
+    """
+
+    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.")
+
+    (nlower, nupper) = l_and_u
+    if nlower + nupper + 1 != a1.shape[0]:
+        raise ValueError("invalid values for the number of lower and upper "
+                         "diagonals: l+u+1 (%d) does not equal ab.shape[0] "
+                         "(%d)" % (nlower + nupper + 1, 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('illegal value in %d-th argument of internal '
+                     'gbsv/gtsv' % -info)
+
+
+def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False,
+                  check_finite=True):
+    """
+    Solve equation a x = b. a is Hermitian positive-definite banded matrix.
+
+    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)
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance)
+    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("%dth leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal '
+                         'pbsv' % -info)
+    return x
+
+
+def solve_toeplitz(c_or_cr, b, check_finite=True):
+    r"""Solve a Toeplitz system using Levinson Recursion
+
+    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.
+
+    .. warning::
+
+        Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
+        not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+        before passing them to `solve_toeplitz`.
+
+    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.
+
+    r, c, b, dtype, b_shape = _validate_args_for_toeplitz_ops(
+        c_or_cr, 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 C x = b for x, where C is a circulant matrix.
+
+    `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')
+
+    # 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.shape = 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):
+    """
+    Compute the inverse of a matrix.
+
+    Parameters
+    ----------
+    a : array_like
+        Square matrix to be inverted.
+    overwrite_a : bool, optional
+        Discard data in `a` (may improve performance). Default is False.
+    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
+    -------
+    ainv : ndarray
+        Inverse of the matrix `a`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular.
+    ValueError
+        If `a` is not square, or not 2D.
+
+    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]])
+    >>> np.dot(a, linalg.inv(a))
+    array([[ 1.,  0.],
+           [ 0.,  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 matrix')
+
+    # accommodate empty square matrices
+    if a1.size == 0:
+        dt = inv(np.eye(2, dtype=a1.dtype)).dtype
+        return np.empty_like(a1, dtype=dt)
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    getrf, getri, getri_lwork = get_lapack_funcs(('getrf', 'getri',
+                                                  'getri_lwork'),
+                                                 (a1,))
+    lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
+    if info == 0:
+        lwork = _compute_lwork(getri_lwork, a1.shape[0])
+
+        # XXX: the following line fixes curious SEGFAULT when
+        # benchmarking 500x500 matrix inverse. This seems to
+        # be a bug in LAPACK ?getri routine because if lwork is
+        # minimal (when using lwork[0] instead of lwork[1]) then
+        # all tests pass. Further investigation is required if
+        # more such SEGFAULTs occur.
+        lwork = int(1.01 * lwork)
+        inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1)
+    if info > 0:
+        raise LinAlgError("singular matrix")
+    if info < 0:
+        raise ValueError('illegal value in %d-th argument of internal '
+                         'getrf|getri' % -info)
+    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.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Input array to compute determinants for.
+    overwrite_a : bool, optional
+        Allow overwriting data in a (may enhance performance).
+    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)
+    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
+    if a1.dtype.char not in 'fdFD':
+        dtype_char = lapack_cast_dict[a1.dtype.char]
+        if not dtype_char:  # No casting possible
+            raise TypeError(f'The dtype "{a1.dtype.name}" cannot be cast '
+                            'to float(32, 64) or complex(64, 128).')
+
+        a1 = a1.astype(dtype_char[0])  # makes a copy, free to scratch
+        overwrite_a = True
+
+    # 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')
+
+    # Then check overwrite permission
+    if not _datacopied(a1, a):  # "a"  still alive through "a1"
+        if not overwrite_a:
+            # Data belongs to "a" so make a copy
+            a1 = a1.copy(order='C')
+        #  else: Do nothing we'll use "a" if possible
+    # else:  a1 has its own data thus free to scratch
+
+    # Then layout checks, might happen that overwrite is allowed but original
+    # array was read-only or non-C-contiguous.
+    if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
+        a1 = a1.copy(order='C')
+
+    if a1.ndim == 2:
+        det = find_det_from_lu(a1)
+        # Convert float, complex to NumPy scalars
+        return (np.float64(det) if np.isrealobj(det) else np.complex128(det))
+
+    # loop over the stacked array, and avoid overflows for single precision
+    # Cf. np.linalg.det(np.diag([1e+38, 1e+38]).astype(np.float32))
+    dtype_char = a1.dtype.char
+    if dtype_char in 'fF':
+        dtype_char = 'd' if dtype_char.islower() else 'D'
+
+    det = np.empty(a1.shape[:-2], dtype=dtype_char)
+    for ind in product(*[range(x) for x in a1.shape[:-2]]):
+        det[ind] = find_det_from_lu(a1[ind])
+    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 equation Ax = 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
+        Discard data in `a` (may enhance performance). Default is False.
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance). Default is False.
+    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
+        Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and
+        ``rank(A) == n`` (returns a scalar if ``b`` is 1-D). Otherwise 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, `residues` is set to a (0,)-shaped
+    array and `s` is always ``None``.
+
+    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()
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+    if len(a1.shape) != 2:
+        raise ValueError('Input array a should be 2D')
+    m, n = a1.shape
+    if len(b1.shape) == 2:
+        nrhs = b1.shape[1]
+    else:
+        nrhs = 1
+    if m != b1.shape[0]:
+        raise ValueError('Shape mismatch: a and b should have the same number'
+                         f' of rows ({m} != {b1.shape[0]}).')
+    if m == 0 or n == 0:  # Zero-sized problem, confuses LAPACK
+        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,))
+
+    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')
+
+    lapack_func, lapack_lwork = get_lapack_funcs((driver,
+                                                 f'{driver}_lwork'),
+                                                 (a1, b1))
+    real_data = True if (lapack_func.dtype.kind == 'f') else False
+
+    if m < n:
+        # need to extend b matrix as it will be filled with
+        # a larger solution matrix
+        if len(b1.shape) == 2:
+            b2 = np.zeros((n, nrhs), dtype=lapack_func.dtype)
+            b2[:m, :] = b1
+        else:
+            b2 = np.zeros(n, dtype=lapack_func.dtype)
+            b2[:m] = b1
+        b1 = b2
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if cond is None:
+        cond = np.finfo(lapack_func.dtype).eps
+
+    if driver in ('gelss', 'gelsd'):
+        if driver == 'gelss':
+            lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+            v, x, s, rank, work, info = lapack_func(a1, b1, cond, lwork,
+                                                    overwrite_a=overwrite_a,
+                                                    overwrite_b=overwrite_b)
+
+        elif driver == 'gelsd':
+            if real_data:
+                lwork, iwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+                x, s, rank, info = lapack_func(a1, b1, lwork,
+                                               iwork, cond, False, False)
+            else:  # complex data
+                lwork, rwork, iwork = _compute_lwork(lapack_lwork, m, n,
+                                                     nrhs, cond)
+                x, s, rank, info = lapack_func(a1, b1, lwork, rwork, iwork,
+                                               cond, False, False)
+        if info > 0:
+            raise LinAlgError("SVD did not converge in Linear Least Squares")
+        if info < 0:
+            raise ValueError('illegal value in %d-th argument of internal %s'
+                             % (-info, lapack_driver))
+        resids = np.asarray([], dtype=x.dtype)
+        if m > n:
+            x1 = x[:n]
+            if rank == n:
+                resids = np.sum(np.abs(x[n:])**2, axis=0)
+            x = x1
+        return x, resids, rank, s
+
+    elif driver == 'gelsy':
+        lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+        jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+        v, x, j, rank, info = lapack_func(a1, b1, jptv, cond,
+                                          lwork, False, False)
+        if info < 0:
+            raise ValueError("illegal value in %d-th argument of internal "
+                             "gelsy" % -info)
+        if m > n:
+            x1 = x[:n]
+            x = x1
+        return x, np.array([], x.dtype), rank, None
+
+
+lstsq.default_lapack_driver = 'gelsd'
+
+
+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.
+
+    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
+
+    """
+    a = _asarray_validated(a, check_finite=check_finite)
+    u, s, vh = _decomp_svd.svd(a, full_matrices=False, check_finite=False)
+    t = u.dtype.char.lower()
+    maxS = np.max(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
+    rank = np.sum(s > val)
+
+    u = u[:, :rank]
+    u /= s[:rank]
+    B = (u @ vh[:rank]).conj().T
+
+    if return_rank:
+        return B, rank
+    else:
+        return B
+
+
+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
+
+
+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.
+
+    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.
+
+    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.
+
+    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
+    -----
+    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 c.ndim > 1 or r.ndim > 1:
+        msg = ("Beginning in SciPy 1.17, 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 "
+               "`toeplitz`, `matmul_toeplitz`, and `solve_toeplitz`.")
+        warnings.warn(msg, FutureWarning, stacklevel=2)
+        c = c.ravel()
+        r = r.ravel()
+
+    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.
+
+    .. warning::
+
+        Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
+        not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+        before passing them to `matmul_toeplitz`.
+
+    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
+
+    r, c, x, dtype, x_shape = _validate_args_for_toeplitz_ops(
+        c_or_cr, 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h
new file mode 100644
index 0000000000000000000000000000000000000000..a175ca15f4adbed6d5c576e9e5ee1117abbd31ec
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h
@@ -0,0 +1,164 @@
+/*
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+*/
+
+#include "npy_cblas.h"
+#include "fortran_defs.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void BLAS_FUNC(caxpy)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(ccopy)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void F_FUNC(cdotcwrp,CDOTCWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void F_FUNC(cdotuwrp,CDOTUWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(cgbmv)(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cgemm)(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(cgemv)(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cgerc)(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cgeru)(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(chbmv)(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(chemm)(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(chemv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cher)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cher2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cher2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(cherk)(char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(chpmv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(chpr)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap);
+void BLAS_FUNC(chpr2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap);
+void BLAS_FUNC(crotg)(npy_complex64 *ca, npy_complex64 *cb, float *c, npy_complex64 *s);
+void BLAS_FUNC(cscal)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(csrot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, float *s);
+void BLAS_FUNC(csscal)(int *n, float *sa, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(cswap)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(csymm)(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(csyr2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(csyrk)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(ctbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+double BLAS_FUNC(dasum)(int *n, double *dx, int *incx);
+void BLAS_FUNC(daxpy)(int *n, double *da, double *dx, int *incx, double *dy, int *incy);
+double BLAS_FUNC(dcabs1)(npy_complex128 *z);
+void BLAS_FUNC(dcopy)(int *n, double *dx, int *incx, double *dy, int *incy);
+double BLAS_FUNC(ddot)(int *n, double *dx, int *incx, double *dy, int *incy);
+void BLAS_FUNC(dgbmv)(char *trans, int *m, int *n, int *kl, int *ku, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dgemm)(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dgemv)(char *trans, int *m, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dger)(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda);
+double BLAS_FUNC(dnrm2)(int *n, double *x, int *incx);
+void BLAS_FUNC(drot)(int *n, double *dx, int *incx, double *dy, int *incy, double *c, double *s);
+void BLAS_FUNC(drotg)(double *da, double *db, double *c, double *s);
+void BLAS_FUNC(drotm)(int *n, double *dx, int *incx, double *dy, int *incy, double *dparam);
+void BLAS_FUNC(drotmg)(double *dd1, double *dd2, double *dx1, double *dy1, double *dparam);
+void BLAS_FUNC(dsbmv)(char *uplo, int *n, int *k, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dscal)(int *n, double *da, double *dx, int *incx);
+double BLAS_FUNC(dsdot)(int *n, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(dspmv)(char *uplo, int *n, double *alpha, double *ap, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dspr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *ap);
+void BLAS_FUNC(dspr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *ap);
+void BLAS_FUNC(dswap)(int *n, double *dx, int *incx, double *dy, int *incy);
+void BLAS_FUNC(dsymm)(char *side, char *uplo, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dsymv)(char *uplo, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dsyr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *a, int *lda);
+void BLAS_FUNC(dsyr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda);
+void BLAS_FUNC(dsyr2k)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dsyrk)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dtbmv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtbsv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtpmv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx);
+void BLAS_FUNC(dtpsv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx);
+void BLAS_FUNC(dtrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dtrmv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dtrsv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx);
+double BLAS_FUNC(dzasum)(int *n, npy_complex128 *zx, int *incx);
+double BLAS_FUNC(dznrm2)(int *n, npy_complex128 *x, int *incx);
+int BLAS_FUNC(icamax)(int *n, npy_complex64 *cx, int *incx);
+int BLAS_FUNC(idamax)(int *n, double *dx, int *incx);
+int BLAS_FUNC(isamax)(int *n, float *sx, int *incx);
+int BLAS_FUNC(izamax)(int *n, npy_complex128 *zx, int *incx);
+int BLAS_FUNC(lsame)(char *ca, char *cb);
+float BLAS_FUNC(sasum)(int *n, float *sx, int *incx);
+void BLAS_FUNC(saxpy)(int *n, float *sa, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(scasum)(int *n, npy_complex64 *cx, int *incx);
+float BLAS_FUNC(scnrm2)(int *n, npy_complex64 *x, int *incx);
+void BLAS_FUNC(scopy)(int *n, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(sdot)(int *n, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(sdsdot)(int *n, float *sb, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(sgbmv)(char *trans, int *m, int *n, int *kl, int *ku, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sgemm)(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(sgemv)(char *trans, int *m, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sger)(int *m, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda);
+float BLAS_FUNC(snrm2)(int *n, float *x, int *incx);
+void BLAS_FUNC(srot)(int *n, float *sx, int *incx, float *sy, int *incy, float *c, float *s);
+void BLAS_FUNC(srotg)(float *sa, float *sb, float *c, float *s);
+void BLAS_FUNC(srotm)(int *n, float *sx, int *incx, float *sy, int *incy, float *sparam);
+void BLAS_FUNC(srotmg)(float *sd1, float *sd2, float *sx1, float *sy1, float *sparam);
+void BLAS_FUNC(ssbmv)(char *uplo, int *n, int *k, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sscal)(int *n, float *sa, float *sx, int *incx);
+void BLAS_FUNC(sspmv)(char *uplo, int *n, float *alpha, float *ap, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sspr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *ap);
+void BLAS_FUNC(sspr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *ap);
+void BLAS_FUNC(sswap)(int *n, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(ssymm)(char *side, char *uplo, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(ssymv)(char *uplo, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(ssyr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *a, int *lda);
+void BLAS_FUNC(ssyr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda);
+void BLAS_FUNC(ssyr2k)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(ssyrk)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c, int *ldc);
+void BLAS_FUNC(stbmv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(stbsv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(stpmv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx);
+void BLAS_FUNC(stpsv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx);
+void BLAS_FUNC(strmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(strmv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(strsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(strsv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(zaxpy)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zcopy)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void F_FUNC(zdotcwrp,ZDOTCWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void F_FUNC(zdotuwrp,ZDOTUWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zdrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, double *s);
+void BLAS_FUNC(zdscal)(int *n, double *da, npy_complex128 *zx, int *incx);
+void BLAS_FUNC(zgbmv)(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zgemm)(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zgemv)(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zgerc)(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zgeru)(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zhbmv)(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zhemm)(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zhemv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zher)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zher2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zher2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zherk)(char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zhpmv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zhpr)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap);
+void BLAS_FUNC(zhpr2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap);
+void BLAS_FUNC(zrotg)(npy_complex128 *ca, npy_complex128 *cb, double *c, npy_complex128 *s);
+void BLAS_FUNC(zscal)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx);
+void BLAS_FUNC(zswap)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zsymm)(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zsyr2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zsyrk)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(ztbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..ccec61c078e57ba7b6a310ec57189fcf236c972d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd
@@ -0,0 +1,40 @@
+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 (int, int) band_check_internal_c(np_numeric_t[:, ::1]A) 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..5633cb61ecf3a90eba901120f64fa6cc6634fa5a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi
@@ -0,0 +1,16 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def bandwidth(a: NDArray[Any]) -> tuple[int, int]: ...
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c520d6b04b6bf0a22c4fcad62d98a17faea7c9fd
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py
@@ -0,0 +1,1632 @@
+#
+# 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,
+                   flatnonzero, conj, asarray, argsort, empty,
+                   iscomplex, zeros, einsum, eye, inf)
+# Local imports
+from scipy._lib._util import _asarray_validated
+from ._misc import LinAlgError, _datacopied, norm
+from .lapack import get_lapack_funcs, _compute_lwork
+
+
+_I = np.array(1j, dtype='F')
+
+
+def _make_complex_eigvecs(w, vin, dtype):
+    """
+    Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output
+    """
+    # - see LAPACK man page DGGEV at ALPHAI
+    v = np.array(vin, dtype=dtype)
+    m = (w.imag > 0)
+    m[:-1] |= (w.imag[1:] < 0)  # workaround for LAPACK bug, cf. ticket #709
+    for i in flatnonzero(m):
+        v.imag[:, i] = vin[:, i+1]
+        conj(v[:, i], v[:, i+1])
+    return v
+
+
+def _make_eigvals(alpha, beta, homogeneous_eigvals):
+    if homogeneous_eigvals:
+        if beta is None:
+            return np.vstack((alpha, np.ones_like(alpha)))
+        else:
+            return np.vstack((alpha, beta))
+    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 _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
+            homogeneous_eigvals):
+    ggev, = get_lapack_funcs(('ggev',), (a1, b1))
+    cvl, cvr = left, right
+    res = ggev(a1, b1, lwork=-1)
+    lwork = res[-2][0].real.astype(np.int_)
+    if ggev.typecode in 'cz':
+        alpha, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,
+                                               overwrite_a, overwrite_b)
+        w = _make_eigvals(alpha, beta, homogeneous_eigvals)
+    else:
+        alphar, alphai, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr,
+                                                        lwork, overwrite_a,
+                                                        overwrite_b)
+        alpha = alphar + _I * alphai
+        w = _make_eigvals(alpha, beta, homogeneous_eigvals)
+    _check_info(info, 'generalized eig algorithm (ggev)')
+
+    only_real = np.all(w.imag == 0.0)
+    if not (ggev.typecode in 'cz' or only_real):
+        t = w.dtype.char
+        if left:
+            vl = _make_complex_eigvecs(w, vl, t)
+        if right:
+            vr = _make_complex_eigvecs(w, vr, t)
+
+    # the eigenvectors returned by the lapack function are NOT normalized
+    for i in range(vr.shape[0]):
+        if right:
+            vr[:, i] /= norm(vr[:, i])
+        if left:
+            vl[:, i] /= norm(vl[:, i])
+
+    if not (left or right):
+        return w
+    if left:
+        if right:
+            return w, vl, vr
+        return w, vl
+    return w, vr
+
+
+def eig(a, b=None, left=False, right=True, overwrite_a=False,
+        overwrite_b=False, check_finite=True, homogeneous_eigvals=False):
+    """
+    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.
+    overwrite_b : bool, optional
+        Whether to overwrite `b`; may improve performance.  Default is False.
+    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]
+
+        Default is False.
+
+    Returns
+    -------
+    w : (M,) or (2, M) double or 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``.
+
+    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 eiegenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0., -1.], [1., 0.]])
+    >>> linalg.eigvals(a)
+    array([0.+1.j, 0.-1.j])
+
+    >>> b = np.array([[0., 1.], [1., 1.]])
+    >>> linalg.eigvals(a, b)
+    array([ 1.+0.j, -1.+0.j])
+
+    >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
+    >>> linalg.eigvals(a, homogeneous_eigvals=True)
+    array([[3.+0.j, 8.+0.j, 7.+0.j],
+           [1.+0.j, 1.+0.j, 1.+0.j]])
+
+    >>> a = np.array([[0., -1.], [1., 0.]])
+    >>> linalg.eigvals(a) == linalg.eig(a)[0]
+    array([ True,  True])
+    >>> linalg.eig(a, left=True, right=False)[1] # normalized left eigenvector
+    array([[-0.70710678+0.j        , -0.70710678-0.j        ],
+           [-0.        +0.70710678j, -0.        -0.70710678j]])
+    >>> linalg.eig(a, left=False, right=True)[1] # normalized right eigenvector
+    array([[0.70710678+0.j        , 0.70710678-0.j        ],
+           [0.        -0.70710678j, 0.        +0.70710678j]])
+
+
+
+    """
+    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')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, vr_n = eig(np.eye(2, dtype=a1.dtype))
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+        vl = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype)
+        vr = np.empty_like(a1, 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
+
+    overwrite_a = overwrite_a or (_datacopied(a1, 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 matrix')
+        if b1.shape != a1.shape:
+            raise ValueError('a and b must have the same shape')
+        return _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
+                       homogeneous_eigvals)
+
+    geev, geev_lwork = get_lapack_funcs(('geev', 'geev_lwork'), (a1,))
+    compute_vl, compute_vr = left, right
+
+    lwork = _compute_lwork(geev_lwork, a1.shape[0],
+                           compute_vl=compute_vl,
+                           compute_vr=compute_vr)
+
+    if geev.typecode in 'cz':
+        w, vl, vr, info = geev(a1, lwork=lwork,
+                               compute_vl=compute_vl,
+                               compute_vr=compute_vr,
+                               overwrite_a=overwrite_a)
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+    else:
+        wr, wi, vl, vr, info = geev(a1, lwork=lwork,
+                                    compute_vl=compute_vl,
+                                    compute_vr=compute_vr,
+                                    overwrite_a=overwrite_a)
+        w = wr + _I * wi
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+
+    _check_info(info, 'eig algorithm (geev)',
+                positive='did not converge (only eigenvalues '
+                         'with order >= %d have converged)')
+
+    only_real = np.all(w.imag == 0.0)
+    if not (geev.typecode in 'cz' or only_real):
+        t = w.dtype.char
+        if left:
+            vl = _make_complex_eigvecs(w, vl, t)
+        if right:
+            vr = _make_complex_eigvecs(w, vr, t)
+    if not (left or right):
+        return w
+    if left:
+        if right:
+            return w, vl, vr
+        return w, vl
+    return w, vr
+
+
+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)
+    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.
+    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.
+    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.
+    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
+    -------
+    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 eiegenvectors 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
+
+
+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)
+    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, check_finite=True,
+            homogeneous_eigvals=False):
+    """
+    Compute eigenvalues from an ordinary or generalized eigenvalue problem.
+
+    Find eigenvalues of a general matrix::
+
+        a   vr[:,i] = w[i]        b   vr[:,i]
+
+    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.
+        If omitted, identity matrix is assumed.
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    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]
+
+        Default is False.
+
+    Returns
+    -------
+    w : (M,) or (2, M) double or 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.]])
+    >>> linalg.eigvals(a)
+    array([0.+1.j, 0.-1.j])
+
+    >>> b = np.array([[0., 1.], [1., 1.]])
+    >>> linalg.eigvals(a, b)
+    array([ 1.+0.j, -1.+0.j])
+
+    >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
+    >>> linalg.eigvals(a, homogeneous_eigvals=True)
+    array([[3.+0.j, 8.+0.j, 7.+0.j],
+           [1.+0.j, 1.+0.j, 1.+0.j]])
+
+    """
+    return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a,
+               check_finite=check_finite,
+               homogeneous_eigvals=homogeneous_eigvals)
+
+
+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.
+    overwrite_b : bool, optional
+        Whether to overwrite data in ``b`` (may improve performance). Default
+        is False.
+    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)
+
+
+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)
+    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)
+
+
+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',
+        or 'stev'. When 'auto' (default), it will use 'stemr' 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 eiegenvectors 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)
+
+
+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',
+        or 'stev'. When 'auto' (default), it will use 'stemr' 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')
+    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 = 'stemr' 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 == '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('illegal value in argument %d of internal %s'
+                         % (-info, driver))
+    if info > 0 and positive:
+        raise LinAlgError(("%s " + positive) % (driver, info,))
+
+
+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.
+    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):
+    """
+    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
+
+    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)
+
+    # 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..c35b6a4920dea6bb638fe54a1fa719ebc74fb773
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py
@@ -0,0 +1,398 @@
+"""Cholesky decomposition functions."""
+
+import numpy as np
+from numpy import asarray_chkfinite, asarray, atleast_2d, empty_like
+
+# Local imports
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs
+
+__all__ = ['cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
+           'cho_solve_banded']
+
+
+def _cholesky(a, lower=False, overwrite_a=False, clean=True,
+              check_finite=True):
+    """Common code for cholesky() and cho_factor()."""
+
+    a1 = asarray_chkfinite(a) if check_finite else asarray(a)
+    a1 = atleast_2d(a1)
+
+    # Dimension check
+    if a1.ndim != 2:
+        raise ValueError(f'Input array needs to be 2D but received a {a1.ndim}d-array.')
+    # Squareness check
+    if a1.shape[0] != a1.shape[1]:
+        raise ValueError('Input array is expected to be square but has '
+                         f'the shape: {a1.shape}.')
+
+    # Quick return for square empty array
+    if a1.size == 0:
+        dt = cholesky(np.eye(1, dtype=a1.dtype)).dtype
+        return empty_like(a1, dtype=dt), lower
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    potrf, = get_lapack_funcs(('potrf',), (a1,))
+    c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)
+    if info > 0:
+        raise LinAlgError("%d-th leading minor of the array is not positive "
+                          "definite" % info)
+    if info < 0:
+        raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument'
+                         'on entry to "POTRF".')
+    return c, lower
+
+
+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).
+    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.
+
+    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]])
+
+    """
+    c, lower = _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::
+        The returned matrix also contains random data in the entries not
+        used by the Cholesky decomposition. If you need to zero these
+        entries, use the function `cholesky` instead.
+
+    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)
+    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 : bool
+        Flag indicating whether the factor is in the lower or upper triangle
+
+    Raises
+    ------
+    LinAlgError
+        Raised if decomposition fails.
+
+    See Also
+    --------
+    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]])
+    >>> c, low = cho_factor(A)
+    >>> 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, np.zeros((4, 4)))
+    True
+
+    """
+    c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
+                         check_finite=check_finite)
+    return c, 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.
+
+    Parameters
+    ----------
+    (c, lower) : tuple, (array, bool)
+        Cholesky factorization of a, as given by cho_factor
+    b : array
+        Right-hand side
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance)
+    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
+    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('illegal value in %dth argument of internal potrs'
+                         % -info)
+    return x
+
+
+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)
+    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("%d-th leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %d-th argument of internal pbtrf'
+                         % -info)
+    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``.
+
+    Parameters
+    ----------
+    (cb, lower) : tuple, (ndarray, bool)
+        `cb` is the Cholesky factorization of A, as given by cholesky_banded.
+        `lower` must be the same value that was given to cholesky_banded.
+    b : array_like
+        Right-hand side
+    overwrite_b : bool, optional
+        If True, the function will overwrite the values in `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
+        (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
+    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("%dth leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal pbtrs'
+                         % -info)
+    return x
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..e10c04fe5ebc196e1b84724b25f0fc20a5e46857
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py
@@ -0,0 +1,221 @@
+from collections.abc import Iterable
+import numpy as np
+
+from scipy._lib._util import _asarray_validated
+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.
+
+    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):
+            raise ValueError("Cosine Sine decomposition only supports square"
+                             f" matrices, got {X.shape}")
+        m = X.shape[0]
+        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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..336df1d5fb416f635c91afe3cc2cfb3c340239fc
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py
@@ -0,0 +1,353 @@
+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 scipy._lib._util import ComplexWarning
+from ._decomp import _asarray_validated
+from .lapack import get_lapack_funcs, _compute_lwork
+
+__all__ = ['ldl']
+
+
+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.
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..06562a4a490a4328c08d4de45a5463427e33562b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py
@@ -0,0 +1,389 @@
+"""LU decomposition functions."""
+
+from warnings import warn
+
+from numpy import asarray, asarray_chkfinite
+import numpy as np
+from itertools import product
+
+# Local imports
+from ._misc import _datacopied, LinAlgWarning
+from .lapack import get_lapack_funcs
+from ._decomp_lu_cython import lu_dispatcher
+
+lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
+                    for x in np.typecodes['All']}
+
+__all__ = ['lu', 'lu_solve', 'lu_factor']
+
+
+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 increase performance)
+    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.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('illegal value in %dth argument of '
+                         'internal getrf (lu_factor)' % -info)
+    if info > 0:
+        warn("Diagonal number %d is exactly zero. Singular matrix." % info,
+             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
+
+    Parameters
+    ----------
+    (lu, piv)
+        Factorization of the coefficient matrix a, 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)
+    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
+    if check_finite:
+        b1 = asarray_chkfinite(b)
+    else:
+        b1 = asarray(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('illegal value in %dth argument of internal gesv|posv'
+                     % -info)
+
+
+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``.
+
+    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)
+    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
+    -------
+    **(If `permute_l` is ``False``)**
+
+    p : (..., M, M) ndarray
+        Permutation arrays or vectors depending on `p_indices`
+    l : (..., M, K) ndarray
+        Lower triangular or trapezoidal array with unit diagonal.
+        ``K = min(M, N)``
+    u : (..., K, N) ndarray
+        Upper triangular or trapezoidal array
+
+    **(If `permute_l` is ``True``)**
+
+    pl : (..., M, K) ndarray
+        Permuted L matrix.
+        ``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)
+    if a1.ndim < 2:
+        raise ValueError('The input array must be at least two-dimensional.')
+
+    # Also check if dtype is LAPACK compatible
+    if a1.dtype.char not in 'fdFD':
+        dtype_char = lapack_cast_dict[a1.dtype.char]
+        if not dtype_char:  # No casting possible
+            raise TypeError(f'The dtype {a1.dtype} cannot be cast '
+                            'to float(32, 64) or complex(64, 128).')
+
+        a1 = a1.astype(dtype_char[0])  # makes a copy, free to scratch
+        overwrite_a = True
+
+    *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())
+
+    # Then check overwrite permission
+    if not _datacopied(a1, a):  # "a"  still alive through "a1"
+        if not overwrite_a:
+            # Data belongs to "a" so make a copy
+            a1 = a1.copy(order='C')
+        #  else: Do nothing we'll use "a" if possible
+    # else:  a1 has its own data thus free to scratch
+
+    # Then layout checks, might happen that overwrite is allowed but original
+    # array was read-only or non-contiguous.
+
+    if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
+        a1 = a1.copy(order='C')
+
+    if not nd:  # 2D array
+
+        p = np.empty(m, dtype=np.int32)
+        u = np.zeros([k, k], dtype=a1.dtype)
+        lu_dispatcher(a1, u, p, permute_l)
+        P, L, U = (p, a1, u) if m > n else (p, u, a1)
+
+    else:  # Stacked array
+
+        # Prepare the contiguous data holders
+        P = np.empty([*nd, m], dtype=np.int32)  # perm vecs
+
+        if m > n:  # Tall arrays, U will be created
+            U = np.zeros([*nd, k, k], dtype=a1.dtype)
+            for ind in product(*[range(x) for x in a1.shape[:-2]]):
+                lu_dispatcher(a1[ind], U[ind], P[ind], permute_l)
+            L = a1
+
+        else:  # Fat arrays, L will be created
+            L = np.zeros([*nd, k, k], dtype=a1.dtype)
+            for ind in product(*[range(x) for x in a1.shape[:-2]]):
+                lu_dispatcher(a1[ind], L[ind], P[ind], permute_l)
+            U = a1
+
+    # 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0a175b1de32806102318cf69f7c5b4c3deddb03c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi
@@ -0,0 +1,6 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def lu_decompose(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ...  # noqa: E501
+
+def lu_dispatcher(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ...  # noqa: E501
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fc3652899bed607ab1dd5e3f1663345010e93c1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py
@@ -0,0 +1,111 @@
+import numpy as np
+from scipy.linalg import svd
+
+
+__all__ = ['polar']
+
+
+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 `a` 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..a41ad90770e3d53c741d85e6f46d4040bf203e7a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py
@@ -0,0 +1,490 @@
+"""QR decomposition functions."""
+import numpy as np
+
+# Local imports
+from .lapack import get_lapack_funcs
+from ._misc import _datacopied
+
+__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("illegal value in %dth argument of internal %s"
+                         % (-ret[-1], name))
+    return ret[:-2]
+
+
+def qr(a, overwrite_a=False, lwork=None, 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 data in `a` is overwritten (may improve performance if
+        `overwrite_a` is set to True by reusing the existing input data
+        structure rather than creating a new one.)
+    lwork : int, optional
+        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
+        is computed.
+    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
+
+    """
+    # '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 ['full', 'qr', 'r', 'economic', 'raw']:
+        raise ValueError("Mode argument should be one of ['full', 'r', "
+                         "'economic', 'raw']")
+
+    if check_finite:
+        a1 = np.asarray_chkfinite(a)
+    else:
+        a1 = np.asarray(a)
+    if len(a1.shape) != 2:
+        raise ValueError("expected a 2-D array")
+
+    M, N = a1.shape
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        K = min(M, N)
+
+        if mode not in ['economic', 'raw']:
+            Q = np.empty_like(a1, shape=(M, M))
+            Q[...] = np.identity(M)
+            R = np.empty_like(a1)
+        else:
+            Q = np.empty_like(a1, shape=(M, K))
+            R = np.empty_like(a1, shape=(K, N))
+
+        if pivoting:
+            Rj = R, np.arange(N, dtype=np.int32)
+        else:
+            Rj = R,
+
+        if mode == 'r':
+            return Rj
+        elif mode == 'raw':
+            qr = np.empty_like(a1, shape=(M, N))
+            tau = np.zeros_like(a1, shape=(K,))
+            return ((qr, tau),) + Rj
+        return (Q,) + Rj
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    if pivoting:
+        geqp3, = get_lapack_funcs(('geqp3',), (a1,))
+        qr, jpvt, tau = safecall(geqp3, "geqp3", a1, overwrite_a=overwrite_a)
+        jpvt -= 1  # geqp3 returns a 1-based index array, so subtract 1
+    else:
+        geqrf, = get_lapack_funcs(('geqrf',), (a1,))
+        qr, tau = safecall(geqrf, "geqrf", a1, lwork=lwork,
+                           overwrite_a=overwrite_a)
+
+    if mode not in ['economic', 'raw'] or M < N:
+        R = np.triu(qr)
+    else:
+        R = np.triu(qr[:N, :])
+
+    if pivoting:
+        Rj = R, jpvt
+    else:
+        Rj = R,
+
+    if mode == 'r':
+        return Rj
+    elif mode == 'raw':
+        return ((qr, tau),) + Rj
+
+    gor_un_gqr, = get_lapack_funcs(('orgqr',), (qr,))
+
+    if M < N:
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr[:, :M], tau,
+                      lwork=lwork, overwrite_a=1)
+    elif mode == 'economic':
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr, tau, lwork=lwork,
+                      overwrite_a=1)
+    else:
+        t = qr.dtype.char
+        qqr = np.empty((M, M), dtype=t)
+        qqr[:, :N] = qr
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qqr, tau, lwork=lwork,
+                      overwrite_a=1)
+
+    return (Q,) + Rj
+
+
+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 data in a is overwritten (may improve performance)
+    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'.
+
+    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, None, "raw", 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:]
+
+
+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 data in a is overwritten (may improve performance)
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py
new file mode 100644
index 0000000000000000000000000000000000000000..39361f172df7f1985c7ed0fbc4d919b5c4545725
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py
@@ -0,0 +1,449 @@
+import warnings
+
+import numpy as np
+from numpy import asarray_chkfinite
+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
+
+
+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 a 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)
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance)
+    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]
+
+
+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.
+    overwrite_b : bool, optional
+        If True, the contents of B are overwritten.
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..8609a175e16d663938386c6b45d190cd0e5dafd8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py
@@ -0,0 +1,334 @@
+"""Schur decomposition functions."""
+import numpy as np
+from numpy import asarray_chkfinite, single, asarray, array
+from numpy.linalg import norm
+
+
+# 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']
+
+
+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).
+    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
+        An 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
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..98425f6c11e727d582102dce72baeb9cbdb6c40b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py
@@ -0,0 +1,534 @@
+"""SVD decomposition functions."""
+import numpy as np
+from numpy import zeros, r_, diag, dot, arccos, arcsin, where, clip
+
+# Local imports.
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs, _compute_lwork
+from ._decomp import _asarray_validated
+
+__all__ = ['svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space']
+
+
+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 `a`; may improve performance.
+        Default is False.
+    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`.
+    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`.
+
+    For ``compute_uv=False``, only ``s`` is returned.
+
+    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.
+
+    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 = np.dot(U, np.dot(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, np.dot(U, np.dot(S, Vh)))
+    True
+
+    >>> s2 = linalg.svd(a, compute_uv=False)
+    >>> np.allclose(s, s2)
+    True
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2:
+        raise ValueError('expected matrix')
+    m, n = a1.shape
+
+    # accommodate empty matrix
+    if a1.size == 0:
+        u0, s0, v0 = svd(np.eye(2, dtype=a1.dtype))
+
+        s = np.empty_like(a1, shape=(0,), dtype=s0.dtype)
+        if full_matrices:
+            u = np.empty_like(a1, shape=(m, m), dtype=u0.dtype)
+            u[...] = np.identity(m)
+            v = np.empty_like(a1, shape=(n, n), dtype=v0.dtype)
+            v[...] = np.identity(n)
+        else:
+            u = np.empty_like(a1, shape=(m, 0), dtype=u0.dtype)
+            v = np.empty_like(a1, shape=(0, n), dtype=v0.dtype)
+        if compute_uv:
+            return u, s, v
+        else:
+            return s
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    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)
+
+    if compute_uv:
+        # XXX: revisit int32 when ILP64 lapack becomes a thing
+        max_mn, min_mn = (m, n) if m > n else (n, m)
+        if full_matrices:
+            if 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. "
+                                  "Try using numpy.linalg.svd instead.")
+        else:
+            sz = max(m * min_mn, n * min_mn)
+            if 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. "
+                                  "Try using numpy.linalg.svd instead.")
+
+    funcs = (lapack_driver, lapack_driver + '_lwork')
+    # XXX: As of 1.14.1 it isn't possible to build SciPy with ILP64,
+    # so the following line always yields a LP64 (32-bit pointer size) variant
+    gesXd, gesXd_lwork = get_lapack_funcs(funcs, (a1,), ilp64="preferred")
+
+    # compute optimal lwork
+    lwork = _compute_lwork(gesXd_lwork, a1.shape[0], a1.shape[1],
+                           compute_uv=compute_uv, full_matrices=full_matrices)
+
+    # perform decomposition
+    u, s, v, info = gesXd(a1, compute_uv=compute_uv, lwork=lwork,
+                          full_matrices=full_matrices, overwrite_a=overwrite_a)
+
+    if info > 0:
+        raise LinAlgError("SVD did not converge")
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal gesdd'
+                         % -info)
+    if compute_uv:
+        return u, s, v
+    else:
+        return 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 `a`; may improve performance.
+        Default is False.
+    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.
+
+    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])
+
+    We can verify the maximum singular value of `m` by computing the maximum
+    length of `m.dot(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.dot(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)
+
+
+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 = diag(s)
+    typ = part.dtype.char
+    MorN = len(s)
+    if MorN == M:
+        return np.hstack((part, zeros((M, N - M), dtype=typ)))
+    elif MorN == N:
+        return r_[part, zeros((M - N, N), dtype=typ)]
+    else:
+        raise ValueError("Length of s must be M or N.")
+
+
+# Orthonormal decomposition
+
+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
+
+
+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.
+    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
+
+
+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
+    --------
+    An Hadamard matrix, which has orthogonal columns, so we expect that
+    the suspace 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 = dot(QA.T.conj(), QB)
+    sigma = svdvals(QA_H_QB)
+
+    # 3. Compute matrix B
+    if QA.shape[1] >= QB.shape[1]:
+        B = QB - dot(QA, QA_H_QB)
+    else:
+        B = QA - 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 = arcsin(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 = where(mask, mu_arcsin, arccos(clip(sigma[::-1], -1., 1.)))
+    return theta
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py
new file mode 100644
index 0000000000000000000000000000000000000000..56ddbc45c3bc47f6beb122e2acadd274ebd9be95
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py
@@ -0,0 +1,413 @@
+"""Frechet derivative of the matrix exponential."""
+import numpy as np
+import scipy.linalg
+
+__all__ = ['expm_frechet', 'expm_cond']
+
+
+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.
+    expm_frechet_AE : ndarray
+        Frechet derivative of the matrix exponential of A in the direction E.
+    For ``compute_expm = False``, only `expm_frechet_AE` is returned.
+
+    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
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h
new file mode 100644
index 0000000000000000000000000000000000000000..676658205e41bcde69e3899e8e065c90738af246
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h
@@ -0,0 +1,1521 @@
+/*
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+*/
+
+#include "npy_cblas.h"
+#include "fortran_defs.h"
+
+typedef int (*_cselect1)(npy_complex64*);
+typedef int (*_cselect2)(npy_complex64*, npy_complex64*);
+typedef int (*_dselect2)(double*, double*);
+typedef int (*_dselect3)(double*, double*, double*);
+typedef int (*_sselect2)(float*, float*);
+typedef int (*_sselect3)(float*, float*, float*);
+typedef int (*_zselect1)(npy_complex128*);
+typedef int (*_zselect2)(npy_complex128*, npy_complex128*);
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void BLAS_FUNC(cbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, float *theta, float *phi, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, float *b11d, float *b11e, float *b12d, float *b12e, float *b21d, float *b21e, float *b22d, float *b22e, float *rwork, int *lrwork, int *info);
+void BLAS_FUNC(cbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, npy_complex64 *vt, int *ldvt, npy_complex64 *u, int *ldu, npy_complex64 *c, int *ldc, float *rwork, int *info);
+void BLAS_FUNC(cgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *pt, int *ldpt, npy_complex64 *c, int *ldc, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbcon)(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbequ)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgbequb)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbsv)(int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, char *equed, float *r, float *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbtf2)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(cgbtrf)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(cgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgebak)(char *job, char *side, int *n, int *ilo, int *ihi, float *scale, int *m, npy_complex64 *v, int *ldv, int *info);
+void BLAS_FUNC(cgebal)(char *job, int *n, npy_complex64 *a, int *lda, int *ilo, int *ihi, float *scale, int *info);
+void BLAS_FUNC(cgebd2)(int *m, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgebrd)(int *m, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgecon)(char *norm, int *n, npy_complex64 *a, int *lda, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgeequ)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgeequb)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgees)(char *jobvs, char *sort, _cselect1 *select, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cgeesx)(char *jobvs, char *sort, _cselect1 *select, char *sense, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cgeev)(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, float *scale, float *abnrm, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgehd2)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgehrd)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgelq2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgelqf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgels)(char *trans, int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgelsd)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *s, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(cgelss)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *s, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgelsy)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *jpvt, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeql2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqlf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqp3)(int *m, int *n, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgeqr2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqr2p)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqrf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqrfp)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqrt)(int *m, int *n, int *nb, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqrt2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(cgeqrt3)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(cgerfs)(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgerq2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgerqf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgesc2)(int *n, npy_complex64 *a, int *lda, npy_complex64 *rhs, int *ipiv, int *jpiv, float *scale);
+void BLAS_FUNC(cgesdd)(char *jobz, int *m, int *n, npy_complex64 *a, int *lda, float *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(cgesv)(int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgesvd)(char *jobu, char *jobvt, int *m, int *n, npy_complex64 *a, int *lda, float *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgesvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, char *equed, float *r, float *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgetc2)(int *n, npy_complex64 *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(cgetf2)(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(cgetrf)(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(cgetri)(int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgetrs)(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cggbak)(char *job, char *side, int *n, int *ilo, int *ihi, float *lscale, float *rscale, int *m, npy_complex64 *v, int *ldv, int *info);
+void BLAS_FUNC(cggbal)(char *job, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *ilo, int *ihi, float *lscale, float *rscale, float *work, int *info);
+void BLAS_FUNC(cgges)(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cggesx)(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(cggev)(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, float *lscale, float *rscale, float *abnrm, float *bbnrm, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(cggglm)(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *d, npy_complex64 *x, npy_complex64 *y, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *info);
+void BLAS_FUNC(cgglse)(int *m, int *n, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, npy_complex64 *d, npy_complex64 *x, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cggqrf)(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cggrqf)(int *m, int *p, int *n, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgtcon)(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgtrfs)(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgtsv)(int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgtsvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgttrf)(int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, int *info);
+void BLAS_FUNC(cgttrs)(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgtts2)(int *itrans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(chbev)(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbevd)(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *x, int *ldx, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chbtrd)(char *vect, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info);
+void BLAS_FUNC(checon)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cheequb)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, npy_complex64 *work, int *info);
+void BLAS_FUNC(cheev)(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, float *w, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cheevd)(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, float *w, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cheevr)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, int *isuppz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cheevx)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chegs2)(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chegst)(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chegv)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *w, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(chegvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *w, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chegvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(cherfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chesv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chesvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cheswapr)(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(chetd2)(char *uplo, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tau, int *info);
+void BLAS_FUNC(chetf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(chetrd)(char *uplo, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(chetri2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetri2x)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info);
+void BLAS_FUNC(chetrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chetrs2)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(chfrk)(char *transr, char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c);
+void BLAS_FUNC(chgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *t, int *ldt, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *info);
+char BLAS_FUNC(chla_transtype)(int *trans);
+void BLAS_FUNC(chpcon)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(chpev)(char *jobz, char *uplo, int *n, npy_complex64 *ap, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpevd)(char *jobz, char *uplo, int *n, npy_complex64 *ap, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chpevx)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chpgst)(int *itype, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, int *info);
+void BLAS_FUNC(chpgv)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpgvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chpgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chpsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chptrd)(char *uplo, int *n, npy_complex64 *ap, float *d, float *e, npy_complex64 *tau, int *info);
+void BLAS_FUNC(chptrf)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info);
+void BLAS_FUNC(chptri)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(chptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chsein)(char *side, char *eigsrc, char *initv, int *select, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(chseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(clabrd)(int *m, int *n, int *nb, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *x, int *ldx, npy_complex64 *y, int *ldy);
+void BLAS_FUNC(clacgv)(int *n, npy_complex64 *x, int *incx);
+void BLAS_FUNC(clacn2)(int *n, npy_complex64 *v, npy_complex64 *x, float *est, int *kase, int *isave);
+void BLAS_FUNC(clacon)(int *n, npy_complex64 *v, npy_complex64 *x, float *est, int *kase);
+void BLAS_FUNC(clacp2)(char *uplo, int *m, int *n, float *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clacpy)(char *uplo, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clacrm)(int *m, int *n, npy_complex64 *a, int *lda, float *b, int *ldb, npy_complex64 *c, int *ldc, float *rwork);
+void BLAS_FUNC(clacrt)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, npy_complex64 *c, npy_complex64 *s);
+void F_FUNC(cladivwrp,CLADIVWRP)(npy_complex64 *out, npy_complex64 *x, npy_complex64 *y);
+void BLAS_FUNC(claed0)(int *qsiz, int *n, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *qstore, int *ldqs, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(claed7)(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, float *d, npy_complex64 *q, int *ldq, float *rho, int *indxq, float *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, npy_complex64 *work, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(claed8)(int *k, int *n, int *qsiz, npy_complex64 *q, int *ldq, float *d, float *rho, int *cutpnt, float *z, float *dlamda, npy_complex64 *q2, int *ldq2, float *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, float *givnum, int *info);
+void BLAS_FUNC(claein)(int *rightv, int *noinit, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *v, npy_complex64 *b, int *ldb, float *rwork, float *eps3, float *smlnum, int *info);
+void BLAS_FUNC(claesy)(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, npy_complex64 *rt1, npy_complex64 *rt2, npy_complex64 *evscal, npy_complex64 *cs1, npy_complex64 *sn1);
+void BLAS_FUNC(claev2)(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, float *rt1, float *rt2, float *cs1, npy_complex64 *sn1);
+void BLAS_FUNC(clag2z)(int *m, int *n, npy_complex64 *sa, int *ldsa, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(clags2)(int *upper, float *a1, npy_complex64 *a2, float *a3, float *b1, npy_complex64 *b2, float *b3, float *csu, npy_complex64 *snu, float *csv, npy_complex64 *snv, float *csq, npy_complex64 *snq);
+void BLAS_FUNC(clagtm)(char *trans, int *n, int *nrhs, float *alpha, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *x, int *ldx, float *beta, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clahef)(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info);
+void BLAS_FUNC(clahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *info);
+void BLAS_FUNC(clahr2)(int *n, int *k, int *nb, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *t, int *ldt, npy_complex64 *y, int *ldy);
+void BLAS_FUNC(claic1)(int *job, int *j, npy_complex64 *x, float *sest, npy_complex64 *w, npy_complex64 *gamma, float *sestpr, npy_complex64 *s, npy_complex64 *c);
+void BLAS_FUNC(clals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *rwork, int *info);
+void BLAS_FUNC(clalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(clalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, float *d, float *e, npy_complex64 *b, int *ldb, float *rcond, int *rank, npy_complex64 *work, float *rwork, int *iwork, int *info);
+float BLAS_FUNC(clangb)(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clange)(char *norm, int *m, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clangt)(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du);
+float BLAS_FUNC(clanhb)(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clanhe)(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clanhf)(char *norm, char *transr, char *uplo, int *n, npy_complex64 *a, float *work);
+float BLAS_FUNC(clanhp)(char *norm, char *uplo, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clanhs)(char *norm, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clanht)(char *norm, int *n, float *d, npy_complex64 *e);
+float BLAS_FUNC(clansb)(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clansp)(char *norm, char *uplo, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clansy)(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clantb)(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clantp)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clantr)(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex64 *a, int *lda, float *work);
+void BLAS_FUNC(clapll)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *ssmin);
+void BLAS_FUNC(clapmr)(int *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k);
+void BLAS_FUNC(clapmt)(int *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k);
+void BLAS_FUNC(claqgb)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(claqge)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(claqhb)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqhe)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqhp)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqp2)(int *m, int *n, int *offset, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, float *vn1, float *vn2, npy_complex64 *work);
+void BLAS_FUNC(claqps)(int *m, int *n, int *offset, int *nb, int *kb, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, float *vn1, float *vn2, npy_complex64 *auxv, npy_complex64 *f, int *ldf);
+void BLAS_FUNC(claqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(claqr1)(int *n, npy_complex64 *h, int *ldh, npy_complex64 *s1, npy_complex64 *s2, npy_complex64 *v);
+void BLAS_FUNC(claqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork);
+void BLAS_FUNC(claqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork);
+void BLAS_FUNC(claqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(claqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex64 *s, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *v, int *ldv, npy_complex64 *u, int *ldu, int *nv, npy_complex64 *wv, int *ldwv, int *nh, npy_complex64 *wh, int *ldwh);
+void BLAS_FUNC(claqsb)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqsp)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqsy)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(clar1v)(int *n, int *b1, int *bn, float *lambda_, float *d, float *l, float *ld, float *lld, float *pivmin, float *gaptol, npy_complex64 *z, int *wantnc, int *negcnt, float *ztz, float *mingma, int *r, int *isuppz, float *nrminv, float *resid, float *rqcorr, float *work);
+void BLAS_FUNC(clar2v)(int *n, npy_complex64 *x, npy_complex64 *y, npy_complex64 *z, int *incx, float *c, npy_complex64 *s, int *incc);
+void BLAS_FUNC(clarcm)(int *m, int *n, float *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, float *rwork);
+void BLAS_FUNC(clarf)(char *side, int *m, int *n, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(clarfg)(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau);
+void BLAS_FUNC(clarfgp)(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau);
+void BLAS_FUNC(clarft)(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt);
+void BLAS_FUNC(clarfx)(char *side, int *m, int *n, npy_complex64 *v, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clargv)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *c, int *incc);
+void BLAS_FUNC(clarnv)(int *idist, int *iseed, int *n, npy_complex64 *x);
+void BLAS_FUNC(clarrv)(int *n, float *vl, float *vu, float *d, float *l, float *pivmin, int *isplit, int *m, int *dol, int *dou, float *minrgp, float *rtol1, float *rtol2, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, npy_complex64 *z, int *ldz, int *isuppz, float *work, int *iwork, int *info);
+void BLAS_FUNC(clartg)(npy_complex64 *f, npy_complex64 *g, float *cs, npy_complex64 *sn, npy_complex64 *r);
+void BLAS_FUNC(clartv)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *c, npy_complex64 *s, int *incc);
+void BLAS_FUNC(clarz)(char *side, int *m, int *n, int *l, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(clarzt)(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt);
+void BLAS_FUNC(clascl)(char *type_bn, int *kl, int *ku, float *cfrom, float *cto, int *m, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(claset)(char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *a, int *lda);
+void BLAS_FUNC(clasr)(char *side, char *pivot, char *direct, int *m, int *n, float *c, float *s, npy_complex64 *a, int *lda);
+void BLAS_FUNC(classq)(int *n, npy_complex64 *x, int *incx, float *scale, float *sumsq);
+void BLAS_FUNC(claswp)(int *n, npy_complex64 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(clasyf)(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info);
+void BLAS_FUNC(clatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatdf)(int *ijob, int *n, npy_complex64 *z, int *ldz, npy_complex64 *rhs, float *rdsum, float *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(clatps)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *ap, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatrd)(char *uplo, int *n, int *nb, npy_complex64 *a, int *lda, float *e, npy_complex64 *tau, npy_complex64 *w, int *ldw);
+void BLAS_FUNC(clatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatrz)(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work);
+void BLAS_FUNC(clauu2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(clauum)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpbcon)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbequ)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpbrfs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbstf)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbsv)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbtf2)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbtrf)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbtrs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpftrf)(char *transr, char *uplo, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(cpftri)(char *transr, char *uplo, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(cpftrs)(char *transr, char *uplo, int *n, int *nrhs, npy_complex64 *a, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpocon)(char *uplo, int *n, npy_complex64 *a, int *lda, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpoequ)(int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpoequb)(int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cporfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cposv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cposvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpotf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cppcon)(char *uplo, int *n, npy_complex64 *ap, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cppequ)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cppsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cppsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpptrf)(char *uplo, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(cpptri)(char *uplo, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(cpptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpstf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(cpstrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(cptcon)(int *n, float *d, npy_complex64 *e, float *anorm, float *rcond, float *rwork, int *info);
+void BLAS_FUNC(cpteqr)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(cptrfs)(char *uplo, int *n, int *nrhs, float *d, npy_complex64 *e, float *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cptsv)(int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cptsvx)(char *fact, int *n, int *nrhs, float *d, npy_complex64 *e, float *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpttrf)(int *n, float *d, npy_complex64 *e, int *info);
+void BLAS_FUNC(cpttrs)(char *uplo, int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cptts2)(int *iuplo, int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(crot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, npy_complex64 *s);
+void BLAS_FUNC(cspcon)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cspmv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cspr)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap);
+void BLAS_FUNC(csprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cspsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cspsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(csptrf)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info);
+void BLAS_FUNC(csptri)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(csrscl)(int *n, float *sa, npy_complex64 *sx, int *incx);
+void BLAS_FUNC(cstedc)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cstegr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cstein)(int *n, float *d, float *e, int *m, float *w, int *iblock, int *isplit, npy_complex64 *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(cstemr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, int *m, float *w, npy_complex64 *z, int *ldz, int *nzc, int *isuppz, int *tryrac, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(csteqr)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(csycon)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(csyconv)(char *uplo, char *way, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csyequb)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, npy_complex64 *work, int *info);
+void BLAS_FUNC(csymv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(csyr)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda);
+void BLAS_FUNC(csyrfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(csysv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csysvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(csyswapr)(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(csytf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(csytrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csytri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csytri2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csytri2x)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info);
+void BLAS_FUNC(csytrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(csytrs2)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex64 *ab, int *ldab, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctftri)(char *transr, char *uplo, char *diag, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(ctfttp)(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctfttr)(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctgevc)(char *side, char *howmny, int *select, int *n, npy_complex64 *s, int *lds, npy_complex64 *p, int *ldp, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctgex2)(int *wantq, int *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *j1, int *info);
+void BLAS_FUNC(ctgexc)(int *wantq, int *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ctgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *m, float *pl, float *pr, float *dif, npy_complex64 *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ctgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *tola, float *tolb, float *alpha, float *beta, npy_complex64 *u, int *ldu, npy_complex64 *v, int *ldv, npy_complex64 *q, int *ldq, npy_complex64 *work, int *ncycle, int *info);
+void BLAS_FUNC(ctgsna)(char *job, char *howmny, int *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, float *s, float *dif, int *mm, int *m, npy_complex64 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ctgsy2)(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, float *scale, float *rdsum, float *rdscal, int *info);
+void BLAS_FUNC(ctgsyl)(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, float *scale, float *dif, npy_complex64 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ctpcon)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctpqrt)(int *m, int *n, int *l, int *nb, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctpqrt2)(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(ctprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(ctprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctptri)(char *uplo, char *diag, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctpttf)(char *transr, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *arf, int *info);
+void BLAS_FUNC(ctpttr)(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrcon)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrevc)(char *side, char *howmny, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrexc)(char *compq, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ctrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrsen)(char *job, char *compq, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, npy_complex64 *w, int *m, float *s, float *sep, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(ctrsna)(char *job, char *howmny, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, float *s, float *sep, int *mm, int *m, npy_complex64 *work, int *ldwork, float *rwork, int *info);
+void BLAS_FUNC(ctrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, float *scale, int *info);
+void BLAS_FUNC(ctrti2)(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrtri)(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctrttf)(char *transr, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *arf, int *info);
+void BLAS_FUNC(ctrttp)(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctzrzf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunbdb)(char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, float *theta, float *phi, npy_complex64 *taup1, npy_complex64 *taup2, npy_complex64 *tauq1, npy_complex64 *tauq2, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cuncsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, float *theta, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *info);
+void BLAS_FUNC(cung2l)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cung2r)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cungbr)(char *vect, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunghr)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungl2)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunglq)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungql)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungqr)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungr2)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cungrq)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungtr)(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunm2l)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunm2r)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunml2)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmlq)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmql)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmqr)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmr2)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmr3)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmrq)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmrz)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cupgtr)(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info);
+void BLAS_FUNC(cupmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(dbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, double *theta, double *phi, double *u1, int *ldu1, double *u2, int *ldu2, double *v1t, int *ldv1t, double *v2t, int *ldv2t, double *b11d, double *b11e, double *b12d, double *b12e, double *b21d, double *b21e, double *b22d, double *b22e, double *work, int *lwork, int *info);
+void BLAS_FUNC(dbdsdc)(char *uplo, char *compq, int *n, double *d, double *e, double *u, int *ldu, double *vt, int *ldvt, double *q, int *iq, double *work, int *iwork, int *info);
+void BLAS_FUNC(dbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, double *vt, int *ldvt, double *u, int *ldu, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(ddisna)(char *job, int *m, int *n, double *d, double *sep, int *info);
+void BLAS_FUNC(dgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, double *ab, int *ldab, double *d, double *e, double *q, int *ldq, double *pt, int *ldpt, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dgbcon)(char *norm, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbequ)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgbequb)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbsv)(int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, int *ipiv, char *equed, double *r, double *c, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbtf2)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(dgbtrf)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(dgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgebak)(char *job, char *side, int *n, int *ilo, int *ihi, double *scale, int *m, double *v, int *ldv, int *info);
+void BLAS_FUNC(dgebal)(char *job, int *n, double *a, int *lda, int *ilo, int *ihi, double *scale, int *info);
+void BLAS_FUNC(dgebd2)(int *m, int *n, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *work, int *info);
+void BLAS_FUNC(dgebrd)(int *m, int *n, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgecon)(char *norm, int *n, double *a, int *lda, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgeequ)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgeequb)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgees)(char *jobvs, char *sort, _dselect2 *select, int *n, double *a, int *lda, int *sdim, double *wr, double *wi, double *vs, int *ldvs, double *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(dgeesx)(char *jobvs, char *sort, _dselect2 *select, char *sense, int *n, double *a, int *lda, int *sdim, double *wr, double *wi, double *vs, int *ldvs, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(dgeev)(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, double *a, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, int *ilo, int *ihi, double *scale, double *abnrm, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgehd2)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgehrd)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgejsv)(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, double *a, int *lda, double *sva, double *u, int *ldu, double *v, int *ldv, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgelq2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgelqf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgels)(char *trans, int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgelsd)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *s, double *rcond, int *rank, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgelss)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *s, double *rcond, int *rank, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgelsy)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *jpvt, double *rcond, int *rank, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dgeql2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqlf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqp3)(int *m, int *n, double *a, int *lda, int *jpvt, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqr2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqr2p)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqrf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqrfp)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqrt)(int *m, int *n, int *nb, double *a, int *lda, double *t, int *ldt, double *work, int *info);
+void BLAS_FUNC(dgeqrt2)(int *m, int *n, double *a, int *lda, double *t, int *ldt, int *info);
+void BLAS_FUNC(dgeqrt3)(int *m, int *n, double *a, int *lda, double *t, int *ldt, int *info);
+void BLAS_FUNC(dgerfs)(char *trans, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgerq2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgerqf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesc2)(int *n, double *a, int *lda, double *rhs, int *ipiv, int *jpiv, double *scale);
+void BLAS_FUNC(dgesdd)(char *jobz, int *m, int *n, double *a, int *lda, double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgesv)(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgesvd)(char *jobu, char *jobvt, int *m, int *n, double *a, int *lda, double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesvj)(char *joba, char *jobu, char *jobv, int *m, int *n, double *a, int *lda, double *sva, int *mv, double *v, int *ldv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesvx)(char *fact, char *trans, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, char *equed, double *r, double *c, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgetc2)(int *n, double *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(dgetf2)(int *m, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dgetrf)(int *m, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dgetri)(int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgetrs)(char *trans, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dggbak)(char *job, char *side, int *n, int *ilo, int *ihi, double *lscale, double *rscale, int *m, double *v, int *ldv, int *info);
+void BLAS_FUNC(dggbal)(char *job, int *n, double *a, int *lda, double *b, int *ldb, int *ilo, int *ihi, double *lscale, double *rscale, double *work, int *info);
+void BLAS_FUNC(dgges)(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, int *n, double *a, int *lda, double *b, int *ldb, int *sdim, double *alphar, double *alphai, double *beta, double *vsl, int *ldvsl, double *vsr, int *ldvsr, double *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(dggesx)(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, char *sense, int *n, double *a, int *lda, double *b, int *ldb, int *sdim, double *alphar, double *alphai, double *beta, double *vsl, int *ldvsl, double *vsr, int *ldvsr, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(dggev)(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *vl, int *ldvl, double *vr, int *ldvr, int *ilo, int *ihi, double *lscale, double *rscale, double *abnrm, double *bbnrm, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(dggglm)(int *n, int *m, int *p, double *a, int *lda, double *b, int *ldb, double *d, double *x, double *y, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *info);
+void BLAS_FUNC(dgglse)(int *m, int *n, int *p, double *a, int *lda, double *b, int *ldb, double *c, double *d, double *x, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggqrf)(int *n, int *m, int *p, double *a, int *lda, double *taua, double *b, int *ldb, double *taub, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggrqf)(int *m, int *p, int *n, double *a, int *lda, double *taua, double *b, int *ldb, double *taub, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgsvj0)(char *jobv, int *m, int *n, double *a, int *lda, double *d, double *sva, int *mv, double *v, int *ldv, double *eps, double *sfmin, double *tol, int *nsweep, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgsvj1)(char *jobv, int *m, int *n, int *n1, double *a, int *lda, double *d, double *sva, int *mv, double *v, int *ldv, double *eps, double *sfmin, double *tol, int *nsweep, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgtcon)(char *norm, int *n, double *dl, double *d, double *du, double *du2, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgtrfs)(char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *dlf, double *df, double *duf, double *du2, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgtsv)(int *n, int *nrhs, double *dl, double *d, double *du, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgtsvx)(char *fact, char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *dlf, double *df, double *duf, double *du2, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgttrf)(int *n, double *dl, double *d, double *du, double *du2, int *ipiv, int *info);
+void BLAS_FUNC(dgttrs)(char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *du2, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgtts2)(int *itrans, int *n, int *nrhs, double *dl, double *d, double *du, double *du2, int *ipiv, double *b, int *ldb);
+void BLAS_FUNC(dhgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *t, int *ldt, double *alphar, double *alphai, double *beta, double *q, int *ldq, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dhsein)(char *side, char *eigsrc, char *initv, int *select, int *n, double *h, int *ldh, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(dhseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, double *z, int *ldz, double *work, int *lwork, int *info);
+int BLAS_FUNC(disnan)(double *din);
+void BLAS_FUNC(dlabad)(double *small, double *large);
+void BLAS_FUNC(dlabrd)(int *m, int *n, int *nb, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *x, int *ldx, double *y, int *ldy);
+void BLAS_FUNC(dlacn2)(int *n, double *v, double *x, int *isgn, double *est, int *kase, int *isave);
+void BLAS_FUNC(dlacon)(int *n, double *v, double *x, int *isgn, double *est, int *kase);
+void BLAS_FUNC(dlacpy)(char *uplo, int *m, int *n, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dladiv)(double *a, double *b, double *c, double *d, double *p, double *q);
+void BLAS_FUNC(dlae2)(double *a, double *b, double *c, double *rt1, double *rt2);
+void BLAS_FUNC(dlaebz)(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, double *abstol, double *reltol, double *pivmin, double *d, double *e, double *e2, int *nval, double *ab, double *c, int *mout, int *nab, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed0)(int *icompq, int *qsiz, int *n, double *d, double *e, double *q, int *ldq, double *qstore, int *ldqs, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed1)(int *n, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed2)(int *k, int *n, int *n1, double *d, double *q, int *ldq, int *indxq, double *rho, double *z, double *dlamda, double *w, double *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info);
+void BLAS_FUNC(dlaed3)(int *k, int *n, int *n1, double *d, double *q, int *ldq, double *rho, double *dlamda, double *q2, int *indx, int *ctot, double *w, double *s, int *info);
+void BLAS_FUNC(dlaed4)(int *n, int *i, double *d, double *z, double *delta, double *rho, double *dlam, int *info);
+void BLAS_FUNC(dlaed5)(int *i, double *d, double *z, double *delta, double *rho, double *dlam);
+void BLAS_FUNC(dlaed6)(int *kniter, int *orgati, double *rho, double *d, double *z, double *finit, double *tau, int *info);
+void BLAS_FUNC(dlaed7)(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed8)(int *icompq, int *k, int *n, int *qsiz, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *z, double *dlamda, double *q2, int *ldq2, double *w, int *perm, int *givptr, int *givcol, double *givnum, int *indxp, int *indx, int *info);
+void BLAS_FUNC(dlaed9)(int *k, int *kstart, int *kstop, int *n, double *d, double *q, int *ldq, double *rho, double *dlamda, double *w, double *s, int *lds, int *info);
+void BLAS_FUNC(dlaeda)(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, double *q, int *qptr, double *z, double *ztemp, int *info);
+void BLAS_FUNC(dlaein)(int *rightv, int *noinit, int *n, double *h, int *ldh, double *wr, double *wi, double *vr, double *vi, double *b, int *ldb, double *work, double *eps3, double *smlnum, double *bignum, int *info);
+void BLAS_FUNC(dlaev2)(double *a, double *b, double *c, double *rt1, double *rt2, double *cs1, double *sn1);
+void BLAS_FUNC(dlaexc)(int *wantq, int *n, double *t, int *ldt, double *q, int *ldq, int *j1, int *n1, int *n2, double *work, int *info);
+void BLAS_FUNC(dlag2)(double *a, int *lda, double *b, int *ldb, double *safmin, double *scale1, double *scale2, double *wr1, double *wr2, double *wi);
+void BLAS_FUNC(dlag2s)(int *m, int *n, double *a, int *lda, float *sa, int *ldsa, int *info);
+void BLAS_FUNC(dlags2)(int *upper, double *a1, double *a2, double *a3, double *b1, double *b2, double *b3, double *csu, double *snu, double *csv, double *snv, double *csq, double *snq);
+void BLAS_FUNC(dlagtf)(int *n, double *a, double *lambda_, double *b, double *c, double *tol, double *d, int *in_, int *info);
+void BLAS_FUNC(dlagtm)(char *trans, int *n, int *nrhs, double *alpha, double *dl, double *d, double *du, double *x, int *ldx, double *beta, double *b, int *ldb);
+void BLAS_FUNC(dlagts)(int *job, int *n, double *a, double *b, double *c, double *d, int *in_, double *y, double *tol, int *info);
+void BLAS_FUNC(dlagv2)(double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *csl, double *snl, double *csr, double *snr);
+void BLAS_FUNC(dlahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, int *info);
+void BLAS_FUNC(dlahr2)(int *n, int *k, int *nb, double *a, int *lda, double *tau, double *t, int *ldt, double *y, int *ldy);
+void BLAS_FUNC(dlaic1)(int *job, int *j, double *x, double *sest, double *w, double *gamma, double *sestpr, double *s, double *c);
+void BLAS_FUNC(dlaln2)(int *ltrans, int *na, int *nw, double *smin, double *ca, double *a, int *lda, double *d1, double *d2, double *b, int *ldb, double *wr, double *wi, double *x, int *ldx, double *scale, double *xnorm, int *info);
+void BLAS_FUNC(dlals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, double *b, int *ldb, double *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *work, int *info);
+void BLAS_FUNC(dlalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, double *b, int *ldb, double *bx, int *ldbx, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, double *d, double *e, double *b, int *ldb, double *rcond, int *rank, double *work, int *iwork, int *info);
+double BLAS_FUNC(dlamch)(char *cmach);
+void BLAS_FUNC(dlamrg)(int *n1, int *n2, double *a, int *dtrd1, int *dtrd2, int *index_bn);
+int BLAS_FUNC(dlaneg)(int *n, double *d, double *lld, double *sigma, double *pivmin, int *r);
+double BLAS_FUNC(dlangb)(char *norm, int *n, int *kl, int *ku, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlange)(char *norm, int *m, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlangt)(char *norm, int *n, double *dl, double *d_, double *du);
+double BLAS_FUNC(dlanhs)(char *norm, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlansb)(char *norm, char *uplo, int *n, int *k, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlansf)(char *norm, char *transr, char *uplo, int *n, double *a, double *work);
+double BLAS_FUNC(dlansp)(char *norm, char *uplo, int *n, double *ap, double *work);
+double BLAS_FUNC(dlanst)(char *norm, int *n, double *d_, double *e);
+double BLAS_FUNC(dlansy)(char *norm, char *uplo, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlantb)(char *norm, char *uplo, char *diag, int *n, int *k, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlantp)(char *norm, char *uplo, char *diag, int *n, double *ap, double *work);
+double BLAS_FUNC(dlantr)(char *norm, char *uplo, char *diag, int *m, int *n, double *a, int *lda, double *work);
+void BLAS_FUNC(dlanv2)(double *a, double *b, double *c, double *d, double *rt1r, double *rt1i, double *rt2r, double *rt2i, double *cs, double *sn);
+void BLAS_FUNC(dlapll)(int *n, double *x, int *incx, double *y, int *incy, double *ssmin);
+void BLAS_FUNC(dlapmr)(int *forwrd, int *m, int *n, double *x, int *ldx, int *k);
+void BLAS_FUNC(dlapmt)(int *forwrd, int *m, int *n, double *x, int *ldx, int *k);
+double BLAS_FUNC(dlapy2)(double *x, double *y);
+double BLAS_FUNC(dlapy3)(double *x, double *y, double *z);
+void BLAS_FUNC(dlaqgb)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(dlaqge)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(dlaqp2)(int *m, int *n, int *offset, double *a, int *lda, int *jpvt, double *tau, double *vn1, double *vn2, double *work);
+void BLAS_FUNC(dlaqps)(int *m, int *n, int *offset, int *nb, int *kb, double *a, int *lda, int *jpvt, double *tau, double *vn1, double *vn2, double *auxv, double *f, int *ldf);
+void BLAS_FUNC(dlaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dlaqr1)(int *n, double *h, int *ldh, double *sr1, double *si1, double *sr2, double *si2, double *v);
+void BLAS_FUNC(dlaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, int *ns, int *nd, double *sr, double *si, double *v, int *ldv, int *nh, double *t, int *ldt, int *nv, double *wv, int *ldwv, double *work, int *lwork);
+void BLAS_FUNC(dlaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, int *ns, int *nd, double *sr, double *si, double *v, int *ldv, int *nh, double *t, int *ldt, int *nv, double *wv, int *ldwv, double *work, int *lwork);
+void BLAS_FUNC(dlaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dlaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, double *sr, double *si, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, double *v, int *ldv, double *u, int *ldu, int *nv, double *wv, int *ldwv, int *nh, double *wh, int *ldwh);
+void BLAS_FUNC(dlaqsb)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqsp)(char *uplo, int *n, double *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqsy)(char *uplo, int *n, double *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqtr)(int *ltran, int *lreal, int *n, double *t, int *ldt, double *b, double *w, double *scale, double *x, double *work, int *info);
+void BLAS_FUNC(dlar1v)(int *n, int *b1, int *bn, double *lambda_, double *d, double *l, double *ld, double *lld, double *pivmin, double *gaptol, double *z, int *wantnc, int *negcnt, double *ztz, double *mingma, int *r, int *isuppz, double *nrminv, double *resid, double *rqcorr, double *work);
+void BLAS_FUNC(dlar2v)(int *n, double *x, double *y, double *z, int *incx, double *c, double *s, int *incc);
+void BLAS_FUNC(dlarf)(char *side, int *m, int *n, double *v, int *incv, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *ldwork);
+void BLAS_FUNC(dlarfg)(int *n, double *alpha, double *x, int *incx, double *tau);
+void BLAS_FUNC(dlarfgp)(int *n, double *alpha, double *x, int *incx, double *tau);
+void BLAS_FUNC(dlarft)(char *direct, char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt);
+void BLAS_FUNC(dlarfx)(char *side, int *m, int *n, double *v, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlargv)(int *n, double *x, int *incx, double *y, int *incy, double *c, int *incc);
+void BLAS_FUNC(dlarnv)(int *idist, int *iseed, int *n, double *x);
+void BLAS_FUNC(dlarra)(int *n, double *d, double *e, double *e2, double *spltol, double *tnrm, int *nsplit, int *isplit, int *info);
+void BLAS_FUNC(dlarrb)(int *n, double *d, double *lld, int *ifirst, int *ilast, double *rtol1, double *rtol2, int *offset, double *w, double *wgap, double *werr, double *work, int *iwork, double *pivmin, double *spdiam, int *twist, int *info);
+void BLAS_FUNC(dlarrc)(char *jobt, int *n, double *vl, double *vu, double *d, double *e, double *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info);
+void BLAS_FUNC(dlarrd)(char *range, char *order, int *n, double *vl, double *vu, int *il, int *iu, double *gers, double *reltol, double *d, double *e, double *e2, double *pivmin, int *nsplit, int *isplit, int *m, double *w, double *werr, double *wl, double *wu, int *iblock, int *indexw, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlarre)(char *range, int *n, double *vl, double *vu, int *il, int *iu, double *d, double *e, double *e2, double *rtol1, double *rtol2, double *spltol, int *nsplit, int *isplit, int *m, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, double *pivmin, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlarrf)(int *n, double *d, double *l, double *ld, int *clstrt, int *clend, double *w, double *wgap, double *werr, double *spdiam, double *clgapl, double *clgapr, double *pivmin, double *sigma, double *dplus, double *lplus, double *work, int *info);
+void BLAS_FUNC(dlarrj)(int *n, double *d, double *e2, int *ifirst, int *ilast, double *rtol, int *offset, double *w, double *werr, double *work, int *iwork, double *pivmin, double *spdiam, int *info);
+void BLAS_FUNC(dlarrk)(int *n, int *iw, double *gl, double *gu, double *d, double *e2, double *pivmin, double *reltol, double *w, double *werr, int *info);
+void BLAS_FUNC(dlarrr)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dlarrv)(int *n, double *vl, double *vu, double *d, double *l, double *pivmin, int *isplit, int *m, int *dol, int *dou, double *minrgp, double *rtol1, double *rtol2, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, double *z, int *ldz, int *isuppz, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlartg)(double *f, double *g, double *cs, double *sn, double *r);
+void BLAS_FUNC(dlartgp)(double *f, double *g, double *cs, double *sn, double *r);
+void BLAS_FUNC(dlartgs)(double *x, double *y, double *sigma, double *cs, double *sn);
+void BLAS_FUNC(dlartv)(int *n, double *x, int *incx, double *y, int *incy, double *c, double *s, int *incc);
+void BLAS_FUNC(dlaruv)(int *iseed, int *n, double *x);
+void BLAS_FUNC(dlarz)(char *side, int *m, int *n, int *l, double *v, int *incv, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *ldwork);
+void BLAS_FUNC(dlarzt)(char *direct, char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt);
+void BLAS_FUNC(dlas2)(double *f, double *g, double *h, double *ssmin, double *ssmax);
+void BLAS_FUNC(dlascl)(char *type_bn, int *kl, int *ku, double *cfrom, double *cto, int *m, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dlasd0)(int *n, int *sqre, double *d, double *e, double *u, int *ldu, double *vt, int *ldvt, int *smlsiz, int *iwork, double *work, int *info);
+void BLAS_FUNC(dlasd1)(int *nl, int *nr, int *sqre, double *d, double *alpha, double *beta, double *u, int *ldu, double *vt, int *ldvt, int *idxq, int *iwork, double *work, int *info);
+void BLAS_FUNC(dlasd2)(int *nl, int *nr, int *sqre, int *k, double *d, double *z, double *alpha, double *beta, double *u, int *ldu, double *vt, int *ldvt, double *dsigma, double *u2, int *ldu2, double *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info);
+void BLAS_FUNC(dlasd3)(int *nl, int *nr, int *sqre, int *k, double *d, double *q, int *ldq, double *dsigma, double *u, int *ldu, double *u2, int *ldu2, double *vt, int *ldvt, double *vt2, int *ldvt2, int *idxc, int *ctot, double *z, int *info);
+void BLAS_FUNC(dlasd4)(int *n, int *i, double *d, double *z, double *delta, double *rho, double *sigma, double *work, int *info);
+void BLAS_FUNC(dlasd5)(int *i, double *d, double *z, double *delta, double *rho, double *dsigma, double *work);
+void BLAS_FUNC(dlasd6)(int *icompq, int *nl, int *nr, int *sqre, double *d, double *vf, double *vl, double *alpha, double *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlasd7)(int *icompq, int *nl, int *nr, int *sqre, int *k, double *d, double *z, double *zw, double *vf, double *vfw, double *vl, double *vlw, double *alpha, double *beta, double *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *c, double *s, int *info);
+void BLAS_FUNC(dlasd8)(int *icompq, int *k, double *d, double *z, double *vf, double *vl, double *difl, double *difr, int *lddifr, double *dsigma, double *work, int *info);
+void BLAS_FUNC(dlasda)(int *icompq, int *smlsiz, int *n, int *sqre, double *d, double *e, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlasdq)(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, double *vt, int *ldvt, double *u, int *ldu, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dlasdt)(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub);
+void BLAS_FUNC(dlaset)(char *uplo, int *m, int *n, double *alpha, double *beta, double *a, int *lda);
+void BLAS_FUNC(dlasq1)(int *n, double *d, double *e, double *work, int *info);
+void BLAS_FUNC(dlasq2)(int *n, double *z, int *info);
+void BLAS_FUNC(dlasq3)(int *i0, int *n0, double *z, int *pp, double *dmin, double *sigma, double *desig, double *qmax, int *nfail, int *iter, int *ndiv, int *ieee, int *ttype, double *dmin1, double *dmin2, double *dn, double *dn1, double *dn2, double *g, double *tau);
+void BLAS_FUNC(dlasq4)(int *i0, int *n0, double *z, int *pp, int *n0in, double *dmin, double *dmin1, double *dmin2, double *dn, double *dn1, double *dn2, double *tau, int *ttype, double *g);
+void BLAS_FUNC(dlasq6)(int *i0, int *n0, double *z, int *pp, double *dmin, double *dmin1, double *dmin2, double *dn, double *dnm1, double *dnm2);
+void BLAS_FUNC(dlasr)(char *side, char *pivot, char *direct, int *m, int *n, double *c, double *s, double *a, int *lda);
+void BLAS_FUNC(dlasrt)(char *id, int *n, double *d, int *info);
+void BLAS_FUNC(dlassq)(int *n, double *x, int *incx, double *scale, double *sumsq);
+void BLAS_FUNC(dlasv2)(double *f, double *g, double *h, double *ssmin, double *ssmax, double *snr, double *csr, double *snl, double *csl);
+void BLAS_FUNC(dlaswp)(int *n, double *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(dlasy2)(int *ltranl, int *ltranr, int *isgn, int *n1, int *n2, double *tl, int *ldtl, double *tr, int *ldtr, double *b, int *ldb, double *scale, double *x, int *ldx, double *xnorm, int *info);
+void BLAS_FUNC(dlasyf)(char *uplo, int *n, int *nb, int *kb, double *a, int *lda, int *ipiv, double *w, int *ldw, int *info);
+void BLAS_FUNC(dlat2s)(char *uplo, int *n, double *a, int *lda, float *sa, int *ldsa, int *info);
+void BLAS_FUNC(dlatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, double *ab, int *ldab, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatdf)(int *ijob, int *n, double *z, int *ldz, double *rhs, double *rdsum, double *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(dlatps)(char *uplo, char *trans, char *diag, char *normin, int *n, double *ap, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatrd)(char *uplo, int *n, int *nb, double *a, int *lda, double *e, double *tau, double *w, int *ldw);
+void BLAS_FUNC(dlatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, double *a, int *lda, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatrz)(int *m, int *n, int *l, double *a, int *lda, double *tau, double *work);
+void BLAS_FUNC(dlauu2)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dlauum)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dopgtr)(char *uplo, int *n, double *ap, double *tau, double *q, int *ldq, double *work, int *info);
+void BLAS_FUNC(dopmtr)(char *side, char *uplo, char *trans, int *m, int *n, double *ap, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dorbdb)(char *trans, char *signs, int *m, int *p, int *q, double *x11, int *ldx11, double *x12, int *ldx12, double *x21, int *ldx21, double *x22, int *ldx22, double *theta, double *phi, double *taup1, double *taup2, double *tauq1, double *tauq2, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, double *x11, int *ldx11, double *x12, int *ldx12, double *x21, int *ldx21, double *x22, int *ldx22, double *theta, double *u1, int *ldu1, double *u2, int *ldu2, double *v1t, int *ldv1t, double *v2t, int *ldv2t, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dorg2l)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorg2r)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorgbr)(char *vect, int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorghr)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgl2)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorglq)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgql)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgqr)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgr2)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorgrq)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgtr)(char *uplo, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorm2l)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dorm2r)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorml2)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormlq)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormql)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormqr)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormr2)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormr3)(char *side, char *trans, int *m, int *n, int *k, int *l, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormrq)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormrz)(char *side, char *trans, int *m, int *n, int *k, int *l, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormtr)(char *side, char *uplo, char *trans, int *m, int *n, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dpbcon)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbequ)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpbrfs)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbstf)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbsv)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbtf2)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbtrf)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbtrs)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpftrf)(char *transr, char *uplo, int *n, double *a, int *info);
+void BLAS_FUNC(dpftri)(char *transr, char *uplo, int *n, double *a, int *info);
+void BLAS_FUNC(dpftrs)(char *transr, char *uplo, int *n, int *nrhs, double *a, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpocon)(char *uplo, int *n, double *a, int *lda, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpoequ)(int *n, double *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpoequb)(int *n, double *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dporfs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dposv)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dposvx)(char *fact, char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpotf2)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotrf)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotri)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotrs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dppcon)(char *uplo, int *n, double *ap, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dppequ)(char *uplo, int *n, double *ap, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpprfs)(char *uplo, int *n, int *nrhs, double *ap, double *afp, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dppsv)(char *uplo, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dppsvx)(char *fact, char *uplo, int *n, int *nrhs, double *ap, double *afp, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpptrf)(char *uplo, int *n, double *ap, int *info);
+void BLAS_FUNC(dpptri)(char *uplo, int *n, double *ap, int *info);
+void BLAS_FUNC(dpptrs)(char *uplo, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpstf2)(char *uplo, int *n, double *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(dpstrf)(char *uplo, int *n, double *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(dptcon)(int *n, double *d, double *e, double *anorm, double *rcond, double *work, int *info);
+void BLAS_FUNC(dpteqr)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dptrfs)(int *n, int *nrhs, double *d, double *e, double *df, double *ef, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *info);
+void BLAS_FUNC(dptsv)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb, int *info);
+void BLAS_FUNC(dptsvx)(char *fact, int *n, int *nrhs, double *d, double *e, double *df, double *ef, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *info);
+void BLAS_FUNC(dpttrf)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dpttrs)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb, int *info);
+void BLAS_FUNC(dptts2)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb);
+void BLAS_FUNC(drscl)(int *n, double *sa, double *sx, int *incx);
+void BLAS_FUNC(dsbev)(char *jobz, char *uplo, int *n, int *kd, double *ab, int *ldab, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsbevd)(char *jobz, char *uplo, int *n, int *kd, double *ab, int *ldab, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, double *ab, int *ldab, double *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *x, int *ldx, double *work, int *info);
+void BLAS_FUNC(dsbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsbtrd)(char *vect, char *uplo, int *n, int *kd, double *ab, int *ldab, double *d, double *e, double *q, int *ldq, double *work, int *info);
+void BLAS_FUNC(dsfrk)(char *transr, char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c);
+void BLAS_FUNC(dsgesv)(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *work, float *swork, int *iter, int *info);
+void BLAS_FUNC(dspcon)(char *uplo, int *n, double *ap, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dspev)(char *jobz, char *uplo, int *n, double *ap, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dspevd)(char *jobz, char *uplo, int *n, double *ap, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dspevx)(char *jobz, char *range, char *uplo, int *n, double *ap, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dspgst)(int *itype, char *uplo, int *n, double *ap, double *bp, int *info);
+void BLAS_FUNC(dspgv)(int *itype, char *jobz, char *uplo, int *n, double *ap, double *bp, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dspgvd)(int *itype, char *jobz, char *uplo, int *n, double *ap, double *bp, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dspgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, double *ap, double *bp, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsposv)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *x, int *ldx, double *work, float *swork, int *iter, int *info);
+void BLAS_FUNC(dsprfs)(char *uplo, int *n, int *nrhs, double *ap, double *afp, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dspsv)(char *uplo, int *n, int *nrhs, double *ap, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dspsvx)(char *fact, char *uplo, int *n, int *nrhs, double *ap, double *afp, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsptrd)(char *uplo, int *n, double *ap, double *d, double *e, double *tau, int *info);
+void BLAS_FUNC(dsptrf)(char *uplo, int *n, double *ap, int *ipiv, int *info);
+void BLAS_FUNC(dsptri)(char *uplo, int *n, double *ap, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsptrs)(char *uplo, int *n, int *nrhs, double *ap, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dstebz)(char *range, char *order, int *n, double *vl, double *vu, int *il, int *iu, double *abstol, double *d, double *e, int *m, int *nsplit, double *w, int *iblock, int *isplit, double *work, int *iwork, int *info);
+void BLAS_FUNC(dstedc)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstegr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstein)(int *n, double *d, double *e, int *m, double *w, int *iblock, int *isplit, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dstemr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, int *m, double *w, double *z, int *ldz, int *nzc, int *isuppz, int *tryrac, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsteqr)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsterf)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dstev)(char *jobz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dstevd)(char *jobz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstevr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstevx)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsycon)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsyconv)(char *uplo, char *way, int *n, double *a, int *lda, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsyequb)(char *uplo, int *n, double *a, int *lda, double *s, double *scond, double *amax, double *work, int *info);
+void BLAS_FUNC(dsyev)(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsyevd)(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsyevr)(char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsyevx)(char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsygs2)(int *itype, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsygst)(int *itype, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsygv)(int *itype, char *jobz, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *w, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsygvd)(int *itype, char *jobz, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsygvx)(int *itype, char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsyrfs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsysv)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsysvx)(char *fact, char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dsyswapr)(char *uplo, int *n, double *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(dsytd2)(char *uplo, int *n, double *a, int *lda, double *d, double *e, double *tau, int *info);
+void BLAS_FUNC(dsytf2)(char *uplo, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dsytrd)(char *uplo, int *n, double *a, int *lda, double *d, double *e, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytrf)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytri)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsytri2)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytri2x)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *nb, int *info);
+void BLAS_FUNC(dsytrs)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsytrs2)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *work, int *info);
+void BLAS_FUNC(dtbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, double *ab, int *ldab, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *a, double *b, int *ldb);
+void BLAS_FUNC(dtftri)(char *transr, char *uplo, char *diag, int *n, double *a, int *info);
+void BLAS_FUNC(dtfttp)(char *transr, char *uplo, int *n, double *arf, double *ap, int *info);
+void BLAS_FUNC(dtfttr)(char *transr, char *uplo, int *n, double *arf, double *a, int *lda, int *info);
+void BLAS_FUNC(dtgevc)(char *side, char *howmny, int *select, int *n, double *s, int *lds, double *p, int *ldp, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *info);
+void BLAS_FUNC(dtgex2)(int *wantq, int *wantz, int *n, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *j1, int *n1, int *n2, double *work, int *lwork, int *info);
+void BLAS_FUNC(dtgexc)(int *wantq, int *wantz, int *n, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *ifst, int *ilst, double *work, int *lwork, int *info);
+void BLAS_FUNC(dtgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *q, int *ldq, double *z, int *ldz, int *m, double *pl, double *pr, double *dif, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dtgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, double *a, int *lda, double *b, int *ldb, double *tola, double *tolb, double *alpha, double *beta, double *u, int *ldu, double *v, int *ldv, double *q, int *ldq, double *work, int *ncycle, int *info);
+void BLAS_FUNC(dtgsna)(char *job, char *howmny, int *select, int *n, double *a, int *lda, double *b, int *ldb, double *vl, int *ldvl, double *vr, int *ldvr, double *s, double *dif, int *mm, int *m, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dtgsy2)(char *trans, int *ijob, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *d, int *ldd, double *e, int *lde, double *f, int *ldf, double *scale, double *rdsum, double *rdscal, int *iwork, int *pq, int *info);
+void BLAS_FUNC(dtgsyl)(char *trans, int *ijob, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *d, int *ldd, double *e, int *lde, double *f, int *ldf, double *scale, double *dif, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dtpcon)(char *norm, char *uplo, char *diag, int *n, double *ap, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, double *v, int *ldv, double *t, int *ldt, double *a, int *lda, double *b, int *ldb, double *work, int *info);
+void BLAS_FUNC(dtpqrt)(int *m, int *n, int *l, int *nb, double *a, int *lda, double *b, int *ldb, double *t, int *ldt, double *work, int *info);
+void BLAS_FUNC(dtpqrt2)(int *m, int *n, int *l, double *a, int *lda, double *b, int *ldb, double *t, int *ldt, int *info);
+void BLAS_FUNC(dtprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, double *v, int *ldv, double *t, int *ldt, double *a, int *lda, double *b, int *ldb, double *work, int *ldwork);
+void BLAS_FUNC(dtprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *ap, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtptri)(char *uplo, char *diag, int *n, double *ap, int *info);
+void BLAS_FUNC(dtptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtpttf)(char *transr, char *uplo, int *n, double *ap, double *arf, int *info);
+void BLAS_FUNC(dtpttr)(char *uplo, int *n, double *ap, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrcon)(char *norm, char *uplo, char *diag, int *n, double *a, int *lda, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtrevc)(char *side, char *howmny, int *select, int *n, double *t, int *ldt, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *info);
+void BLAS_FUNC(dtrexc)(char *compq, int *n, double *t, int *ldt, double *q, int *ldq, int *ifst, int *ilst, double *work, int *info);
+void BLAS_FUNC(dtrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtrsen)(char *job, char *compq, int *select, int *n, double *t, int *ldt, double *q, int *ldq, double *wr, double *wi, int *m, double *s, double *sep, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dtrsna)(char *job, char *howmny, int *select, int *n, double *t, int *ldt, double *vl, int *ldvl, double *vr, int *ldvr, double *s, double *sep, int *mm, int *m, double *work, int *ldwork, int *iwork, int *info);
+void BLAS_FUNC(dtrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *scale, int *info);
+void BLAS_FUNC(dtrti2)(char *uplo, char *diag, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrtri)(char *uplo, char *diag, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtrttf)(char *transr, char *uplo, int *n, double *a, int *lda, double *arf, int *info);
+void BLAS_FUNC(dtrttp)(char *uplo, int *n, double *a, int *lda, double *ap, int *info);
+void BLAS_FUNC(dtzrzf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+double BLAS_FUNC(dzsum1)(int *n, npy_complex128 *cx, int *incx);
+int BLAS_FUNC(icmax1)(int *n, npy_complex64 *cx, int *incx);
+int BLAS_FUNC(ieeeck)(int *ispec, float *zero, float *one);
+int BLAS_FUNC(ilaclc)(int *m, int *n, npy_complex64 *a, int *lda);
+int BLAS_FUNC(ilaclr)(int *m, int *n, npy_complex64 *a, int *lda);
+int BLAS_FUNC(iladiag)(char *diag);
+int BLAS_FUNC(iladlc)(int *m, int *n, double *a, int *lda);
+int BLAS_FUNC(iladlr)(int *m, int *n, double *a, int *lda);
+int BLAS_FUNC(ilaprec)(char *prec);
+int BLAS_FUNC(ilaslc)(int *m, int *n, float *a, int *lda);
+int BLAS_FUNC(ilaslr)(int *m, int *n, float *a, int *lda);
+int BLAS_FUNC(ilatrans)(char *trans);
+int BLAS_FUNC(ilauplo)(char *uplo);
+void BLAS_FUNC(ilaver)(int *vers_major, int *vers_minor, int *vers_patch);
+int BLAS_FUNC(ilazlc)(int *m, int *n, npy_complex128 *a, int *lda);
+int BLAS_FUNC(ilazlr)(int *m, int *n, npy_complex128 *a, int *lda);
+int BLAS_FUNC(izmax1)(int *n, npy_complex128 *cx, int *incx);
+void BLAS_FUNC(sbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, float *theta, float *phi, float *u1, int *ldu1, float *u2, int *ldu2, float *v1t, int *ldv1t, float *v2t, int *ldv2t, float *b11d, float *b11e, float *b12d, float *b12e, float *b21d, float *b21e, float *b22d, float *b22e, float *work, int *lwork, int *info);
+void BLAS_FUNC(sbdsdc)(char *uplo, char *compq, int *n, float *d, float *e, float *u, int *ldu, float *vt, int *ldvt, float *q, int *iq, float *work, int *iwork, int *info);
+void BLAS_FUNC(sbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, float *vt, int *ldvt, float *u, int *ldu, float *c, int *ldc, float *work, int *info);
+float BLAS_FUNC(scsum1)(int *n, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(sdisna)(char *job, int *m, int *n, float *d, float *sep, int *info);
+void BLAS_FUNC(sgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, float *ab, int *ldab, float *d, float *e, float *q, int *ldq, float *pt, int *ldpt, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sgbcon)(char *norm, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbequ)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgbequb)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbsv)(int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, int *ipiv, char *equed, float *r, float *c, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbtf2)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(sgbtrf)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(sgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgebak)(char *job, char *side, int *n, int *ilo, int *ihi, float *scale, int *m, float *v, int *ldv, int *info);
+void BLAS_FUNC(sgebal)(char *job, int *n, float *a, int *lda, int *ilo, int *ihi, float *scale, int *info);
+void BLAS_FUNC(sgebd2)(int *m, int *n, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *work, int *info);
+void BLAS_FUNC(sgebrd)(int *m, int *n, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgecon)(char *norm, int *n, float *a, int *lda, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgeequ)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgeequb)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgees)(char *jobvs, char *sort, _sselect2 *select, int *n, float *a, int *lda, int *sdim, float *wr, float *wi, float *vs, int *ldvs, float *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(sgeesx)(char *jobvs, char *sort, _sselect2 *select, char *sense, int *n, float *a, int *lda, int *sdim, float *wr, float *wi, float *vs, int *ldvs, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(sgeev)(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, float *a, int *lda, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, int *ilo, int *ihi, float *scale, float *abnrm, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgehd2)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgehrd)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgejsv)(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, float *a, int *lda, float *sva, float *u, int *ldu, float *v, int *ldv, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgelq2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgelqf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgels)(char *trans, int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgelsd)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *s, float *rcond, int *rank, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgelss)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *s, float *rcond, int *rank, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgelsy)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *jpvt, float *rcond, int *rank, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sgeql2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqlf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqp3)(int *m, int *n, float *a, int *lda, int *jpvt, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqr2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqr2p)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqrf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqrfp)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqrt)(int *m, int *n, int *nb, float *a, int *lda, float *t, int *ldt, float *work, int *info);
+void BLAS_FUNC(sgeqrt2)(int *m, int *n, float *a, int *lda, float *t, int *ldt, int *info);
+void BLAS_FUNC(sgeqrt3)(int *m, int *n, float *a, int *lda, float *t, int *ldt, int *info);
+void BLAS_FUNC(sgerfs)(char *trans, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgerq2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgerqf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesc2)(int *n, float *a, int *lda, float *rhs, int *ipiv, int *jpiv, float *scale);
+void BLAS_FUNC(sgesdd)(char *jobz, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgesv)(int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgesvd)(char *jobu, char *jobvt, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesvj)(char *joba, char *jobu, char *jobv, int *m, int *n, float *a, int *lda, float *sva, int *mv, float *v, int *ldv, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesvx)(char *fact, char *trans, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, char *equed, float *r, float *c, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgetc2)(int *n, float *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(sgetf2)(int *m, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(sgetrf)(int *m, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(sgetri)(int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgetrs)(char *trans, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sggbak)(char *job, char *side, int *n, int *ilo, int *ihi, float *lscale, float *rscale, int *m, float *v, int *ldv, int *info);
+void BLAS_FUNC(sggbal)(char *job, int *n, float *a, int *lda, float *b, int *ldb, int *ilo, int *ihi, float *lscale, float *rscale, float *work, int *info);
+void BLAS_FUNC(sgges)(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(sggesx)(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, char *sense, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(sggev)(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *vl, int *ldvl, float *vr, int *ldvr, int *ilo, int *ihi, float *lscale, float *rscale, float *abnrm, float *bbnrm, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(sggglm)(int *n, int *m, int *p, float *a, int *lda, float *b, int *ldb, float *d, float *x, float *y, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *info);
+void BLAS_FUNC(sgglse)(int *m, int *n, int *p, float *a, int *lda, float *b, int *ldb, float *c, float *d, float *x, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggqrf)(int *n, int *m, int *p, float *a, int *lda, float *taua, float *b, int *ldb, float *taub, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggrqf)(int *m, int *p, int *n, float *a, int *lda, float *taua, float *b, int *ldb, float *taub, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgsvj0)(char *jobv, int *m, int *n, float *a, int *lda, float *d, float *sva, int *mv, float *v, int *ldv, float *eps, float *sfmin, float *tol, int *nsweep, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgsvj1)(char *jobv, int *m, int *n, int *n1, float *a, int *lda, float *d, float *sva, int *mv, float *v, int *ldv, float *eps, float *sfmin, float *tol, int *nsweep, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgtcon)(char *norm, int *n, float *dl, float *d, float *du, float *du2, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgtrfs)(char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *dlf, float *df, float *duf, float *du2, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgtsv)(int *n, int *nrhs, float *dl, float *d, float *du, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgtsvx)(char *fact, char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *dlf, float *df, float *duf, float *du2, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgttrf)(int *n, float *dl, float *d, float *du, float *du2, int *ipiv, int *info);
+void BLAS_FUNC(sgttrs)(char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *du2, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgtts2)(int *itrans, int *n, int *nrhs, float *dl, float *d, float *du, float *du2, int *ipiv, float *b, int *ldb);
+void BLAS_FUNC(shgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *t, int *ldt, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(shsein)(char *side, char *eigsrc, char *initv, int *select, int *n, float *h, int *ldh, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(shseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slabad)(float *small, float *large);
+void BLAS_FUNC(slabrd)(int *m, int *n, int *nb, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *x, int *ldx, float *y, int *ldy);
+void BLAS_FUNC(slacn2)(int *n, float *v, float *x, int *isgn, float *est, int *kase, int *isave);
+void BLAS_FUNC(slacon)(int *n, float *v, float *x, int *isgn, float *est, int *kase);
+void BLAS_FUNC(slacpy)(char *uplo, int *m, int *n, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(sladiv)(float *a, float *b, float *c, float *d, float *p, float *q);
+void BLAS_FUNC(slae2)(float *a, float *b, float *c, float *rt1, float *rt2);
+void BLAS_FUNC(slaebz)(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, float *abstol, float *reltol, float *pivmin, float *d, float *e, float *e2, int *nval, float *ab, float *c, int *mout, int *nab, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed0)(int *icompq, int *qsiz, int *n, float *d, float *e, float *q, int *ldq, float *qstore, int *ldqs, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed1)(int *n, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed2)(int *k, int *n, int *n1, float *d, float *q, int *ldq, int *indxq, float *rho, float *z, float *dlamda, float *w, float *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info);
+void BLAS_FUNC(slaed3)(int *k, int *n, int *n1, float *d, float *q, int *ldq, float *rho, float *dlamda, float *q2, int *indx, int *ctot, float *w, float *s, int *info);
+void BLAS_FUNC(slaed4)(int *n, int *i, float *d, float *z, float *delta, float *rho, float *dlam, int *info);
+void BLAS_FUNC(slaed5)(int *i, float *d, float *z, float *delta, float *rho, float *dlam);
+void BLAS_FUNC(slaed6)(int *kniter, int *orgati, float *rho, float *d, float *z, float *finit, float *tau, int *info);
+void BLAS_FUNC(slaed7)(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed8)(int *icompq, int *k, int *n, int *qsiz, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *z, float *dlamda, float *q2, int *ldq2, float *w, int *perm, int *givptr, int *givcol, float *givnum, int *indxp, int *indx, int *info);
+void BLAS_FUNC(slaed9)(int *k, int *kstart, int *kstop, int *n, float *d, float *q, int *ldq, float *rho, float *dlamda, float *w, float *s, int *lds, int *info);
+void BLAS_FUNC(slaeda)(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, float *q, int *qptr, float *z, float *ztemp, int *info);
+void BLAS_FUNC(slaein)(int *rightv, int *noinit, int *n, float *h, int *ldh, float *wr, float *wi, float *vr, float *vi, float *b, int *ldb, float *work, float *eps3, float *smlnum, float *bignum, int *info);
+void BLAS_FUNC(slaev2)(float *a, float *b, float *c, float *rt1, float *rt2, float *cs1, float *sn1);
+void BLAS_FUNC(slaexc)(int *wantq, int *n, float *t, int *ldt, float *q, int *ldq, int *j1, int *n1, int *n2, float *work, int *info);
+void BLAS_FUNC(slag2)(float *a, int *lda, float *b, int *ldb, float *safmin, float *scale1, float *scale2, float *wr1, float *wr2, float *wi);
+void BLAS_FUNC(slag2d)(int *m, int *n, float *sa, int *ldsa, double *a, int *lda, int *info);
+void BLAS_FUNC(slags2)(int *upper, float *a1, float *a2, float *a3, float *b1, float *b2, float *b3, float *csu, float *snu, float *csv, float *snv, float *csq, float *snq);
+void BLAS_FUNC(slagtf)(int *n, float *a, float *lambda_, float *b, float *c, float *tol, float *d, int *in_, int *info);
+void BLAS_FUNC(slagtm)(char *trans, int *n, int *nrhs, float *alpha, float *dl, float *d, float *du, float *x, int *ldx, float *beta, float *b, int *ldb);
+void BLAS_FUNC(slagts)(int *job, int *n, float *a, float *b, float *c, float *d, int *in_, float *y, float *tol, int *info);
+void BLAS_FUNC(slagv2)(float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *csl, float *snl, float *csr, float *snr);
+void BLAS_FUNC(slahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, int *info);
+void BLAS_FUNC(slahr2)(int *n, int *k, int *nb, float *a, int *lda, float *tau, float *t, int *ldt, float *y, int *ldy);
+void BLAS_FUNC(slaic1)(int *job, int *j, float *x, float *sest, float *w, float *gamma, float *sestpr, float *s, float *c);
+void BLAS_FUNC(slaln2)(int *ltrans, int *na, int *nw, float *smin, float *ca, float *a, int *lda, float *d1, float *d2, float *b, int *ldb, float *wr, float *wi, float *x, int *ldx, float *scale, float *xnorm, int *info);
+void BLAS_FUNC(slals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, float *b, int *ldb, float *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *work, int *info);
+void BLAS_FUNC(slalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, float *b, int *ldb, float *bx, int *ldbx, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, float *d, float *e, float *b, int *ldb, float *rcond, int *rank, float *work, int *iwork, int *info);
+float BLAS_FUNC(slamch)(char *cmach);
+void BLAS_FUNC(slamrg)(int *n1, int *n2, float *a, int *strd1, int *strd2, int *index_bn);
+float BLAS_FUNC(slangb)(char *norm, int *n, int *kl, int *ku, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slange)(char *norm, int *m, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slangt)(char *norm, int *n, float *dl, float *d, float *du);
+float BLAS_FUNC(slanhs)(char *norm, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slansb)(char *norm, char *uplo, int *n, int *k, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slansf)(char *norm, char *transr, char *uplo, int *n, float *a, float *work);
+float BLAS_FUNC(slansp)(char *norm, char *uplo, int *n, float *ap, float *work);
+float BLAS_FUNC(slanst)(char *norm, int *n, float *d, float *e);
+float BLAS_FUNC(slansy)(char *norm, char *uplo, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slantb)(char *norm, char *uplo, char *diag, int *n, int *k, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slantp)(char *norm, char *uplo, char *diag, int *n, float *ap, float *work);
+float BLAS_FUNC(slantr)(char *norm, char *uplo, char *diag, int *m, int *n, float *a, int *lda, float *work);
+void BLAS_FUNC(slanv2)(float *a, float *b, float *c, float *d, float *rt1r, float *rt1i, float *rt2r, float *rt2i, float *cs, float *sn);
+void BLAS_FUNC(slapll)(int *n, float *x, int *incx, float *y, int *incy, float *ssmin);
+void BLAS_FUNC(slapmr)(int *forwrd, int *m, int *n, float *x, int *ldx, int *k);
+void BLAS_FUNC(slapmt)(int *forwrd, int *m, int *n, float *x, int *ldx, int *k);
+float BLAS_FUNC(slapy2)(float *x, float *y);
+float BLAS_FUNC(slapy3)(float *x, float *y, float *z);
+void BLAS_FUNC(slaqgb)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(slaqge)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(slaqp2)(int *m, int *n, int *offset, float *a, int *lda, int *jpvt, float *tau, float *vn1, float *vn2, float *work);
+void BLAS_FUNC(slaqps)(int *m, int *n, int *offset, int *nb, int *kb, float *a, int *lda, int *jpvt, float *tau, float *vn1, float *vn2, float *auxv, float *f, int *ldf);
+void BLAS_FUNC(slaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slaqr1)(int *n, float *h, int *ldh, float *sr1, float *si1, float *sr2, float *si2, float *v);
+void BLAS_FUNC(slaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, int *ns, int *nd, float *sr, float *si, float *v, int *ldv, int *nh, float *t, int *ldt, int *nv, float *wv, int *ldwv, float *work, int *lwork);
+void BLAS_FUNC(slaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, int *ns, int *nd, float *sr, float *si, float *v, int *ldv, int *nh, float *t, int *ldt, int *nv, float *wv, int *ldwv, float *work, int *lwork);
+void BLAS_FUNC(slaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, float *sr, float *si, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, float *v, int *ldv, float *u, int *ldu, int *nv, float *wv, int *ldwv, int *nh, float *wh, int *ldwh);
+void BLAS_FUNC(slaqsb)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqsp)(char *uplo, int *n, float *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqsy)(char *uplo, int *n, float *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqtr)(int *ltran, int *lreal, int *n, float *t, int *ldt, float *b, float *w, float *scale, float *x, float *work, int *info);
+void BLAS_FUNC(slar1v)(int *n, int *b1, int *bn, float *lambda_, float *d, float *l, float *ld, float *lld, float *pivmin, float *gaptol, float *z, int *wantnc, int *negcnt, float *ztz, float *mingma, int *r, int *isuppz, float *nrminv, float *resid, float *rqcorr, float *work);
+void BLAS_FUNC(slar2v)(int *n, float *x, float *y, float *z, int *incx, float *c, float *s, int *incc);
+void BLAS_FUNC(slarf)(char *side, int *m, int *n, float *v, int *incv, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *ldwork);
+void BLAS_FUNC(slarfg)(int *n, float *alpha, float *x, int *incx, float *tau);
+void BLAS_FUNC(slarfgp)(int *n, float *alpha, float *x, int *incx, float *tau);
+void BLAS_FUNC(slarft)(char *direct, char *storev, int *n, int *k, float *v, int *ldv, float *tau, float *t, int *ldt);
+void BLAS_FUNC(slarfx)(char *side, int *m, int *n, float *v, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slargv)(int *n, float *x, int *incx, float *y, int *incy, float *c, int *incc);
+void BLAS_FUNC(slarnv)(int *idist, int *iseed, int *n, float *x);
+void BLAS_FUNC(slarra)(int *n, float *d, float *e, float *e2, float *spltol, float *tnrm, int *nsplit, int *isplit, int *info);
+void BLAS_FUNC(slarrb)(int *n, float *d, float *lld, int *ifirst, int *ilast, float *rtol1, float *rtol2, int *offset, float *w, float *wgap, float *werr, float *work, int *iwork, float *pivmin, float *spdiam, int *twist, int *info);
+void BLAS_FUNC(slarrc)(char *jobt, int *n, float *vl, float *vu, float *d, float *e, float *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info);
+void BLAS_FUNC(slarrd)(char *range, char *order, int *n, float *vl, float *vu, int *il, int *iu, float *gers, float *reltol, float *d, float *e, float *e2, float *pivmin, int *nsplit, int *isplit, int *m, float *w, float *werr, float *wl, float *wu, int *iblock, int *indexw, float *work, int *iwork, int *info);
+void BLAS_FUNC(slarre)(char *range, int *n, float *vl, float *vu, int *il, int *iu, float *d, float *e, float *e2, float *rtol1, float *rtol2, float *spltol, int *nsplit, int *isplit, int *m, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, float *pivmin, float *work, int *iwork, int *info);
+void BLAS_FUNC(slarrf)(int *n, float *d, float *l, float *ld, int *clstrt, int *clend, float *w, float *wgap, float *werr, float *spdiam, float *clgapl, float *clgapr, float *pivmin, float *sigma, float *dplus, float *lplus, float *work, int *info);
+void BLAS_FUNC(slarrj)(int *n, float *d, float *e2, int *ifirst, int *ilast, float *rtol, int *offset, float *w, float *werr, float *work, int *iwork, float *pivmin, float *spdiam, int *info);
+void BLAS_FUNC(slarrk)(int *n, int *iw, float *gl, float *gu, float *d, float *e2, float *pivmin, float *reltol, float *w, float *werr, int *info);
+void BLAS_FUNC(slarrr)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(slarrv)(int *n, float *vl, float *vu, float *d, float *l, float *pivmin, int *isplit, int *m, int *dol, int *dou, float *minrgp, float *rtol1, float *rtol2, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, float *z, int *ldz, int *isuppz, float *work, int *iwork, int *info);
+void BLAS_FUNC(slartg)(float *f, float *g, float *cs, float *sn, float *r);
+void BLAS_FUNC(slartgp)(float *f, float *g, float *cs, float *sn, float *r);
+void BLAS_FUNC(slartgs)(float *x, float *y, float *sigma, float *cs, float *sn);
+void BLAS_FUNC(slartv)(int *n, float *x, int *incx, float *y, int *incy, float *c, float *s, int *incc);
+void BLAS_FUNC(slaruv)(int *iseed, int *n, float *x);
+void BLAS_FUNC(slarz)(char *side, int *m, int *n, int *l, float *v, int *incv, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *ldwork);
+void BLAS_FUNC(slarzt)(char *direct, char *storev, int *n, int *k, float *v, int *ldv, float *tau, float *t, int *ldt);
+void BLAS_FUNC(slas2)(float *f, float *g, float *h, float *ssmin, float *ssmax);
+void BLAS_FUNC(slascl)(char *type_bn, int *kl, int *ku, float *cfrom, float *cto, int *m, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(slasd0)(int *n, int *sqre, float *d, float *e, float *u, int *ldu, float *vt, int *ldvt, int *smlsiz, int *iwork, float *work, int *info);
+void BLAS_FUNC(slasd1)(int *nl, int *nr, int *sqre, float *d, float *alpha, float *beta, float *u, int *ldu, float *vt, int *ldvt, int *idxq, int *iwork, float *work, int *info);
+void BLAS_FUNC(slasd2)(int *nl, int *nr, int *sqre, int *k, float *d, float *z, float *alpha, float *beta, float *u, int *ldu, float *vt, int *ldvt, float *dsigma, float *u2, int *ldu2, float *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info);
+void BLAS_FUNC(slasd3)(int *nl, int *nr, int *sqre, int *k, float *d, float *q, int *ldq, float *dsigma, float *u, int *ldu, float *u2, int *ldu2, float *vt, int *ldvt, float *vt2, int *ldvt2, int *idxc, int *ctot, float *z, int *info);
+void BLAS_FUNC(slasd4)(int *n, int *i, float *d, float *z, float *delta, float *rho, float *sigma, float *work, int *info);
+void BLAS_FUNC(slasd5)(int *i, float *d, float *z, float *delta, float *rho, float *dsigma, float *work);
+void BLAS_FUNC(slasd6)(int *icompq, int *nl, int *nr, int *sqre, float *d, float *vf, float *vl, float *alpha, float *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slasd7)(int *icompq, int *nl, int *nr, int *sqre, int *k, float *d, float *z, float *zw, float *vf, float *vfw, float *vl, float *vlw, float *alpha, float *beta, float *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *c, float *s, int *info);
+void BLAS_FUNC(slasd8)(int *icompq, int *k, float *d, float *z, float *vf, float *vl, float *difl, float *difr, int *lddifr, float *dsigma, float *work, int *info);
+void BLAS_FUNC(slasda)(int *icompq, int *smlsiz, int *n, int *sqre, float *d, float *e, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slasdq)(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, float *vt, int *ldvt, float *u, int *ldu, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(slasdt)(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub);
+void BLAS_FUNC(slaset)(char *uplo, int *m, int *n, float *alpha, float *beta, float *a, int *lda);
+void BLAS_FUNC(slasq1)(int *n, float *d, float *e, float *work, int *info);
+void BLAS_FUNC(slasq2)(int *n, float *z, int *info);
+void BLAS_FUNC(slasq3)(int *i0, int *n0, float *z, int *pp, float *dmin, float *sigma, float *desig, float *qmax, int *nfail, int *iter, int *ndiv, int *ieee, int *ttype, float *dmin1, float *dmin2, float *dn, float *dn1, float *dn2, float *g, float *tau);
+void BLAS_FUNC(slasq4)(int *i0, int *n0, float *z, int *pp, int *n0in, float *dmin, float *dmin1, float *dmin2, float *dn, float *dn1, float *dn2, float *tau, int *ttype, float *g);
+void BLAS_FUNC(slasq6)(int *i0, int *n0, float *z, int *pp, float *dmin, float *dmin1, float *dmin2, float *dn, float *dnm1, float *dnm2);
+void BLAS_FUNC(slasr)(char *side, char *pivot, char *direct, int *m, int *n, float *c, float *s, float *a, int *lda);
+void BLAS_FUNC(slasrt)(char *id, int *n, float *d, int *info);
+void BLAS_FUNC(slassq)(int *n, float *x, int *incx, float *scale, float *sumsq);
+void BLAS_FUNC(slasv2)(float *f, float *g, float *h, float *ssmin, float *ssmax, float *snr, float *csr, float *snl, float *csl);
+void BLAS_FUNC(slaswp)(int *n, float *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(slasy2)(int *ltranl, int *ltranr, int *isgn, int *n1, int *n2, float *tl, int *ldtl, float *tr, int *ldtr, float *b, int *ldb, float *scale, float *x, int *ldx, float *xnorm, int *info);
+void BLAS_FUNC(slasyf)(char *uplo, int *n, int *nb, int *kb, float *a, int *lda, int *ipiv, float *w, int *ldw, int *info);
+void BLAS_FUNC(slatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, float *ab, int *ldab, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatdf)(int *ijob, int *n, float *z, int *ldz, float *rhs, float *rdsum, float *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(slatps)(char *uplo, char *trans, char *diag, char *normin, int *n, float *ap, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatrd)(char *uplo, int *n, int *nb, float *a, int *lda, float *e, float *tau, float *w, int *ldw);
+void BLAS_FUNC(slatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, float *a, int *lda, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatrz)(int *m, int *n, int *l, float *a, int *lda, float *tau, float *work);
+void BLAS_FUNC(slauu2)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(slauum)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(sopgtr)(char *uplo, int *n, float *ap, float *tau, float *q, int *ldq, float *work, int *info);
+void BLAS_FUNC(sopmtr)(char *side, char *uplo, char *trans, int *m, int *n, float *ap, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sorbdb)(char *trans, char *signs, int *m, int *p, int *q, float *x11, int *ldx11, float *x12, int *ldx12, float *x21, int *ldx21, float *x22, int *ldx22, float *theta, float *phi, float *taup1, float *taup2, float *tauq1, float *tauq2, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, float *x11, int *ldx11, float *x12, int *ldx12, float *x21, int *ldx21, float *x22, int *ldx22, float *theta, float *u1, int *ldu1, float *u2, int *ldu2, float *v1t, int *ldv1t, float *v2t, int *ldv2t, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sorg2l)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorg2r)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorgbr)(char *vect, int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorghr)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgl2)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorglq)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgql)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgqr)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgr2)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorgrq)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgtr)(char *uplo, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorm2l)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sorm2r)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorml2)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormlq)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormql)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormqr)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormr2)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormr3)(char *side, char *trans, int *m, int *n, int *k, int *l, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormrq)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormrz)(char *side, char *trans, int *m, int *n, int *k, int *l, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormtr)(char *side, char *uplo, char *trans, int *m, int *n, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(spbcon)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbequ)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spbrfs)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbstf)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbsv)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(spbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbtf2)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbtrf)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbtrs)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(spftrf)(char *transr, char *uplo, int *n, float *a, int *info);
+void BLAS_FUNC(spftri)(char *transr, char *uplo, int *n, float *a, int *info);
+void BLAS_FUNC(spftrs)(char *transr, char *uplo, int *n, int *nrhs, float *a, float *b, int *ldb, int *info);
+void BLAS_FUNC(spocon)(char *uplo, int *n, float *a, int *lda, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(spoequ)(int *n, float *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spoequb)(int *n, float *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(sporfs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sposv)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(sposvx)(char *fact, char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spotf2)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotrf)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotri)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotrs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(sppcon)(char *uplo, int *n, float *ap, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sppequ)(char *uplo, int *n, float *ap, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spprfs)(char *uplo, int *n, int *nrhs, float *ap, float *afp, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sppsv)(char *uplo, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(sppsvx)(char *fact, char *uplo, int *n, int *nrhs, float *ap, float *afp, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spptrf)(char *uplo, int *n, float *ap, int *info);
+void BLAS_FUNC(spptri)(char *uplo, int *n, float *ap, int *info);
+void BLAS_FUNC(spptrs)(char *uplo, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(spstf2)(char *uplo, int *n, float *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(spstrf)(char *uplo, int *n, float *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(sptcon)(int *n, float *d, float *e, float *anorm, float *rcond, float *work, int *info);
+void BLAS_FUNC(spteqr)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sptrfs)(int *n, int *nrhs, float *d, float *e, float *df, float *ef, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *info);
+void BLAS_FUNC(sptsv)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb, int *info);
+void BLAS_FUNC(sptsvx)(char *fact, int *n, int *nrhs, float *d, float *e, float *df, float *ef, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *info);
+void BLAS_FUNC(spttrf)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(spttrs)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb, int *info);
+void BLAS_FUNC(sptts2)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb);
+void BLAS_FUNC(srscl)(int *n, float *sa, float *sx, int *incx);
+void BLAS_FUNC(ssbev)(char *jobz, char *uplo, int *n, int *kd, float *ab, int *ldab, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssbevd)(char *jobz, char *uplo, int *n, int *kd, float *ab, int *ldab, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, float *ab, int *ldab, float *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *x, int *ldx, float *work, int *info);
+void BLAS_FUNC(ssbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssbtrd)(char *vect, char *uplo, int *n, int *kd, float *ab, int *ldab, float *d, float *e, float *q, int *ldq, float *work, int *info);
+void BLAS_FUNC(ssfrk)(char *transr, char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c);
+void BLAS_FUNC(sspcon)(char *uplo, int *n, float *ap, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sspev)(char *jobz, char *uplo, int *n, float *ap, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sspevd)(char *jobz, char *uplo, int *n, float *ap, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sspevx)(char *jobz, char *range, char *uplo, int *n, float *ap, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(sspgst)(int *itype, char *uplo, int *n, float *ap, float *bp, int *info);
+void BLAS_FUNC(sspgv)(int *itype, char *jobz, char *uplo, int *n, float *ap, float *bp, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sspgvd)(int *itype, char *jobz, char *uplo, int *n, float *ap, float *bp, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sspgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, float *ap, float *bp, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssprfs)(char *uplo, int *n, int *nrhs, float *ap, float *afp, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sspsv)(char *uplo, int *n, int *nrhs, float *ap, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sspsvx)(char *fact, char *uplo, int *n, int *nrhs, float *ap, float *afp, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssptrd)(char *uplo, int *n, float *ap, float *d, float *e, float *tau, int *info);
+void BLAS_FUNC(ssptrf)(char *uplo, int *n, float *ap, int *ipiv, int *info);
+void BLAS_FUNC(ssptri)(char *uplo, int *n, float *ap, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssptrs)(char *uplo, int *n, int *nrhs, float *ap, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sstebz)(char *range, char *order, int *n, float *vl, float *vu, int *il, int *iu, float *abstol, float *d, float *e, int *m, int *nsplit, float *w, int *iblock, int *isplit, float *work, int *iwork, int *info);
+void BLAS_FUNC(sstedc)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstegr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstein)(int *n, float *d, float *e, int *m, float *w, int *iblock, int *isplit, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(sstemr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, int *m, float *w, float *z, int *ldz, int *nzc, int *isuppz, int *tryrac, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssteqr)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssterf)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(sstev)(char *jobz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sstevd)(char *jobz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstevr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstevx)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssycon)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssyconv)(char *uplo, char *way, int *n, float *a, int *lda, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssyequb)(char *uplo, int *n, float *a, int *lda, float *s, float *scond, float *amax, float *work, int *info);
+void BLAS_FUNC(ssyev)(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssyevd)(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssyevr)(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssyevx)(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssygs2)(int *itype, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssygst)(int *itype, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssygv)(int *itype, char *jobz, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *w, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssygvd)(int *itype, char *jobz, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssygvx)(int *itype, char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssyrfs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssysv)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssysvx)(char *fact, char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ssyswapr)(char *uplo, int *n, float *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(ssytd2)(char *uplo, int *n, float *a, int *lda, float *d, float *e, float *tau, int *info);
+void BLAS_FUNC(ssytf2)(char *uplo, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(ssytrd)(char *uplo, int *n, float *a, int *lda, float *d, float *e, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytrf)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytri)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssytri2)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytri2x)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *nb, int *info);
+void BLAS_FUNC(ssytrs)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssytrs2)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, float *work, int *info);
+void BLAS_FUNC(stbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, float *ab, int *ldab, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(stbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(stbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(stfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, float *alpha, float *a, float *b, int *ldb);
+void BLAS_FUNC(stftri)(char *transr, char *uplo, char *diag, int *n, float *a, int *info);
+void BLAS_FUNC(stfttp)(char *transr, char *uplo, int *n, float *arf, float *ap, int *info);
+void BLAS_FUNC(stfttr)(char *transr, char *uplo, int *n, float *arf, float *a, int *lda, int *info);
+void BLAS_FUNC(stgevc)(char *side, char *howmny, int *select, int *n, float *s, int *lds, float *p, int *ldp, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *info);
+void BLAS_FUNC(stgex2)(int *wantq, int *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *j1, int *n1, int *n2, float *work, int *lwork, int *info);
+void BLAS_FUNC(stgexc)(int *wantq, int *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *ifst, int *ilst, float *work, int *lwork, int *info);
+void BLAS_FUNC(stgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, int *m, float *pl, float *pr, float *dif, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(stgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, float *a, int *lda, float *b, int *ldb, float *tola, float *tolb, float *alpha, float *beta, float *u, int *ldu, float *v, int *ldv, float *q, int *ldq, float *work, int *ncycle, int *info);
+void BLAS_FUNC(stgsna)(char *job, char *howmny, int *select, int *n, float *a, int *lda, float *b, int *ldb, float *vl, int *ldvl, float *vr, int *ldvr, float *s, float *dif, int *mm, int *m, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(stgsy2)(char *trans, int *ijob, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *d, int *ldd, float *e, int *lde, float *f, int *ldf, float *scale, float *rdsum, float *rdscal, int *iwork, int *pq, int *info);
+void BLAS_FUNC(stgsyl)(char *trans, int *ijob, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *d, int *ldd, float *e, int *lde, float *f, int *ldf, float *scale, float *dif, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(stpcon)(char *norm, char *uplo, char *diag, int *n, float *ap, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(stpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, float *v, int *ldv, float *t, int *ldt, float *a, int *lda, float *b, int *ldb, float *work, int *info);
+void BLAS_FUNC(stpqrt)(int *m, int *n, int *l, int *nb, float *a, int *lda, float *b, int *ldb, float *t, int *ldt, float *work, int *info);
+void BLAS_FUNC(stpqrt2)(int *m, int *n, int *l, float *a, int *lda, float *b, int *ldb, float *t, int *ldt, int *info);
+void BLAS_FUNC(stprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, float *v, int *ldv, float *t, int *ldt, float *a, int *lda, float *b, int *ldb, float *work, int *ldwork);
+void BLAS_FUNC(stprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *ap, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(stptri)(char *uplo, char *diag, int *n, float *ap, int *info);
+void BLAS_FUNC(stptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(stpttf)(char *transr, char *uplo, int *n, float *ap, float *arf, int *info);
+void BLAS_FUNC(stpttr)(char *uplo, int *n, float *ap, float *a, int *lda, int *info);
+void BLAS_FUNC(strcon)(char *norm, char *uplo, char *diag, int *n, float *a, int *lda, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(strevc)(char *side, char *howmny, int *select, int *n, float *t, int *ldt, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *info);
+void BLAS_FUNC(strexc)(char *compq, int *n, float *t, int *ldt, float *q, int *ldq, int *ifst, int *ilst, float *work, int *info);
+void BLAS_FUNC(strrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(strsen)(char *job, char *compq, int *select, int *n, float *t, int *ldt, float *q, int *ldq, float *wr, float *wi, int *m, float *s, float *sep, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(strsna)(char *job, char *howmny, int *select, int *n, float *t, int *ldt, float *vl, int *ldvl, float *vr, int *ldvr, float *s, float *sep, int *mm, int *m, float *work, int *ldwork, int *iwork, int *info);
+void BLAS_FUNC(strsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *scale, int *info);
+void BLAS_FUNC(strti2)(char *uplo, char *diag, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(strtri)(char *uplo, char *diag, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(strtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(strttf)(char *transr, char *uplo, int *n, float *a, int *lda, float *arf, int *info);
+void BLAS_FUNC(strttp)(char *uplo, int *n, float *a, int *lda, float *ap, int *info);
+void BLAS_FUNC(stzrzf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(xerbla_array)(char *srname_array, int *srname_len, int *info);
+void BLAS_FUNC(zbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, double *theta, double *phi, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, double *b11d, double *b11e, double *b12d, double *b12e, double *b21d, double *b21e, double *b22d, double *b22e, double *rwork, int *lrwork, int *info);
+void BLAS_FUNC(zbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, npy_complex128 *vt, int *ldvt, npy_complex128 *u, int *ldu, npy_complex128 *c, int *ldc, double *rwork, int *info);
+void BLAS_FUNC(zcgesv)(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, double *rwork, int *iter, int *info);
+void BLAS_FUNC(zcposv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, double *rwork, int *iter, int *info);
+void BLAS_FUNC(zdrscl)(int *n, double *sa, npy_complex128 *sx, int *incx);
+void BLAS_FUNC(zgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *pt, int *ldpt, npy_complex128 *c, int *ldc, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbcon)(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbequ)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgbequb)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbsv)(int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, char *equed, double *r, double *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbtf2)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(zgbtrf)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(zgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgebak)(char *job, char *side, int *n, int *ilo, int *ihi, double *scale, int *m, npy_complex128 *v, int *ldv, int *info);
+void BLAS_FUNC(zgebal)(char *job, int *n, npy_complex128 *a, int *lda, int *ilo, int *ihi, double *scale, int *info);
+void BLAS_FUNC(zgebd2)(int *m, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgebrd)(int *m, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgecon)(char *norm, int *n, npy_complex128 *a, int *lda, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgeequ)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgeequb)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgees)(char *jobvs, char *sort, _zselect1 *select, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zgeesx)(char *jobvs, char *sort, _zselect1 *select, char *sense, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zgeev)(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, double *scale, double *abnrm, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgehd2)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgehrd)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgelq2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgelqf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgels)(char *trans, int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgelsd)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *s, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zgelss)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *s, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgelsy)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *jpvt, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeql2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqlf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqp3)(int *m, int *n, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgeqr2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqr2p)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqrf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqrfp)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqrt)(int *m, int *n, int *nb, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqrt2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(zgeqrt3)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(zgerfs)(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgerq2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgerqf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgesc2)(int *n, npy_complex128 *a, int *lda, npy_complex128 *rhs, int *ipiv, int *jpiv, double *scale);
+void BLAS_FUNC(zgesdd)(char *jobz, int *m, int *n, npy_complex128 *a, int *lda, double *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zgesv)(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgesvd)(char *jobu, char *jobvt, int *m, int *n, npy_complex128 *a, int *lda, double *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgesvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, char *equed, double *r, double *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgetc2)(int *n, npy_complex128 *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(zgetf2)(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zgetrf)(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zgetri)(int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgetrs)(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zggbak)(char *job, char *side, int *n, int *ilo, int *ihi, double *lscale, double *rscale, int *m, npy_complex128 *v, int *ldv, int *info);
+void BLAS_FUNC(zggbal)(char *job, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *ilo, int *ihi, double *lscale, double *rscale, double *work, int *info);
+void BLAS_FUNC(zgges)(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zggesx)(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(zggev)(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, double *lscale, double *rscale, double *abnrm, double *bbnrm, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(zggglm)(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *d, npy_complex128 *x, npy_complex128 *y, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *info);
+void BLAS_FUNC(zgglse)(int *m, int *n, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, npy_complex128 *d, npy_complex128 *x, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zggqrf)(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zggrqf)(int *m, int *p, int *n, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgtcon)(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgtrfs)(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgtsv)(int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgtsvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgttrf)(int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, int *info);
+void BLAS_FUNC(zgttrs)(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgtts2)(int *itrans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zhbev)(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbevd)(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *x, int *ldx, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhbtrd)(char *vect, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhecon)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zheequb)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, npy_complex128 *work, int *info);
+void BLAS_FUNC(zheev)(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, double *w, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zheevd)(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, double *w, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zheevr)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, int *isuppz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zheevx)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhegs2)(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhegst)(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhegv)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *w, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zhegvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *w, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhegvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zherfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhesv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhesvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zheswapr)(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(zhetd2)(char *uplo, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tau, int *info);
+void BLAS_FUNC(zhetf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zhetrd)(char *uplo, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhetri2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetri2x)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info);
+void BLAS_FUNC(zhetrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhetrs2)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhfrk)(char *transr, char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c);
+void BLAS_FUNC(zhgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *t, int *ldt, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zhpcon)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhpev)(char *jobz, char *uplo, int *n, npy_complex128 *ap, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpevd)(char *jobz, char *uplo, int *n, npy_complex128 *ap, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhpevx)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhpgst)(int *itype, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, int *info);
+void BLAS_FUNC(zhpgv)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpgvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhpgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhpsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhptrd)(char *uplo, int *n, npy_complex128 *ap, double *d, double *e, npy_complex128 *tau, int *info);
+void BLAS_FUNC(zhptrf)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info);
+void BLAS_FUNC(zhptri)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhsein)(char *side, char *eigsrc, char *initv, int *select, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(zhseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlabrd)(int *m, int *n, int *nb, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *x, int *ldx, npy_complex128 *y, int *ldy);
+void BLAS_FUNC(zlacgv)(int *n, npy_complex128 *x, int *incx);
+void BLAS_FUNC(zlacn2)(int *n, npy_complex128 *v, npy_complex128 *x, double *est, int *kase, int *isave);
+void BLAS_FUNC(zlacon)(int *n, npy_complex128 *v, npy_complex128 *x, double *est, int *kase);
+void BLAS_FUNC(zlacp2)(char *uplo, int *m, int *n, double *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlacpy)(char *uplo, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlacrm)(int *m, int *n, npy_complex128 *a, int *lda, double *b, int *ldb, npy_complex128 *c, int *ldc, double *rwork);
+void BLAS_FUNC(zlacrt)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, npy_complex128 *c, npy_complex128 *s);
+void F_FUNC(zladivwrp,ZLADIVWRP)(npy_complex128 *out, npy_complex128 *x, npy_complex128 *y);
+void BLAS_FUNC(zlaed0)(int *qsiz, int *n, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *qstore, int *ldqs, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlaed7)(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, double *d, npy_complex128 *q, int *ldq, double *rho, int *indxq, double *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, npy_complex128 *work, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlaed8)(int *k, int *n, int *qsiz, npy_complex128 *q, int *ldq, double *d, double *rho, int *cutpnt, double *z, double *dlamda, npy_complex128 *q2, int *ldq2, double *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, double *givnum, int *info);
+void BLAS_FUNC(zlaein)(int *rightv, int *noinit, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *v, npy_complex128 *b, int *ldb, double *rwork, double *eps3, double *smlnum, int *info);
+void BLAS_FUNC(zlaesy)(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, npy_complex128 *rt1, npy_complex128 *rt2, npy_complex128 *evscal, npy_complex128 *cs1, npy_complex128 *sn1);
+void BLAS_FUNC(zlaev2)(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, double *rt1, double *rt2, double *cs1, npy_complex128 *sn1);
+void BLAS_FUNC(zlag2c)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info);
+void BLAS_FUNC(zlags2)(int *upper, double *a1, npy_complex128 *a2, double *a3, double *b1, npy_complex128 *b2, double *b3, double *csu, npy_complex128 *snu, double *csv, npy_complex128 *snv, double *csq, npy_complex128 *snq);
+void BLAS_FUNC(zlagtm)(char *trans, int *n, int *nrhs, double *alpha, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *x, int *ldx, double *beta, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlahef)(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info);
+void BLAS_FUNC(zlahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *info);
+void BLAS_FUNC(zlahr2)(int *n, int *k, int *nb, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *t, int *ldt, npy_complex128 *y, int *ldy);
+void BLAS_FUNC(zlaic1)(int *job, int *j, npy_complex128 *x, double *sest, npy_complex128 *w, npy_complex128 *gamma, double *sestpr, npy_complex128 *s, npy_complex128 *c);
+void BLAS_FUNC(zlals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *rwork, int *info);
+void BLAS_FUNC(zlalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, double *d, double *e, npy_complex128 *b, int *ldb, double *rcond, int *rank, npy_complex128 *work, double *rwork, int *iwork, int *info);
+double BLAS_FUNC(zlangb)(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlange)(char *norm, int *m, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlangt)(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d_, npy_complex128 *du);
+double BLAS_FUNC(zlanhb)(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlanhe)(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlanhf)(char *norm, char *transr, char *uplo, int *n, npy_complex128 *a, double *work);
+double BLAS_FUNC(zlanhp)(char *norm, char *uplo, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlanhs)(char *norm, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlanht)(char *norm, int *n, double *d_, npy_complex128 *e);
+double BLAS_FUNC(zlansb)(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlansp)(char *norm, char *uplo, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlansy)(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlantb)(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlantp)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlantr)(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex128 *a, int *lda, double *work);
+void BLAS_FUNC(zlapll)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *ssmin);
+void BLAS_FUNC(zlapmr)(int *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k);
+void BLAS_FUNC(zlapmt)(int *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k);
+void BLAS_FUNC(zlaqgb)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(zlaqge)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(zlaqhb)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqhe)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqhp)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqp2)(int *m, int *n, int *offset, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, double *vn1, double *vn2, npy_complex128 *work);
+void BLAS_FUNC(zlaqps)(int *m, int *n, int *offset, int *nb, int *kb, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, double *vn1, double *vn2, npy_complex128 *auxv, npy_complex128 *f, int *ldf);
+void BLAS_FUNC(zlaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlaqr1)(int *n, npy_complex128 *h, int *ldh, npy_complex128 *s1, npy_complex128 *s2, npy_complex128 *v);
+void BLAS_FUNC(zlaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork);
+void BLAS_FUNC(zlaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork);
+void BLAS_FUNC(zlaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex128 *s, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *v, int *ldv, npy_complex128 *u, int *ldu, int *nv, npy_complex128 *wv, int *ldwv, int *nh, npy_complex128 *wh, int *ldwh);
+void BLAS_FUNC(zlaqsb)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqsp)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqsy)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlar1v)(int *n, int *b1, int *bn, double *lambda_, double *d, double *l, double *ld, double *lld, double *pivmin, double *gaptol, npy_complex128 *z, int *wantnc, int *negcnt, double *ztz, double *mingma, int *r, int *isuppz, double *nrminv, double *resid, double *rqcorr, double *work);
+void BLAS_FUNC(zlar2v)(int *n, npy_complex128 *x, npy_complex128 *y, npy_complex128 *z, int *incx, double *c, npy_complex128 *s, int *incc);
+void BLAS_FUNC(zlarcm)(int *m, int *n, double *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, double *rwork);
+void BLAS_FUNC(zlarf)(char *side, int *m, int *n, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(zlarfg)(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau);
+void BLAS_FUNC(zlarfgp)(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau);
+void BLAS_FUNC(zlarft)(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt);
+void BLAS_FUNC(zlarfx)(char *side, int *m, int *n, npy_complex128 *v, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlargv)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *c, int *incc);
+void BLAS_FUNC(zlarnv)(int *idist, int *iseed, int *n, npy_complex128 *x);
+void BLAS_FUNC(zlarrv)(int *n, double *vl, double *vu, double *d, double *l, double *pivmin, int *isplit, int *m, int *dol, int *dou, double *minrgp, double *rtol1, double *rtol2, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, npy_complex128 *z, int *ldz, int *isuppz, double *work, int *iwork, int *info);
+void BLAS_FUNC(zlartg)(npy_complex128 *f, npy_complex128 *g, double *cs, npy_complex128 *sn, npy_complex128 *r);
+void BLAS_FUNC(zlartv)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *c, npy_complex128 *s, int *incc);
+void BLAS_FUNC(zlarz)(char *side, int *m, int *n, int *l, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(zlarzt)(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt);
+void BLAS_FUNC(zlascl)(char *type_bn, int *kl, int *ku, double *cfrom, double *cto, int *m, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zlaset)(char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zlasr)(char *side, char *pivot, char *direct, int *m, int *n, double *c, double *s, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zlassq)(int *n, npy_complex128 *x, int *incx, double *scale, double *sumsq);
+void BLAS_FUNC(zlaswp)(int *n, npy_complex128 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(zlasyf)(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info);
+void BLAS_FUNC(zlat2c)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info);
+void BLAS_FUNC(zlatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatdf)(int *ijob, int *n, npy_complex128 *z, int *ldz, npy_complex128 *rhs, double *rdsum, double *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(zlatps)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *ap, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatrd)(char *uplo, int *n, int *nb, npy_complex128 *a, int *lda, double *e, npy_complex128 *tau, npy_complex128 *w, int *ldw);
+void BLAS_FUNC(zlatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatrz)(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work);
+void BLAS_FUNC(zlauu2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zlauum)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpbcon)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbequ)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpbrfs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbstf)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbsv)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbtf2)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbtrf)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbtrs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpftrf)(char *transr, char *uplo, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(zpftri)(char *transr, char *uplo, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(zpftrs)(char *transr, char *uplo, int *n, int *nrhs, npy_complex128 *a, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpocon)(char *uplo, int *n, npy_complex128 *a, int *lda, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpoequ)(int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpoequb)(int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zporfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zposv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zposvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpotf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zppcon)(char *uplo, int *n, npy_complex128 *ap, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zppequ)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zppsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zppsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpptrf)(char *uplo, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(zpptri)(char *uplo, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(zpptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpstf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(zpstrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(zptcon)(int *n, double *d, npy_complex128 *e, double *anorm, double *rcond, double *rwork, int *info);
+void BLAS_FUNC(zpteqr)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(zptrfs)(char *uplo, int *n, int *nrhs, double *d, npy_complex128 *e, double *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zptsv)(int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zptsvx)(char *fact, int *n, int *nrhs, double *d, npy_complex128 *e, double *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpttrf)(int *n, double *d, npy_complex128 *e, int *info);
+void BLAS_FUNC(zpttrs)(char *uplo, int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zptts2)(int *iuplo, int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, npy_complex128 *s);
+void BLAS_FUNC(zspcon)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zspmv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zspr)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap);
+void BLAS_FUNC(zsprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zspsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zspsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zsptrf)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info);
+void BLAS_FUNC(zsptri)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zstedc)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zstegr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zstein)(int *n, double *d, double *e, int *m, double *w, int *iblock, int *isplit, npy_complex128 *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zstemr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, int *m, double *w, npy_complex128 *z, int *ldz, int *nzc, int *isuppz, int *tryrac, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zsteqr)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(zsycon)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsyconv)(char *uplo, char *way, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsyequb)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsymv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zsyr)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zsyrfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zsysv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsysvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zsyswapr)(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(zsytf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zsytrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsytri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsytri2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsytri2x)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info);
+void BLAS_FUNC(zsytrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zsytrs2)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex128 *ab, int *ldab, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztftri)(char *transr, char *uplo, char *diag, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(ztfttp)(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztfttr)(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztgevc)(char *side, char *howmny, int *select, int *n, npy_complex128 *s, int *lds, npy_complex128 *p, int *ldp, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztgex2)(int *wantq, int *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *j1, int *info);
+void BLAS_FUNC(ztgexc)(int *wantq, int *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ztgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *m, double *pl, double *pr, double *dif, npy_complex128 *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ztgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *tola, double *tolb, double *alpha, double *beta, npy_complex128 *u, int *ldu, npy_complex128 *v, int *ldv, npy_complex128 *q, int *ldq, npy_complex128 *work, int *ncycle, int *info);
+void BLAS_FUNC(ztgsna)(char *job, char *howmny, int *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, double *s, double *dif, int *mm, int *m, npy_complex128 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ztgsy2)(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, double *scale, double *rdsum, double *rdscal, int *info);
+void BLAS_FUNC(ztgsyl)(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, double *scale, double *dif, npy_complex128 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ztpcon)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztpqrt)(int *m, int *n, int *l, int *nb, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztpqrt2)(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(ztprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(ztprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztptri)(char *uplo, char *diag, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztpttf)(char *transr, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *arf, int *info);
+void BLAS_FUNC(ztpttr)(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrcon)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrevc)(char *side, char *howmny, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrexc)(char *compq, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ztrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrsen)(char *job, char *compq, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, npy_complex128 *w, int *m, double *s, double *sep, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(ztrsna)(char *job, char *howmny, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, double *s, double *sep, int *mm, int *m, npy_complex128 *work, int *ldwork, double *rwork, int *info);
+void BLAS_FUNC(ztrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, double *scale, int *info);
+void BLAS_FUNC(ztrti2)(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrtri)(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztrttf)(char *transr, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *arf, int *info);
+void BLAS_FUNC(ztrttp)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztzrzf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunbdb)(char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, double *theta, double *phi, npy_complex128 *taup1, npy_complex128 *taup2, npy_complex128 *tauq1, npy_complex128 *tauq2, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zuncsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, double *theta, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *info);
+void BLAS_FUNC(zung2l)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zung2r)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zungbr)(char *vect, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunghr)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungl2)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunglq)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungql)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungqr)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungr2)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zungrq)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungtr)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunm2l)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunm2r)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunml2)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmlq)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmql)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmqr)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmr2)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmr3)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmrq)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmrz)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zupgtr)(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info);
+void BLAS_FUNC(zupmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a0ba92af71f3f3188cc73ca441187db9701b052
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py
@@ -0,0 +1,867 @@
+#
+# Author: Travis Oliphant, March 2002
+#
+import warnings
+from itertools import product
+
+import numpy as np
+from numpy import (dot, diag, prod, logical_not, ravel, transpose,
+                   conjugate, absolute, amax, sign, isfinite, triu)
+
+# Local imports
+from scipy.linalg import LinAlgError, bandwidth
+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 ._matfuncs_sqrtm import sqrtm
+from ._matfuncs_expm import pick_pade_structure, pade_UV_calc
+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.
+
+
+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
+
+    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)
+
+
+def logm(A, disp=True):
+    """
+    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
+    disp : bool, optional
+        Emit warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    logm : (N, N) ndarray
+        Matrix logarithm of `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_1
+
+    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 disp:
+        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
+    else:
+        return F, errest
+
+
+def expm(A):
+    """Compute the matrix exponential of an array.
+
+    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)
+    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.
+
+    n = a.shape[-1]
+    eA = np.empty(a.shape, dtype=a.dtype)
+    # working memory to hold intermediate arrays
+    Am = np.empty((5, n, n), dtype=a.dtype)
+
+    # Main loop to go through the slices of an ndarray and passing to expm
+    for ind in product(*[range(x) for x in a.shape[:-2]]):
+        aw = a[ind]
+
+        lu = bandwidth(aw)
+        if not any(lu):  # a is diagonal?
+            eA[ind] = np.diag(np.exp(np.diag(aw)))
+            continue
+
+        # Generic/triangular case; copy the slice into scratch and send.
+        # Am will be mutated by pick_pade_structure
+        # If s != 0, scaled Am will be returned from pick_pade_structure.
+        Am[0, :, :] = aw
+        m, s = pick_pade_structure(Am)
+        if (m < 0):
+            raise MemoryError("scipy.linalg.expm could not allocate sufficient"
+                              " memory while trying to compute the Pade "
+                              f"structure (error code {m}).")
+        info = pade_UV_calc(Am, m)
+        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 got an internal LAPACK "
+                                   "error during the exponential computation "
+                                   f"(error code {info})")
+        eAw = Am[0]
+
+        if s != 0:  # squaring needed
+
+            if (lu[1] == 0) or (lu[0] == 0):  # lower/upper triangular
+                # This branch implements Code Fragment 2.1 of [1]
+
+                diag_aw = np.diag(aw)
+                # einsum returns a writable view
+                np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2**(-s))
+                # super/sub diagonal
+                sd = np.diag(aw, k=-1 if lu[1] == 0 else 1)
+
+                for i in range(s-1, -1, -1):
+                    eAw = eAw @ eAw
+
+                    # diagonal
+                    np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2.**(-i))
+                    exp_sd = _exp_sinch(diag_aw * (2.**(-i))) * (sd * 2**(-i))
+                    if lu[1] == 0:  # lower
+                        np.einsum('ii->i', eAw[1:, :-1])[:] = exp_sd
+                    else:  # upper
+                        np.einsum('ii->i', eAw[:-1, 1:])[:] = exp_sd
+
+            else:  # generic
+                for _ in range(s):
+                    eAw = eAw @ eAw
+
+        # Zero out the entries from np.empty in case of triangular input
+        if (lu[0] == 0) or (lu[1] == 0):
+            eA[ind] = np.triu(eAw) if lu[0] == 0 else np.tril(eAw)
+        else:
+            eA[ind] = eAw
+
+    return eA
+
+
+def _exp_sinch(x):
+    # Higham's formula (10.42), might overflow, see GH-11839
+    lexp_diff = np.diff(np.exp(x))
+    l_diff = np.diff(x)
+    mask_z = l_diff == 0.
+    lexp_diff[~mask_z] /= l_diff[~mask_z]
+    lexp_diff[mask_z] = np.exp(x[:-1][mask_z])
+    return lexp_diff
+
+
+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
+
+
+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
+
+
+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)))
+
+
+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)))
+
+
+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)))
+
+
+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)))
+
+
+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
+
+
+def signm(A, disp=True):
+    """
+    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
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    signm : (N, N) ndarray
+        Value of the sign function at `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_1
+
+    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])
+    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 disp:
+        if not isfinite(errest) or errest >= errtol:
+            print("signm result may be inaccurate, approximate err =", errest)
+        return S0
+    else:
+        return S0, errest
+
+
+def khatri_rao(a, b):
+    r"""
+    Khatri-rao product
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..98ca455c6eb06c1e95e6e11d3db2dc346a295fde
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi
@@ -0,0 +1,6 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def pick_pade_structure(a: NDArray[Any]) -> tuple[int, int]: ...
+
+def pade_UV_calc(Am: NDArray[Any], m: int) -> int: ...
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
new file mode 100644
index 0000000000000000000000000000000000000000..1decffae2e521f0a9325b873cc33b095a4e3c166
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
@@ -0,0 +1,886 @@
+"""
+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
+        self.ndim = A.ndim
+        self.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 : integer
+        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 : integer
+        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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7da6ced474ee3db548a24ecc08d7e2627f0d7a4
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py
@@ -0,0 +1,205 @@
+"""
+Matrix square root for general matrices and for upper triangular matrices.
+
+This module exists to avoid cyclic imports.
+
+"""
+__all__ = ['sqrtm']
+
+import numpy as np
+
+from scipy._lib._util import _asarray_validated
+
+# Local imports
+from ._misc import norm
+from .lapack import ztrsyl, dtrsyl
+from ._decomp_schur import schur, rsf2csf
+from ._basic import _ensure_dtype_cdsz
+
+
+
+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))
+
+    # 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]
+            if keep_it_real:
+                x, scale, info = dtrsyl(Rii, Rjj, S)
+            else:
+                x, scale, info = ztrsyl(Rii, Rjj, S)
+            R[istart:istop, jstart:jstop] = x * scale
+
+    # Return the matrix square root.
+    return R
+
+
+def sqrtm(A, disp=True, blocksize=64):
+    """
+    Matrix square root.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose square root to evaluate
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+    blocksize : integer, 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 `A`. The dtype is float or complex.
+        The precision (data size) is determined based on the precision of
+        input `A`.
+
+    errest : float
+        (if disp == False)
+
+        Frobenius norm of the estimated error, ||err||_F / ||A||_F
+
+    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.
+
+    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 = _asarray_validated(A, check_finite=True, as_inexact=True)
+    if len(A.shape) != 2:
+        raise ValueError("Non-matrix input to matrix function.")
+    if blocksize < 1:
+        raise ValueError("The blocksize should be at least 1.")
+    A, = _ensure_dtype_cdsz(A)
+    keep_it_real = np.isrealobj(A)
+    if keep_it_real:
+        T, Z = schur(A)
+        d0 = np.diagonal(T)
+        d1 = np.diagonal(T, -1)
+        eps = np.finfo(T.dtype).eps
+        needs_conversion = abs(d1) > eps * (abs(d0[1:]) + abs(d0[:-1]))
+        if needs_conversion.any():
+            T, Z = rsf2csf(T, Z)
+    else:
+        T, Z = schur(A, output='complex')
+    failflag = False
+    try:
+        R = _sqrtm_triu(T, blocksize=blocksize)
+        ZH = np.conjugate(Z).T
+        X = Z.dot(R).dot(ZH)
+        dtype = np.result_type(A.dtype, 1j if np.iscomplexobj(X) else 1)
+        X = X.astype(dtype, copy=False)
+    except SqrtmError:
+        failflag = True
+        X = np.empty_like(A)
+        X.fill(np.nan)
+
+    if disp:
+        if failflag:
+            print("Failed to find a square root.")
+        return X
+    else:
+        try:
+            arg2 = norm(X.dot(X) - A, 'fro')**2 / norm(A, 'fro')
+        except ValueError:
+            # NaNs in matrix
+            arg2 = np.inf
+
+        return X, arg2
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_misc.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..27cd442080c8569417694a8a612fe0a461c1a2ca
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_misc.py
@@ -0,0 +1,191 @@
+import numpy as np
+from numpy.linalg import LinAlgError
+from .blas import get_blas_funcs
+from .lapack import get_lapack_funcs
+
+__all__ = ['LinAlgError', 'LinAlgWarning', 'norm']
+
+
+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)
+
+    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
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d68f0b737ead5d581095ad32a34ae88d153264c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py
@@ -0,0 +1,111 @@
+"""
+Solve the orthogonal Procrustes problem.
+
+"""
+import numpy as np
+from ._decomp_svd import svd
+
+
+__all__ = ['orthogonal_procrustes']
+
+
+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.
+
+    .. versionadded:: 0.15.0
+
+    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
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+        B = np.asarray_chkfinite(B)
+    else:
+        A = np.asanyarray(A)
+        B = np.asanyarray(B)
+    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.
+    u, w, vt = svd((B.T @ np.conjugate(A)).T)
+    R = u @ vt
+    scale = w.sum()
+    return R, scale
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..589172827f528799203cb3e93a4a013e07dc5ff8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py
@@ -0,0 +1,178 @@
+""" 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)
+from scipy.sparse import csc_matrix
+
+__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_matrix
+        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.
+    """
+    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_matrix((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.
+
+    Parameters
+    ----------
+    input_matrix : array_like
+        Input matrix, of shape ``(n, d)``.
+    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_matrix`` 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()
+    >>> n_rows, n_columns, density, sketch_n_rows = 15000, 100, 0.01, 200
+    >>> A = sparse.rand(n_rows, n_columns, density=density, format='csc')
+    >>> B = sparse.rand(n_rows, n_columns, density=density, format='csr')
+    >>> C = sparse.rand(n_rows, n_columns, density=density, format='coo')
+    >>> D = rng.standard_normal((n_rows, n_columns))
+    >>> 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
+
+    """
+    S = cwt_matrix(sketch_size, input_matrix.shape[0], rng=rng)
+    return S.dot(input_matrix)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..60a6a73e7bf9cce36090137c0e884d3ed22c55a8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py
@@ -0,0 +1,857 @@
+"""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 ._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']
+
+
+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("Illegal value encountered in "
+                          "the %d term" % (-info,))
+
+    return np.dot(np.dot(u, y), v.conj().transpose())
+
+
+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)
+
+
+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.
+
+    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
+
+    """
+
+    # 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.
+
+    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
+
+    """
+
+    # 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dca572f2d5a12a27ccb468425f03c75e86d5da7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py
@@ -0,0 +1,1332 @@
+import math
+import warnings
+
+import numpy as np
+from numpy.lib.stride_tricks import as_strided
+
+
+__all__ = ['toeplitz', 'circulant', 'hankel',
+           'hadamard', 'leslie', 'kron', '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.
+
+    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:]]``.
+
+        .. warning::
+
+            Beginning in SciPy 1.17, 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 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.asarray(c)
+    if r is None:
+        r = c.conjugate()
+    else:
+        r = np.asarray(r)
+
+    if c.ndim > 1 or r.ndim > 1:
+        msg = ("Beginning in SciPy 1.17, 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 `toeplitz`.")
+        warnings.warn(msg, FutureWarning, stacklevel=2)
+
+    c, r = c.ravel(), r.ravel()
+    # 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.
+
+    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):
+    """
+    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. Whatever the actual shape of `c`, it
+        will be converted to a 1-D array.
+    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:]]``. Whatever the actual shape of `r`, it will be
+        converted to a 1-D array.
+
+    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).ravel()
+    if r is None:
+        r = np.zeros_like(c)
+    else:
+        r = np.asarray(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 an 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 an 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
+
+
+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.
+
+    Parameters
+    ----------
+    f : (..., N,) array_like
+        The "fecundity" coefficients.
+    s : (..., N-1,) array_like
+        The "survival" coefficients. The length of each slice of `s` (along the last
+        axis) 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`.
+        For 1-D input, the data-type of the array will be the data-type of
+        ``f[0]+s[0]``.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    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.
+
+    N-dimensional input are treated as a batches of coefficient arrays: each
+    slice along the last axis of the input arrays is a 1-D coefficient array,
+    and each slice along the last two dimensions of the output is the
+    corresponding Leslie matrix.
+
+    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]
+
+    if f.ndim > 1 or s.ndim > 1:
+        from scipy.stats._resampling import _vectorize_statistic
+        _leslie_nd = _vectorize_statistic(leslie)
+        return np.moveaxis(_leslie_nd(f, s, axis=-1), [0, 1], [-2, -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
+
+
+def kron(a, b):
+    """
+    Kronecker product.
+
+    .. deprecated:: 1.15.0
+        `kron` has been deprecated in favour of `numpy.kron` and will be
+        removed in SciPy 1.17.0.
+
+    The result is the block matrix::
+
+        a[0,0]*b    a[0,1]*b  ... a[0,-1]*b
+        a[1,0]*b    a[1,1]*b  ... a[1,-1]*b
+        ...
+        a[-1,0]*b   a[-1,1]*b ... a[-1,-1]*b
+
+    Parameters
+    ----------
+    a : (M, N) ndarray
+        Input array
+    b : (P, Q) ndarray
+        Input array
+
+    Returns
+    -------
+    A : (M*P, N*Q) ndarray
+        Kronecker product of `a` and `b`.
+
+    Examples
+    --------
+    >>> from numpy import array
+    >>> from scipy.linalg import kron
+    >>> kron(array([[1,2],[3,4]]), array([[1,1,1]]))
+    array([[1, 1, 1, 2, 2, 2],
+           [3, 3, 3, 4, 4, 4]])
+
+    """
+    msg = ("`kron` has been deprecated in favour of `numpy.kron` in SciPy"
+           " 1.15.0 and will be removed in SciPy 1.17.0.")
+    warnings.warn(msg, DeprecationWarning, stacklevel=2)
+    # accommodate empty arrays
+    if a.size == 0 or b.size == 0:
+        m = a.shape[0] * b.shape[0]
+        n = a.shape[1] * b.shape[1]
+        return np.empty_like(a, shape=(m, n))
+
+    if not a.flags['CONTIGUOUS']:
+        a = np.reshape(a, a.shape)
+    if not b.flags['CONTIGUOUS']:
+        b = np.reshape(b, b.shape)
+    o = np.outer(a, b)
+    o = o.reshape(a.shape + b.shape)
+    return np.concatenate(np.concatenate(o, axis=1), axis=1)
+
+
+def block_diag(*arrs):
+    """
+    Create a block diagonal matrix from provided arrays.
+
+    Given the inputs `A`, `B` and `C`, the output will have these
+    arrays arranged on the diagonal::
+
+        [[A, 0, 0],
+         [0, B, 0],
+         [0, 0, C]]
+
+    Parameters
+    ----------
+    A, B, C, ... : array_like, up to 2-D
+        Input arrays.  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. `D` has the
+        same dtype as `A`.
+
+    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.]])
+
+    """
+    if arrs == ():
+        arrs = ([],)
+    arrs = [np.atleast_2d(a) for a in arrs]
+
+    bad_args = [k for k in range(len(arrs)) if arrs[k].ndim > 2]
+    if bad_args:
+        raise ValueError("arguments in the following positions "
+                         f"have dimension greater than 2: {bad_args}")
+
+    shapes = np.array([a.shape for a in arrs])
+    out_dtype = np.result_type(*[arr.dtype for arr in arrs])
+    out = np.zeros(np.sum(shapes, axis=0), dtype=out_dtype)
+
+    r, c = 0, 0
+    for i, (rr, cc) in enumerate(shapes):
+        out[r:r + rr, c:c + cc] = 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`.
+
+    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 an 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
+
+
+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]_.
+
+    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
+
+    """
+    a = np.atleast_1d(a)
+
+    if a.ndim > 1:
+        return np.apply_along_axis(fiedler, -1, a)
+
+    if a.size == 0:
+        return np.array([], dtype=float)
+    elif a.size == 1:
+        return np.array([[0.]])
+    else:
+        return np.abs(a[:, None] - a)
+
+
+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``.
+
+    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]]])
+        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.
+
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6d01d2b6e59b040f39c0b53cc2788bbd3d0888f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py
@@ -0,0 +1,65 @@
+import numpy as np
+
+
+class _FakeMatrix:
+    def __init__(self, data):
+        self._data = data
+        self.__array_interface__ = data.__array_interface__
+
+
+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
+
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..04ef3645a2ed6a22106ed8ca1acf9e9ac93df5cf
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/blas.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..c943460e6bafcd9a382586d5a5155357382ea596
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/blas.py
@@ -0,0 +1,484 @@
+"""
+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`.
+
+Finding functions
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   get_blas_funcs
+   find_best_blas_type
+
+BLAS Level 1 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   caxpy
+   ccopy
+   cdotc
+   cdotu
+   crotg
+   cscal
+   csrot
+   csscal
+   cswap
+   dasum
+   daxpy
+   dcopy
+   ddot
+   dnrm2
+   drot
+   drotg
+   drotm
+   drotmg
+   dscal
+   dswap
+   dzasum
+   dznrm2
+   icamax
+   idamax
+   isamax
+   izamax
+   sasum
+   saxpy
+   scasum
+   scnrm2
+   scopy
+   sdot
+   snrm2
+   srot
+   srotg
+   srotm
+   srotmg
+   sscal
+   sswap
+   zaxpy
+   zcopy
+   zdotc
+   zdotu
+   zdrot
+   zdscal
+   zrotg
+   zscal
+   zswap
+
+BLAS Level 2 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgbmv
+   sgemv
+   sger
+   ssbmv
+   sspr
+   sspr2
+   ssymv
+   ssyr
+   ssyr2
+   stbmv
+   stpsv
+   strmv
+   strsv
+   dgbmv
+   dgemv
+   dger
+   dsbmv
+   dspr
+   dspr2
+   dsymv
+   dsyr
+   dsyr2
+   dtbmv
+   dtpsv
+   dtrmv
+   dtrsv
+   cgbmv
+   cgemv
+   cgerc
+   cgeru
+   chbmv
+   chemv
+   cher
+   cher2
+   chpmv
+   chpr
+   chpr2
+   ctbmv
+   ctbsv
+   ctpmv
+   ctpsv
+   ctrmv
+   ctrsv
+   csyr
+   zgbmv
+   zgemv
+   zgerc
+   zgeru
+   zhbmv
+   zhemv
+   zher
+   zher2
+   zhpmv
+   zhpr
+   zhpr2
+   ztbmv
+   ztbsv
+   ztpmv
+   ztrmv
+   ztrsv
+   zsyr
+
+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.linalg import _fblas
+try:
+    from scipy.linalg import _cblas
+except ImportError:
+    _cblas = None
+
+try:
+    from scipy.linalg import _fblas_64
+    HAS_ILP64 = True
+except ImportError:
+    HAS_ILP64 = False
+    _fblas_64 = None
+
+# Expose all functions (only fblas --- cblas is an implementation detail)
+empty_module = None
+from scipy.linalg._fblas import *  # noqa: E402, F403
+del empty_module
+
+# 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, cmodule,
+               fmodule_name, cmodule_name, alias,
+               ilp64=False):
+    """
+    Return available BLAS/LAPACK functions.
+
+    Used also in lapack.py. See get_blas_funcs for docstring.
+    """
+
+    funcs = []
+    unpack = False
+    dtype = np.dtype(dtype)
+    module1 = (cmodule, cmodule_name)
+    module2 = (fmodule, fmodule_name)
+
+    if isinstance(names, str):
+        names = (names,)
+        unpack = True
+
+    prefix, dtype, prefer_fortran = find_best_blas_type(arrays, dtype)
+
+    if prefer_fortran:
+        module1, module2 = module2, module1
+
+    for name in names:
+        func_name = prefix + name
+        func_name = alias.get(func_name, func_name)
+        func = getattr(module1[0], func_name, None)
+        module_name = module1[1]
+        if func is None:
+            func = getattr(module2[0], func_name, None)
+            module_name = module2[1]
+        if func is None:
+            raise ValueError(
+                f'{lib_name} function {func_name} could not be found')
+        func.module_name, func.typecode = module_name, prefix
+        func.dtype = 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=False):
+        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=False):
+    """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 routine. Default: False
+
+    Returns
+    -------
+    funcs : list
+        List containing the found function(s).
+
+
+    Notes
+    -----
+    This routine automatically chooses between Fortran/C
+    interfaces. Fortran code is used whenever possible for arrays with
+    column major order. In all other cases, C code is preferred.
+
+    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,))
+    >>> x_gemv.typecode
+    'd'
+    >>> x_gemv = LA.get_blas_funcs('gemv',(a*1j,))
+    >>> x_gemv.typecode
+    'z'
+
+    """
+    if isinstance(ilp64, str):
+        if ilp64 == 'preferred':
+            ilp64 = HAS_ILP64
+        else:
+            raise ValueError("Invalid value for 'ilp64'")
+
+    if not ilp64:
+        return _get_funcs(names, arrays, dtype,
+                          "BLAS", _fblas, _cblas, "fblas", "cblas",
+                          _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, None, "fblas_64", None,
+                          _blas_alias, ilp64=True)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..7ed44f6ea8611f926e3ea5fd2670446cdf9b398c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd
@@ -0,0 +1,169 @@
+"""
+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
+
+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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..35286fe11d72226269c0e459d9a3109151f74a4a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx
@@ -0,0 +1,1432 @@
+# This file was generated by _generate_pyx.py.
+# Do not edit this file directly.
+# cython: boundscheck = False
+# cython: wraparound = False
+# cython: cdivision = True
+
+"""
+BLAS Functions for Cython
+=========================
+
+Usable from Cython via::
+
+    cimport scipy.linalg.cython_blas
+
+These wrappers do not check for alignment of arrays.
+Alignment should be checked before these wrappers are used.
+
+If using ``cdotu``, ``cdotc``, ``zdotu``, ``zdotc``, ``sladiv``, or ``dladiv``,
+the ``CYTHON_CCOMPLEX`` define must be set to 0 during compilation. For
+example, in a ``meson.build`` file when using Meson::
+
+    py.extension_module('ext_module'
+        'ext_module.pyx',
+        c_args: ['-DCYTHON_CCOMPLEX=0'],
+        ...
+    )
+
+Raw function pointers (Fortran-style pointer arguments):
+
+- caxpy
+- ccopy
+- cdotc
+- cdotu
+- cgbmv
+- cgemm
+- cgemv
+- cgerc
+- cgeru
+- chbmv
+- chemm
+- chemv
+- cher
+- cher2
+- cher2k
+- cherk
+- chpmv
+- chpr
+- chpr2
+- crotg
+- cscal
+- csrot
+- csscal
+- cswap
+- csymm
+- csyr2k
+- csyrk
+- ctbmv
+- ctbsv
+- ctpmv
+- ctpsv
+- ctrmm
+- ctrmv
+- ctrsm
+- ctrsv
+- dasum
+- daxpy
+- dcabs1
+- dcopy
+- ddot
+- dgbmv
+- dgemm
+- dgemv
+- dger
+- dnrm2
+- drot
+- drotg
+- drotm
+- drotmg
+- dsbmv
+- dscal
+- dsdot
+- dspmv
+- dspr
+- dspr2
+- dswap
+- dsymm
+- dsymv
+- dsyr
+- dsyr2
+- dsyr2k
+- dsyrk
+- dtbmv
+- dtbsv
+- dtpmv
+- dtpsv
+- dtrmm
+- dtrmv
+- dtrsm
+- dtrsv
+- dzasum
+- dznrm2
+- icamax
+- idamax
+- isamax
+- izamax
+- lsame
+- sasum
+- saxpy
+- scasum
+- scnrm2
+- scopy
+- sdot
+- sdsdot
+- sgbmv
+- sgemm
+- sgemv
+- sger
+- snrm2
+- srot
+- srotg
+- srotm
+- srotmg
+- ssbmv
+- sscal
+- sspmv
+- sspr
+- sspr2
+- sswap
+- ssymm
+- ssymv
+- ssyr
+- ssyr2
+- ssyr2k
+- ssyrk
+- stbmv
+- stbsv
+- stpmv
+- stpsv
+- strmm
+- strmv
+- strsm
+- strsv
+- zaxpy
+- zcopy
+- zdotc
+- zdotu
+- zdrot
+- zdscal
+- zgbmv
+- zgemm
+- zgemv
+- zgerc
+- zgeru
+- zhbmv
+- zhemm
+- zhemv
+- zher
+- zher2
+- zher2k
+- zherk
+- zhpmv
+- zhpr
+- zhpr2
+- zrotg
+- zscal
+- zswap
+- zsymm
+- zsyr2k
+- zsyrk
+- ztbmv
+- ztbsv
+- ztpmv
+- ztpsv
+- ztrmm
+- ztrmv
+- ztrsm
+- ztrsv
+
+
+"""
+
+# 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.
+
+cdef extern from "fortran_defs.h":
+    pass
+
+from numpy cimport npy_complex64, npy_complex128
+
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_caxpy "BLAS_FUNC(caxpy)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_caxpy(n, ca, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ccopy "BLAS_FUNC(ccopy)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_ccopy(n, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cdotc "F_FUNC(cdotcwrp,CDOTCWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    cdef c out
+    _fortran_cdotc(&out, n, cx, incx, cy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cdotu "F_FUNC(cdotuwrp,CDOTUWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    cdef c out
+    _fortran_cdotu(&out, n, cx, incx, cy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgbmv "BLAS_FUNC(cgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) 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:
+    
+    _fortran_cgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgemm "BLAS_FUNC(cgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) 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:
+    
+    _fortran_cgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgemv "BLAS_FUNC(cgemv)"(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) 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:
+    
+    _fortran_cgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgerc "BLAS_FUNC(cgerc)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cgerc(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgeru "BLAS_FUNC(cgeru)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cgeru(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chbmv "BLAS_FUNC(chbmv)"(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) 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:
+    
+    _fortran_chbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chemm "BLAS_FUNC(chemm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) 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:
+    
+    _fortran_chemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chemv "BLAS_FUNC(chemv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) 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:
+    
+    _fortran_chemv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher "BLAS_FUNC(cher)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil
+cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cher(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher2 "BLAS_FUNC(cher2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cher2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher2k "BLAS_FUNC(cher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *beta, npy_complex64 *c, int *ldc) 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:
+    
+    _fortran_cher2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cherk "BLAS_FUNC(cherk)"(char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c, int *ldc) 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:
+    
+    _fortran_cherk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpmv "BLAS_FUNC(chpmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_chpmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpr "BLAS_FUNC(chpr)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil
+cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil:
+    
+    _fortran_chpr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpr2 "BLAS_FUNC(chpr2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap) nogil
+cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil:
+    
+    _fortran_chpr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_crotg "BLAS_FUNC(crotg)"(npy_complex64 *ca, npy_complex64 *cb, s *c, npy_complex64 *s) nogil
+cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil:
+    
+    _fortran_crotg(ca, cb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cscal "BLAS_FUNC(cscal)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx) nogil
+cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil:
+    
+    _fortran_cscal(n, ca, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csrot "BLAS_FUNC(csrot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, s *s) nogil
+cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil:
+    
+    _fortran_csrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csscal "BLAS_FUNC(csscal)"(int *n, s *sa, npy_complex64 *cx, int *incx) nogil
+cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil:
+    
+    _fortran_csscal(n, sa, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cswap "BLAS_FUNC(cswap)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_cswap(n, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csymm "BLAS_FUNC(csymm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) 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:
+    
+    _fortran_csymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csyr2k "BLAS_FUNC(csyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) 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:
+    
+    _fortran_csyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csyrk "BLAS_FUNC(csyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc) 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:
+    
+    _fortran_csyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctbmv "BLAS_FUNC(ctbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctbsv "BLAS_FUNC(ctbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctpmv "BLAS_FUNC(ctpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil
+cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctpsv "BLAS_FUNC(ctpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil
+cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrmm "BLAS_FUNC(ctrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) 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:
+    
+    _fortran_ctrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrmv "BLAS_FUNC(ctrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrsm "BLAS_FUNC(ctrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) 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:
+    
+    _fortran_ctrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrsv "BLAS_FUNC(ctrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dasum "BLAS_FUNC(dasum)"(int *n, d *dx, int *incx) nogil
+cdef d dasum(int *n, d *dx, int *incx) noexcept nogil:
+    
+    return _fortran_dasum(n, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_daxpy "BLAS_FUNC(daxpy)"(int *n, d *da, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_daxpy(n, da, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dcabs1 "BLAS_FUNC(dcabs1)"(npy_complex128 *z) nogil
+cdef d dcabs1(z *z) noexcept nogil:
+    
+    return _fortran_dcabs1(z)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dcopy "BLAS_FUNC(dcopy)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_dcopy(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_ddot "BLAS_FUNC(ddot)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    return _fortran_ddot(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgbmv "BLAS_FUNC(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) 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:
+    
+    _fortran_dgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgemm "BLAS_FUNC(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) 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:
+    
+    _fortran_dgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgemv "BLAS_FUNC(dgemv)"(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) 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:
+    
+    _fortran_dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dger "BLAS_FUNC(dger)"(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil
+cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dger(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dnrm2 "BLAS_FUNC(dnrm2)"(int *n, d *x, int *incx) nogil
+cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil:
+    
+    return _fortran_dnrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drot "BLAS_FUNC(drot)"(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) nogil
+cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil:
+    
+    _fortran_drot(n, dx, incx, dy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotg "BLAS_FUNC(drotg)"(d *da, d *db, d *c, d *s) nogil
+cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil:
+    
+    _fortran_drotg(da, db, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotm "BLAS_FUNC(drotm)"(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) nogil
+cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil:
+    
+    _fortran_drotm(n, dx, incx, dy, incy, dparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotmg "BLAS_FUNC(drotmg)"(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) nogil
+cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil:
+    
+    _fortran_drotmg(dd1, dd2, dx1, dy1, dparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsbmv "BLAS_FUNC(dsbmv)"(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) 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:
+    
+    _fortran_dsbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dscal "BLAS_FUNC(dscal)"(int *n, d *da, d *dx, int *incx) nogil
+cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil:
+    
+    _fortran_dscal(n, da, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dsdot "BLAS_FUNC(dsdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_dsdot(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspmv "BLAS_FUNC(dspmv)"(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspr "BLAS_FUNC(dspr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) nogil
+cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil:
+    
+    _fortran_dspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspr2 "BLAS_FUNC(dspr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) nogil
+cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil:
+    
+    _fortran_dspr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dswap "BLAS_FUNC(dswap)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_dswap(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsymm "BLAS_FUNC(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) 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:
+    
+    _fortran_dsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsymv "BLAS_FUNC(dsymv)"(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) 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:
+    
+    _fortran_dsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr "BLAS_FUNC(dsyr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) nogil
+cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dsyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr2 "BLAS_FUNC(dsyr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil
+cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dsyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr2k "BLAS_FUNC(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) 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:
+    
+    _fortran_dsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyrk "BLAS_FUNC(dsyrk)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) 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:
+    
+    _fortran_dsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtbmv "BLAS_FUNC(dtbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtbsv "BLAS_FUNC(dtbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtpmv "BLAS_FUNC(dtpmv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil
+cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtpsv "BLAS_FUNC(dtpsv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil
+cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrmm "BLAS_FUNC(dtrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) 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:
+    
+    _fortran_dtrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrmv "BLAS_FUNC(dtrmv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrsm "BLAS_FUNC(dtrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) 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:
+    
+    _fortran_dtrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrsv "BLAS_FUNC(dtrsv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dzasum "BLAS_FUNC(dzasum)"(int *n, npy_complex128 *zx, int *incx) nogil
+cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil:
+    
+    return _fortran_dzasum(n, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dznrm2 "BLAS_FUNC(dznrm2)"(int *n, npy_complex128 *x, int *incx) nogil
+cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil:
+    
+    return _fortran_dznrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_icamax "BLAS_FUNC(icamax)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef int icamax(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_icamax(n, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_idamax "BLAS_FUNC(idamax)"(int *n, d *dx, int *incx) nogil
+cdef int idamax(int *n, d *dx, int *incx) noexcept nogil:
+    
+    return _fortran_idamax(n, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_isamax "BLAS_FUNC(isamax)"(int *n, s *sx, int *incx) nogil
+cdef int isamax(int *n, s *sx, int *incx) noexcept nogil:
+    
+    return _fortran_isamax(n, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_izamax "BLAS_FUNC(izamax)"(int *n, npy_complex128 *zx, int *incx) nogil
+cdef int izamax(int *n, z *zx, int *incx) noexcept nogil:
+    
+    return _fortran_izamax(n, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    bint _fortran_lsame "BLAS_FUNC(lsame)"(char *ca, char *cb) nogil
+cdef bint lsame(char *ca, char *cb) noexcept nogil:
+    
+    return _fortran_lsame(ca, cb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sasum "BLAS_FUNC(sasum)"(int *n, s *sx, int *incx) nogil
+cdef s sasum(int *n, s *sx, int *incx) noexcept nogil:
+    
+    return _fortran_sasum(n, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_saxpy "BLAS_FUNC(saxpy)"(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_saxpy(n, sa, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_scasum "BLAS_FUNC(scasum)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef s scasum(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_scasum(n, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_scnrm2 "BLAS_FUNC(scnrm2)"(int *n, npy_complex64 *x, int *incx) nogil
+cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil:
+    
+    return _fortran_scnrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_scopy "BLAS_FUNC(scopy)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_scopy(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sdot "BLAS_FUNC(sdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_sdot(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sdsdot "BLAS_FUNC(sdsdot)"(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) nogil
+cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_sdsdot(n, sb, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgbmv "BLAS_FUNC(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) 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:
+    
+    _fortran_sgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgemm "BLAS_FUNC(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) 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:
+    
+    _fortran_sgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgemv "BLAS_FUNC(sgemv)"(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) 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:
+    
+    _fortran_sgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sger "BLAS_FUNC(sger)"(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil
+cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil:
+    
+    _fortran_sger(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_snrm2 "BLAS_FUNC(snrm2)"(int *n, s *x, int *incx) nogil
+cdef s snrm2(int *n, s *x, int *incx) noexcept nogil:
+    
+    return _fortran_snrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srot "BLAS_FUNC(srot)"(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) nogil
+cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil:
+    
+    _fortran_srot(n, sx, incx, sy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotg "BLAS_FUNC(srotg)"(s *sa, s *sb, s *c, s *s) nogil
+cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil:
+    
+    _fortran_srotg(sa, sb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotm "BLAS_FUNC(srotm)"(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) nogil
+cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil:
+    
+    _fortran_srotm(n, sx, incx, sy, incy, sparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotmg "BLAS_FUNC(srotmg)"(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) nogil
+cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil:
+    
+    _fortran_srotmg(sd1, sd2, sx1, sy1, sparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssbmv "BLAS_FUNC(ssbmv)"(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) 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:
+    
+    _fortran_ssbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sscal "BLAS_FUNC(sscal)"(int *n, s *sa, s *sx, int *incx) nogil
+cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil:
+    
+    _fortran_sscal(n, sa, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspmv "BLAS_FUNC(sspmv)"(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_sspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspr "BLAS_FUNC(sspr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) nogil
+cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil:
+    
+    _fortran_sspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspr2 "BLAS_FUNC(sspr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) nogil
+cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil:
+    
+    _fortran_sspr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sswap "BLAS_FUNC(sswap)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_sswap(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssymm "BLAS_FUNC(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) 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:
+    
+    _fortran_ssymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssymv "BLAS_FUNC(ssymv)"(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) 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:
+    
+    _fortran_ssymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr "BLAS_FUNC(ssyr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) nogil
+cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil:
+    
+    _fortran_ssyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr2 "BLAS_FUNC(ssyr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil
+cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil:
+    
+    _fortran_ssyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr2k "BLAS_FUNC(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) 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:
+    
+    _fortran_ssyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyrk "BLAS_FUNC(ssyrk)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) 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:
+    
+    _fortran_ssyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stbmv "BLAS_FUNC(stbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil
+cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stbsv "BLAS_FUNC(stbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil
+cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stpmv "BLAS_FUNC(stpmv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil
+cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stpsv "BLAS_FUNC(stpsv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil
+cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strmm "BLAS_FUNC(strmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) 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:
+    
+    _fortran_strmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strmv "BLAS_FUNC(strmv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil
+cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_strmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strsm "BLAS_FUNC(strsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) 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:
+    
+    _fortran_strsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strsv "BLAS_FUNC(strsv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil
+cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_strsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zaxpy "BLAS_FUNC(zaxpy)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zaxpy(n, za, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zcopy "BLAS_FUNC(zcopy)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zcopy(n, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdotc "F_FUNC(zdotcwrp,ZDOTCWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    cdef z out
+    _fortran_zdotc(&out, n, zx, incx, zy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdotu "F_FUNC(zdotuwrp,ZDOTUWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    cdef z out
+    _fortran_zdotu(&out, n, zx, incx, zy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdrot "BLAS_FUNC(zdrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, d *s) nogil
+cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil:
+    
+    _fortran_zdrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdscal "BLAS_FUNC(zdscal)"(int *n, d *da, npy_complex128 *zx, int *incx) nogil
+cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil:
+    
+    _fortran_zdscal(n, da, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgbmv "BLAS_FUNC(zgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) 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:
+    
+    _fortran_zgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgemm "BLAS_FUNC(zgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) 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:
+    
+    _fortran_zgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgemv "BLAS_FUNC(zgemv)"(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) 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:
+    
+    _fortran_zgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgerc "BLAS_FUNC(zgerc)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zgerc(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgeru "BLAS_FUNC(zgeru)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zgeru(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhbmv "BLAS_FUNC(zhbmv)"(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) 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:
+    
+    _fortran_zhbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhemm "BLAS_FUNC(zhemm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) 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:
+    
+    _fortran_zhemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhemv "BLAS_FUNC(zhemv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) 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:
+    
+    _fortran_zhemv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher "BLAS_FUNC(zher)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil
+cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zher(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher2 "BLAS_FUNC(zher2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zher2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher2k "BLAS_FUNC(zher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *beta, npy_complex128 *c, int *ldc) 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:
+    
+    _fortran_zher2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zherk "BLAS_FUNC(zherk)"(char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c, int *ldc) 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:
+    
+    _fortran_zherk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpmv "BLAS_FUNC(zhpmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zhpmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpr "BLAS_FUNC(zhpr)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil
+cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil:
+    
+    _fortran_zhpr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpr2 "BLAS_FUNC(zhpr2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap) nogil
+cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil:
+    
+    _fortran_zhpr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zrotg "BLAS_FUNC(zrotg)"(npy_complex128 *ca, npy_complex128 *cb, d *c, npy_complex128 *s) nogil
+cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil:
+    
+    _fortran_zrotg(ca, cb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zscal "BLAS_FUNC(zscal)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx) nogil
+cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil:
+    
+    _fortran_zscal(n, za, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zswap "BLAS_FUNC(zswap)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zswap(n, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsymm "BLAS_FUNC(zsymm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) 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:
+    
+    _fortran_zsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsyr2k "BLAS_FUNC(zsyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) 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:
+    
+    _fortran_zsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsyrk "BLAS_FUNC(zsyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc) 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:
+    
+    _fortran_zsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztbmv "BLAS_FUNC(ztbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztbsv "BLAS_FUNC(ztbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztpmv "BLAS_FUNC(ztpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil
+cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztpsv "BLAS_FUNC(ztpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil
+cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrmm "BLAS_FUNC(ztrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) 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:
+    
+    _fortran_ztrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrmv "BLAS_FUNC(ztrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrsm "BLAS_FUNC(ztrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) 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:
+    
+    _fortran_ztrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrsv "BLAS_FUNC(ztrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+
+# Python-accessible wrappers for testing:
+
+cdef inline bint _is_contiguous(double[:,:] a, int axis) noexcept nogil:
+    return (a.strides[axis] == sizeof(a[0,0]) or a.shape[axis] == 1)
+
+cpdef float complex _test_cdotc(float complex[:] cx, float complex[:] cy) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotc(&n, &cx[0], &incx, &cy[0], &incy)
+
+cpdef float complex _test_cdotu(float complex[:] cx, float complex[:] cy) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
+
+cpdef double _test_dasum(double[:] dx) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+    return dasum(&n, &dx[0], &incx)
+
+cpdef double _test_ddot(double[:] dx, double[:] dy) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+        int incy = dy.strides[0] // sizeof(dy[0])
+    return ddot(&n, &dx[0], &incx, &dy[0], &incy)
+
+cpdef int _test_dgemm(double alpha, double[:,:] a, double[:,:] b, double beta,
+                double[:,:] c) except -1 nogil:
+    cdef:
+        char *transa
+        char *transb
+        int m, n, k, lda, ldb, ldc
+        double *a0=&a[0,0]
+        double *b0=&b[0,0]
+        double *c0=&c[0,0]
+    # In the case that c is C contiguous, swap a and b and
+    # swap whether or not each of them is transposed.
+    # This can be done because a.dot(b) = b.T.dot(a.T).T.
+    if _is_contiguous(c, 1):
+        if _is_contiguous(a, 1):
+            transb = 'n'
+            ldb = (&a[1,0]) - a0 if a.shape[0] > 1 else 1
+        elif _is_contiguous(a, 0):
+            transb = 't'
+            ldb = (&a[0,1]) - a0 if a.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'a' is neither C nor Fortran contiguous.")
+        if _is_contiguous(b, 1):
+            transa = 'n'
+            lda = (&b[1,0]) - b0 if b.shape[0] > 1 else 1
+        elif _is_contiguous(b, 0):
+            transa = 't'
+            lda = (&b[0,1]) - b0 if b.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'b' is neither C nor Fortran contiguous.")
+        k = b.shape[0]
+        if k != a.shape[1]:
+            with gil:
+                raise ValueError("Shape mismatch in input arrays.")
+        m = b.shape[1]
+        n = a.shape[0]
+        if n != c.shape[0] or m != c.shape[1]:
+            with gil:
+                raise ValueError("Output array does not have the correct shape.")
+        ldc = (&c[1,0]) - c0 if c.shape[0] > 1 else 1
+        dgemm(transa, transb, &m, &n, &k, &alpha, b0, &lda, a0,
+                   &ldb, &beta, c0, &ldc)
+    elif _is_contiguous(c, 0):
+        if _is_contiguous(a, 1):
+            transa = 't'
+            lda = (&a[1,0]) - a0 if a.shape[0] > 1 else 1
+        elif _is_contiguous(a, 0):
+            transa = 'n'
+            lda = (&a[0,1]) - a0 if a.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'a' is neither C nor Fortran contiguous.")
+        if _is_contiguous(b, 1):
+            transb = 't'
+            ldb = (&b[1,0]) - b0 if b.shape[0] > 1 else 1
+        elif _is_contiguous(b, 0):
+            transb = 'n'
+            ldb = (&b[0,1]) - b0 if b.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'b' is neither C nor Fortran contiguous.")
+        m = a.shape[0]
+        k = a.shape[1]
+        if k != b.shape[0]:
+            with gil:
+                raise ValueError("Shape mismatch in input arrays.")
+        n = b.shape[1]
+        if m != c.shape[0] or n != c.shape[1]:
+            with gil:
+                raise ValueError("Output array does not have the correct shape.")
+        ldc = (&c[0,1]) - c0 if c.shape[1] > 1 else 1
+        dgemm(transa, transb, &m, &n, &k, &alpha, a0, &lda, b0,
+                   &ldb, &beta, c0, &ldc)
+    else:
+        with gil:
+            raise ValueError("Input 'c' is neither C nor Fortran contiguous.")
+    return 0
+
+cpdef double _test_dnrm2(double[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return dnrm2(&n, &x[0], &incx)
+
+cpdef double _test_dzasum(double complex[:] zx) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+    return dzasum(&n, &zx[0], &incx)
+
+cpdef double _test_dznrm2(double complex[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return dznrm2(&n, &x[0], &incx)
+
+cpdef int _test_icamax(float complex[:] cx) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+    return icamax(&n, &cx[0], &incx)
+
+cpdef int _test_idamax(double[:] dx) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+    return idamax(&n, &dx[0], &incx)
+
+cpdef int _test_isamax(float[:] sx) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+    return isamax(&n, &sx[0], &incx)
+
+cpdef int _test_izamax(double complex[:] zx) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+    return izamax(&n, &zx[0], &incx)
+
+cpdef float _test_sasum(float[:] sx) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+    return sasum(&n, &sx[0], &incx)
+
+cpdef float _test_scasum(float complex[:] cx) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+    return scasum(&n, &cx[0], &incx)
+
+cpdef float _test_scnrm2(float complex[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return scnrm2(&n, &x[0], &incx)
+
+cpdef float _test_sdot(float[:] sx, float[:] sy) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+        int incy = sy.strides[0] // sizeof(sy[0])
+    return sdot(&n, &sx[0], &incx, &sy[0], &incy)
+
+cpdef float _test_snrm2(float[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return snrm2(&n, &x[0], &incx)
+
+cpdef double complex _test_zdotc(double complex[:] zx, double complex[:] zy) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+        int incy = zy.strides[0] // sizeof(zy[0])
+    return zdotc(&n, &zx[0], &incx, &zy[0], &incy)
+
+cpdef double complex _test_zdotu(double complex[:] zx, double complex[:] zy) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+        int incy = zy.strides[0] // sizeof(zy[0])
+    return zdotu(&n, &zx[0], &incx, &zy[0], &incy)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..7964c52d766cd1b08bda6411960a29dbeb6bfe2d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd
@@ -0,0 +1,1528 @@
+"""
+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
+
+# Function pointer type declarations for
+# gees and gges families of functions.
+ctypedef bint cselect1(c*)
+ctypedef bint cselect2(c*, c*)
+ctypedef bint dselect2(d*, d*)
+ctypedef bint dselect3(d*, d*, d*)
+ctypedef bint sselect2(s*, s*)
+ctypedef bint sselect3(s*, s*, s*)
+ctypedef bint zselect1(z*)
+ctypedef bint 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..7f9cbfbb519603d4107af51ac353e0650720cf8c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx
@@ -0,0 +1,12045 @@
+# This file was generated by _generate_pyx.py.
+# Do not edit this file directly.
+"""
+LAPACK functions for Cython
+===========================
+
+Usable from Cython via::
+
+    cimport scipy.linalg.cython_lapack
+
+This module provides Cython-level wrappers for all primary routines included
+in LAPACK 3.4.0 except for ``zcgesv`` since its interface is not consistent
+from LAPACK 3.4.0 to 3.6.0. It also provides some of the
+fixed-api auxiliary routines.
+
+These wrappers do not check for alignment of arrays.
+Alignment should be checked before these wrappers are used.
+
+Raw function pointers (Fortran-style pointer arguments):
+
+- cbbcsd
+- cbdsqr
+- cgbbrd
+- cgbcon
+- cgbequ
+- cgbequb
+- cgbrfs
+- cgbsv
+- cgbsvx
+- cgbtf2
+- cgbtrf
+- cgbtrs
+- cgebak
+- cgebal
+- cgebd2
+- cgebrd
+- cgecon
+- cgeequ
+- cgeequb
+- cgees
+- cgeesx
+- cgeev
+- cgeevx
+- cgehd2
+- cgehrd
+- cgelq2
+- cgelqf
+- cgels
+- cgelsd
+- cgelss
+- cgelsy
+- cgemqrt
+- cgeql2
+- cgeqlf
+- cgeqp3
+- cgeqr2
+- cgeqr2p
+- cgeqrf
+- cgeqrfp
+- cgeqrt
+- cgeqrt2
+- cgeqrt3
+- cgerfs
+- cgerq2
+- cgerqf
+- cgesc2
+- cgesdd
+- cgesv
+- cgesvd
+- cgesvx
+- cgetc2
+- cgetf2
+- cgetrf
+- cgetri
+- cgetrs
+- cggbak
+- cggbal
+- cgges
+- cggesx
+- cggev
+- cggevx
+- cggglm
+- cgghrd
+- cgglse
+- cggqrf
+- cggrqf
+- cgtcon
+- cgtrfs
+- cgtsv
+- cgtsvx
+- cgttrf
+- cgttrs
+- cgtts2
+- chbev
+- chbevd
+- chbevx
+- chbgst
+- chbgv
+- chbgvd
+- chbgvx
+- chbtrd
+- checon
+- cheequb
+- cheev
+- cheevd
+- cheevr
+- cheevx
+- chegs2
+- chegst
+- chegv
+- chegvd
+- chegvx
+- cherfs
+- chesv
+- chesvx
+- cheswapr
+- chetd2
+- chetf2
+- chetrd
+- chetrf
+- chetri
+- chetri2
+- chetri2x
+- chetrs
+- chetrs2
+- chfrk
+- chgeqz
+- chla_transtype
+- chpcon
+- chpev
+- chpevd
+- chpevx
+- chpgst
+- chpgv
+- chpgvd
+- chpgvx
+- chprfs
+- chpsv
+- chpsvx
+- chptrd
+- chptrf
+- chptri
+- chptrs
+- chsein
+- chseqr
+- clabrd
+- clacgv
+- clacn2
+- clacon
+- clacp2
+- clacpy
+- clacrm
+- clacrt
+- cladiv
+- claed0
+- claed7
+- claed8
+- claein
+- claesy
+- claev2
+- clag2z
+- clags2
+- clagtm
+- clahef
+- clahqr
+- clahr2
+- claic1
+- clals0
+- clalsa
+- clalsd
+- clangb
+- clange
+- clangt
+- clanhb
+- clanhe
+- clanhf
+- clanhp
+- clanhs
+- clanht
+- clansb
+- clansp
+- clansy
+- clantb
+- clantp
+- clantr
+- clapll
+- clapmr
+- clapmt
+- claqgb
+- claqge
+- claqhb
+- claqhe
+- claqhp
+- claqp2
+- claqps
+- claqr0
+- claqr1
+- claqr2
+- claqr3
+- claqr4
+- claqr5
+- claqsb
+- claqsp
+- claqsy
+- clar1v
+- clar2v
+- clarcm
+- clarf
+- clarfb
+- clarfg
+- clarfgp
+- clarft
+- clarfx
+- clargv
+- clarnv
+- clarrv
+- clartg
+- clartv
+- clarz
+- clarzb
+- clarzt
+- clascl
+- claset
+- clasr
+- classq
+- claswp
+- clasyf
+- clatbs
+- clatdf
+- clatps
+- clatrd
+- clatrs
+- clatrz
+- clauu2
+- clauum
+- cpbcon
+- cpbequ
+- cpbrfs
+- cpbstf
+- cpbsv
+- cpbsvx
+- cpbtf2
+- cpbtrf
+- cpbtrs
+- cpftrf
+- cpftri
+- cpftrs
+- cpocon
+- cpoequ
+- cpoequb
+- cporfs
+- cposv
+- cposvx
+- cpotf2
+- cpotrf
+- cpotri
+- cpotrs
+- cppcon
+- cppequ
+- cpprfs
+- cppsv
+- cppsvx
+- cpptrf
+- cpptri
+- cpptrs
+- cpstf2
+- cpstrf
+- cptcon
+- cpteqr
+- cptrfs
+- cptsv
+- cptsvx
+- cpttrf
+- cpttrs
+- cptts2
+- crot
+- cspcon
+- cspmv
+- cspr
+- csprfs
+- cspsv
+- cspsvx
+- csptrf
+- csptri
+- csptrs
+- csrscl
+- cstedc
+- cstegr
+- cstein
+- cstemr
+- csteqr
+- csycon
+- csyconv
+- csyequb
+- csymv
+- csyr
+- csyrfs
+- csysv
+- csysvx
+- csyswapr
+- csytf2
+- csytrf
+- csytri
+- csytri2
+- csytri2x
+- csytrs
+- csytrs2
+- ctbcon
+- ctbrfs
+- ctbtrs
+- ctfsm
+- ctftri
+- ctfttp
+- ctfttr
+- ctgevc
+- ctgex2
+- ctgexc
+- ctgsen
+- ctgsja
+- ctgsna
+- ctgsy2
+- ctgsyl
+- ctpcon
+- ctpmqrt
+- ctpqrt
+- ctpqrt2
+- ctprfb
+- ctprfs
+- ctptri
+- ctptrs
+- ctpttf
+- ctpttr
+- ctrcon
+- ctrevc
+- ctrexc
+- ctrrfs
+- ctrsen
+- ctrsna
+- ctrsyl
+- ctrti2
+- ctrtri
+- ctrtrs
+- ctrttf
+- ctrttp
+- ctzrzf
+- cunbdb
+- cuncsd
+- cung2l
+- cung2r
+- cungbr
+- cunghr
+- cungl2
+- cunglq
+- cungql
+- cungqr
+- cungr2
+- cungrq
+- cungtr
+- cunm2l
+- cunm2r
+- cunmbr
+- cunmhr
+- cunml2
+- cunmlq
+- cunmql
+- cunmqr
+- cunmr2
+- cunmr3
+- cunmrq
+- cunmrz
+- cunmtr
+- cupgtr
+- cupmtr
+- dbbcsd
+- dbdsdc
+- dbdsqr
+- ddisna
+- dgbbrd
+- dgbcon
+- dgbequ
+- dgbequb
+- dgbrfs
+- dgbsv
+- dgbsvx
+- dgbtf2
+- dgbtrf
+- dgbtrs
+- dgebak
+- dgebal
+- dgebd2
+- dgebrd
+- dgecon
+- dgeequ
+- dgeequb
+- dgees
+- dgeesx
+- dgeev
+- dgeevx
+- dgehd2
+- dgehrd
+- dgejsv
+- dgelq2
+- dgelqf
+- dgels
+- dgelsd
+- dgelss
+- dgelsy
+- dgemqrt
+- dgeql2
+- dgeqlf
+- dgeqp3
+- dgeqr2
+- dgeqr2p
+- dgeqrf
+- dgeqrfp
+- dgeqrt
+- dgeqrt2
+- dgeqrt3
+- dgerfs
+- dgerq2
+- dgerqf
+- dgesc2
+- dgesdd
+- dgesv
+- dgesvd
+- dgesvj
+- dgesvx
+- dgetc2
+- dgetf2
+- dgetrf
+- dgetri
+- dgetrs
+- dggbak
+- dggbal
+- dgges
+- dggesx
+- dggev
+- dggevx
+- dggglm
+- dgghrd
+- dgglse
+- dggqrf
+- dggrqf
+- dgsvj0
+- dgsvj1
+- dgtcon
+- dgtrfs
+- dgtsv
+- dgtsvx
+- dgttrf
+- dgttrs
+- dgtts2
+- dhgeqz
+- dhsein
+- dhseqr
+- disnan
+- dlabad
+- dlabrd
+- dlacn2
+- dlacon
+- dlacpy
+- dladiv
+- dlae2
+- dlaebz
+- dlaed0
+- dlaed1
+- dlaed2
+- dlaed3
+- dlaed4
+- dlaed5
+- dlaed6
+- dlaed7
+- dlaed8
+- dlaed9
+- dlaeda
+- dlaein
+- dlaev2
+- dlaexc
+- dlag2
+- dlag2s
+- dlags2
+- dlagtf
+- dlagtm
+- dlagts
+- dlagv2
+- dlahqr
+- dlahr2
+- dlaic1
+- dlaln2
+- dlals0
+- dlalsa
+- dlalsd
+- dlamch
+- dlamrg
+- dlaneg
+- dlangb
+- dlange
+- dlangt
+- dlanhs
+- dlansb
+- dlansf
+- dlansp
+- dlanst
+- dlansy
+- dlantb
+- dlantp
+- dlantr
+- dlanv2
+- dlapll
+- dlapmr
+- dlapmt
+- dlapy2
+- dlapy3
+- dlaqgb
+- dlaqge
+- dlaqp2
+- dlaqps
+- dlaqr0
+- dlaqr1
+- dlaqr2
+- dlaqr3
+- dlaqr4
+- dlaqr5
+- dlaqsb
+- dlaqsp
+- dlaqsy
+- dlaqtr
+- dlar1v
+- dlar2v
+- dlarf
+- dlarfb
+- dlarfg
+- dlarfgp
+- dlarft
+- dlarfx
+- dlargv
+- dlarnv
+- dlarra
+- dlarrb
+- dlarrc
+- dlarrd
+- dlarre
+- dlarrf
+- dlarrj
+- dlarrk
+- dlarrr
+- dlarrv
+- dlartg
+- dlartgp
+- dlartgs
+- dlartv
+- dlaruv
+- dlarz
+- dlarzb
+- dlarzt
+- dlas2
+- dlascl
+- dlasd0
+- dlasd1
+- dlasd2
+- dlasd3
+- dlasd4
+- dlasd5
+- dlasd6
+- dlasd7
+- dlasd8
+- dlasda
+- dlasdq
+- dlasdt
+- dlaset
+- dlasq1
+- dlasq2
+- dlasq3
+- dlasq4
+- dlasq6
+- dlasr
+- dlasrt
+- dlassq
+- dlasv2
+- dlaswp
+- dlasy2
+- dlasyf
+- dlat2s
+- dlatbs
+- dlatdf
+- dlatps
+- dlatrd
+- dlatrs
+- dlatrz
+- dlauu2
+- dlauum
+- dopgtr
+- dopmtr
+- dorbdb
+- dorcsd
+- dorg2l
+- dorg2r
+- dorgbr
+- dorghr
+- dorgl2
+- dorglq
+- dorgql
+- dorgqr
+- dorgr2
+- dorgrq
+- dorgtr
+- dorm2l
+- dorm2r
+- dormbr
+- dormhr
+- dorml2
+- dormlq
+- dormql
+- dormqr
+- dormr2
+- dormr3
+- dormrq
+- dormrz
+- dormtr
+- dpbcon
+- dpbequ
+- dpbrfs
+- dpbstf
+- dpbsv
+- dpbsvx
+- dpbtf2
+- dpbtrf
+- dpbtrs
+- dpftrf
+- dpftri
+- dpftrs
+- dpocon
+- dpoequ
+- dpoequb
+- dporfs
+- dposv
+- dposvx
+- dpotf2
+- dpotrf
+- dpotri
+- dpotrs
+- dppcon
+- dppequ
+- dpprfs
+- dppsv
+- dppsvx
+- dpptrf
+- dpptri
+- dpptrs
+- dpstf2
+- dpstrf
+- dptcon
+- dpteqr
+- dptrfs
+- dptsv
+- dptsvx
+- dpttrf
+- dpttrs
+- dptts2
+- drscl
+- dsbev
+- dsbevd
+- dsbevx
+- dsbgst
+- dsbgv
+- dsbgvd
+- dsbgvx
+- dsbtrd
+- dsfrk
+- dsgesv
+- dspcon
+- dspev
+- dspevd
+- dspevx
+- dspgst
+- dspgv
+- dspgvd
+- dspgvx
+- dsposv
+- dsprfs
+- dspsv
+- dspsvx
+- dsptrd
+- dsptrf
+- dsptri
+- dsptrs
+- dstebz
+- dstedc
+- dstegr
+- dstein
+- dstemr
+- dsteqr
+- dsterf
+- dstev
+- dstevd
+- dstevr
+- dstevx
+- dsycon
+- dsyconv
+- dsyequb
+- dsyev
+- dsyevd
+- dsyevr
+- dsyevx
+- dsygs2
+- dsygst
+- dsygv
+- dsygvd
+- dsygvx
+- dsyrfs
+- dsysv
+- dsysvx
+- dsyswapr
+- dsytd2
+- dsytf2
+- dsytrd
+- dsytrf
+- dsytri
+- dsytri2
+- dsytri2x
+- dsytrs
+- dsytrs2
+- dtbcon
+- dtbrfs
+- dtbtrs
+- dtfsm
+- dtftri
+- dtfttp
+- dtfttr
+- dtgevc
+- dtgex2
+- dtgexc
+- dtgsen
+- dtgsja
+- dtgsna
+- dtgsy2
+- dtgsyl
+- dtpcon
+- dtpmqrt
+- dtpqrt
+- dtpqrt2
+- dtprfb
+- dtprfs
+- dtptri
+- dtptrs
+- dtpttf
+- dtpttr
+- dtrcon
+- dtrevc
+- dtrexc
+- dtrrfs
+- dtrsen
+- dtrsna
+- dtrsyl
+- dtrti2
+- dtrtri
+- dtrtrs
+- dtrttf
+- dtrttp
+- dtzrzf
+- dzsum1
+- icmax1
+- ieeeck
+- ilaclc
+- ilaclr
+- iladiag
+- iladlc
+- iladlr
+- ilaprec
+- ilaslc
+- ilaslr
+- ilatrans
+- ilauplo
+- ilaver
+- ilazlc
+- ilazlr
+- izmax1
+- sbbcsd
+- sbdsdc
+- sbdsqr
+- scsum1
+- sdisna
+- sgbbrd
+- sgbcon
+- sgbequ
+- sgbequb
+- sgbrfs
+- sgbsv
+- sgbsvx
+- sgbtf2
+- sgbtrf
+- sgbtrs
+- sgebak
+- sgebal
+- sgebd2
+- sgebrd
+- sgecon
+- sgeequ
+- sgeequb
+- sgees
+- sgeesx
+- sgeev
+- sgeevx
+- sgehd2
+- sgehrd
+- sgejsv
+- sgelq2
+- sgelqf
+- sgels
+- sgelsd
+- sgelss
+- sgelsy
+- sgemqrt
+- sgeql2
+- sgeqlf
+- sgeqp3
+- sgeqr2
+- sgeqr2p
+- sgeqrf
+- sgeqrfp
+- sgeqrt
+- sgeqrt2
+- sgeqrt3
+- sgerfs
+- sgerq2
+- sgerqf
+- sgesc2
+- sgesdd
+- sgesv
+- sgesvd
+- sgesvj
+- sgesvx
+- sgetc2
+- sgetf2
+- sgetrf
+- sgetri
+- sgetrs
+- sggbak
+- sggbal
+- sgges
+- sggesx
+- sggev
+- sggevx
+- sggglm
+- sgghrd
+- sgglse
+- sggqrf
+- sggrqf
+- sgsvj0
+- sgsvj1
+- sgtcon
+- sgtrfs
+- sgtsv
+- sgtsvx
+- sgttrf
+- sgttrs
+- sgtts2
+- shgeqz
+- shsein
+- shseqr
+- slabad
+- slabrd
+- slacn2
+- slacon
+- slacpy
+- sladiv
+- slae2
+- slaebz
+- slaed0
+- slaed1
+- slaed2
+- slaed3
+- slaed4
+- slaed5
+- slaed6
+- slaed7
+- slaed8
+- slaed9
+- slaeda
+- slaein
+- slaev2
+- slaexc
+- slag2
+- slag2d
+- slags2
+- slagtf
+- slagtm
+- slagts
+- slagv2
+- slahqr
+- slahr2
+- slaic1
+- slaln2
+- slals0
+- slalsa
+- slalsd
+- slamch
+- slamrg
+- slangb
+- slange
+- slangt
+- slanhs
+- slansb
+- slansf
+- slansp
+- slanst
+- slansy
+- slantb
+- slantp
+- slantr
+- slanv2
+- slapll
+- slapmr
+- slapmt
+- slapy2
+- slapy3
+- slaqgb
+- slaqge
+- slaqp2
+- slaqps
+- slaqr0
+- slaqr1
+- slaqr2
+- slaqr3
+- slaqr4
+- slaqr5
+- slaqsb
+- slaqsp
+- slaqsy
+- slaqtr
+- slar1v
+- slar2v
+- slarf
+- slarfb
+- slarfg
+- slarfgp
+- slarft
+- slarfx
+- slargv
+- slarnv
+- slarra
+- slarrb
+- slarrc
+- slarrd
+- slarre
+- slarrf
+- slarrj
+- slarrk
+- slarrr
+- slarrv
+- slartg
+- slartgp
+- slartgs
+- slartv
+- slaruv
+- slarz
+- slarzb
+- slarzt
+- slas2
+- slascl
+- slasd0
+- slasd1
+- slasd2
+- slasd3
+- slasd4
+- slasd5
+- slasd6
+- slasd7
+- slasd8
+- slasda
+- slasdq
+- slasdt
+- slaset
+- slasq1
+- slasq2
+- slasq3
+- slasq4
+- slasq6
+- slasr
+- slasrt
+- slassq
+- slasv2
+- slaswp
+- slasy2
+- slasyf
+- slatbs
+- slatdf
+- slatps
+- slatrd
+- slatrs
+- slatrz
+- slauu2
+- slauum
+- sopgtr
+- sopmtr
+- sorbdb
+- sorcsd
+- sorg2l
+- sorg2r
+- sorgbr
+- sorghr
+- sorgl2
+- sorglq
+- sorgql
+- sorgqr
+- sorgr2
+- sorgrq
+- sorgtr
+- sorm2l
+- sorm2r
+- sormbr
+- sormhr
+- sorml2
+- sormlq
+- sormql
+- sormqr
+- sormr2
+- sormr3
+- sormrq
+- sormrz
+- sormtr
+- spbcon
+- spbequ
+- spbrfs
+- spbstf
+- spbsv
+- spbsvx
+- spbtf2
+- spbtrf
+- spbtrs
+- spftrf
+- spftri
+- spftrs
+- spocon
+- spoequ
+- spoequb
+- sporfs
+- sposv
+- sposvx
+- spotf2
+- spotrf
+- spotri
+- spotrs
+- sppcon
+- sppequ
+- spprfs
+- sppsv
+- sppsvx
+- spptrf
+- spptri
+- spptrs
+- spstf2
+- spstrf
+- sptcon
+- spteqr
+- sptrfs
+- sptsv
+- sptsvx
+- spttrf
+- spttrs
+- sptts2
+- srscl
+- ssbev
+- ssbevd
+- ssbevx
+- ssbgst
+- ssbgv
+- ssbgvd
+- ssbgvx
+- ssbtrd
+- ssfrk
+- sspcon
+- sspev
+- sspevd
+- sspevx
+- sspgst
+- sspgv
+- sspgvd
+- sspgvx
+- ssprfs
+- sspsv
+- sspsvx
+- ssptrd
+- ssptrf
+- ssptri
+- ssptrs
+- sstebz
+- sstedc
+- sstegr
+- sstein
+- sstemr
+- ssteqr
+- ssterf
+- sstev
+- sstevd
+- sstevr
+- sstevx
+- ssycon
+- ssyconv
+- ssyequb
+- ssyev
+- ssyevd
+- ssyevr
+- ssyevx
+- ssygs2
+- ssygst
+- ssygv
+- ssygvd
+- ssygvx
+- ssyrfs
+- ssysv
+- ssysvx
+- ssyswapr
+- ssytd2
+- ssytf2
+- ssytrd
+- ssytrf
+- ssytri
+- ssytri2
+- ssytri2x
+- ssytrs
+- ssytrs2
+- stbcon
+- stbrfs
+- stbtrs
+- stfsm
+- stftri
+- stfttp
+- stfttr
+- stgevc
+- stgex2
+- stgexc
+- stgsen
+- stgsja
+- stgsna
+- stgsy2
+- stgsyl
+- stpcon
+- stpmqrt
+- stpqrt
+- stpqrt2
+- stprfb
+- stprfs
+- stptri
+- stptrs
+- stpttf
+- stpttr
+- strcon
+- strevc
+- strexc
+- strrfs
+- strsen
+- strsna
+- strsyl
+- strti2
+- strtri
+- strtrs
+- strttf
+- strttp
+- stzrzf
+- xerbla_array
+- zbbcsd
+- zbdsqr
+- zcgesv
+- zcposv
+- zdrscl
+- zgbbrd
+- zgbcon
+- zgbequ
+- zgbequb
+- zgbrfs
+- zgbsv
+- zgbsvx
+- zgbtf2
+- zgbtrf
+- zgbtrs
+- zgebak
+- zgebal
+- zgebd2
+- zgebrd
+- zgecon
+- zgeequ
+- zgeequb
+- zgees
+- zgeesx
+- zgeev
+- zgeevx
+- zgehd2
+- zgehrd
+- zgelq2
+- zgelqf
+- zgels
+- zgelsd
+- zgelss
+- zgelsy
+- zgemqrt
+- zgeql2
+- zgeqlf
+- zgeqp3
+- zgeqr2
+- zgeqr2p
+- zgeqrf
+- zgeqrfp
+- zgeqrt
+- zgeqrt2
+- zgeqrt3
+- zgerfs
+- zgerq2
+- zgerqf
+- zgesc2
+- zgesdd
+- zgesv
+- zgesvd
+- zgesvx
+- zgetc2
+- zgetf2
+- zgetrf
+- zgetri
+- zgetrs
+- zggbak
+- zggbal
+- zgges
+- zggesx
+- zggev
+- zggevx
+- zggglm
+- zgghrd
+- zgglse
+- zggqrf
+- zggrqf
+- zgtcon
+- zgtrfs
+- zgtsv
+- zgtsvx
+- zgttrf
+- zgttrs
+- zgtts2
+- zhbev
+- zhbevd
+- zhbevx
+- zhbgst
+- zhbgv
+- zhbgvd
+- zhbgvx
+- zhbtrd
+- zhecon
+- zheequb
+- zheev
+- zheevd
+- zheevr
+- zheevx
+- zhegs2
+- zhegst
+- zhegv
+- zhegvd
+- zhegvx
+- zherfs
+- zhesv
+- zhesvx
+- zheswapr
+- zhetd2
+- zhetf2
+- zhetrd
+- zhetrf
+- zhetri
+- zhetri2
+- zhetri2x
+- zhetrs
+- zhetrs2
+- zhfrk
+- zhgeqz
+- zhpcon
+- zhpev
+- zhpevd
+- zhpevx
+- zhpgst
+- zhpgv
+- zhpgvd
+- zhpgvx
+- zhprfs
+- zhpsv
+- zhpsvx
+- zhptrd
+- zhptrf
+- zhptri
+- zhptrs
+- zhsein
+- zhseqr
+- zlabrd
+- zlacgv
+- zlacn2
+- zlacon
+- zlacp2
+- zlacpy
+- zlacrm
+- zlacrt
+- zladiv
+- zlaed0
+- zlaed7
+- zlaed8
+- zlaein
+- zlaesy
+- zlaev2
+- zlag2c
+- zlags2
+- zlagtm
+- zlahef
+- zlahqr
+- zlahr2
+- zlaic1
+- zlals0
+- zlalsa
+- zlalsd
+- zlangb
+- zlange
+- zlangt
+- zlanhb
+- zlanhe
+- zlanhf
+- zlanhp
+- zlanhs
+- zlanht
+- zlansb
+- zlansp
+- zlansy
+- zlantb
+- zlantp
+- zlantr
+- zlapll
+- zlapmr
+- zlapmt
+- zlaqgb
+- zlaqge
+- zlaqhb
+- zlaqhe
+- zlaqhp
+- zlaqp2
+- zlaqps
+- zlaqr0
+- zlaqr1
+- zlaqr2
+- zlaqr3
+- zlaqr4
+- zlaqr5
+- zlaqsb
+- zlaqsp
+- zlaqsy
+- zlar1v
+- zlar2v
+- zlarcm
+- zlarf
+- zlarfb
+- zlarfg
+- zlarfgp
+- zlarft
+- zlarfx
+- zlargv
+- zlarnv
+- zlarrv
+- zlartg
+- zlartv
+- zlarz
+- zlarzb
+- zlarzt
+- zlascl
+- zlaset
+- zlasr
+- zlassq
+- zlaswp
+- zlasyf
+- zlat2c
+- zlatbs
+- zlatdf
+- zlatps
+- zlatrd
+- zlatrs
+- zlatrz
+- zlauu2
+- zlauum
+- zpbcon
+- zpbequ
+- zpbrfs
+- zpbstf
+- zpbsv
+- zpbsvx
+- zpbtf2
+- zpbtrf
+- zpbtrs
+- zpftrf
+- zpftri
+- zpftrs
+- zpocon
+- zpoequ
+- zpoequb
+- zporfs
+- zposv
+- zposvx
+- zpotf2
+- zpotrf
+- zpotri
+- zpotrs
+- zppcon
+- zppequ
+- zpprfs
+- zppsv
+- zppsvx
+- zpptrf
+- zpptri
+- zpptrs
+- zpstf2
+- zpstrf
+- zptcon
+- zpteqr
+- zptrfs
+- zptsv
+- zptsvx
+- zpttrf
+- zpttrs
+- zptts2
+- zrot
+- zspcon
+- zspmv
+- zspr
+- zsprfs
+- zspsv
+- zspsvx
+- zsptrf
+- zsptri
+- zsptrs
+- zstedc
+- zstegr
+- zstein
+- zstemr
+- zsteqr
+- zsycon
+- zsyconv
+- zsyequb
+- zsymv
+- zsyr
+- zsyrfs
+- zsysv
+- zsysvx
+- zsyswapr
+- zsytf2
+- zsytrf
+- zsytri
+- zsytri2
+- zsytri2x
+- zsytrs
+- zsytrs2
+- ztbcon
+- ztbrfs
+- ztbtrs
+- ztfsm
+- ztftri
+- ztfttp
+- ztfttr
+- ztgevc
+- ztgex2
+- ztgexc
+- ztgsen
+- ztgsja
+- ztgsna
+- ztgsy2
+- ztgsyl
+- ztpcon
+- ztpmqrt
+- ztpqrt
+- ztpqrt2
+- ztprfb
+- ztprfs
+- ztptri
+- ztptrs
+- ztpttf
+- ztpttr
+- ztrcon
+- ztrevc
+- ztrexc
+- ztrrfs
+- ztrsen
+- ztrsna
+- ztrsyl
+- ztrti2
+- ztrtri
+- ztrtrs
+- ztrttf
+- ztrttp
+- ztzrzf
+- zunbdb
+- zuncsd
+- zung2l
+- zung2r
+- zungbr
+- zunghr
+- zungl2
+- zunglq
+- zungql
+- zungqr
+- zungr2
+- zungrq
+- zungtr
+- zunm2l
+- zunm2r
+- zunmbr
+- zunmhr
+- zunml2
+- zunmlq
+- zunmql
+- zunmqr
+- zunmr2
+- zunmr3
+- zunmrq
+- zunmrz
+- zunmtr
+- zupgtr
+- zupmtr
+
+
+"""
+
+# 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.
+
+cdef extern from "fortran_defs.h":
+    pass
+
+from numpy cimport npy_complex64, npy_complex128
+
+cdef extern from "_lapack_subroutines.h":
+    # Function pointer type declarations for
+    # gees and gges families of functions.
+    ctypedef bint _cselect1(npy_complex64*)
+    ctypedef bint _cselect2(npy_complex64*, npy_complex64*)
+    ctypedef bint _dselect2(d*, d*)
+    ctypedef bint _dselect3(d*, d*, d*)
+    ctypedef bint _sselect2(s*, s*)
+    ctypedef bint _sselect3(s*, s*, s*)
+    ctypedef bint _zselect1(npy_complex128*)
+    ctypedef bint _zselect2(npy_complex128*, npy_complex128*)
+
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cbbcsd "BLAS_FUNC(cbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *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) nogil
+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:
+    
+    _fortran_cbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, rwork, lrwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cbdsqr "BLAS_FUNC(cbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, npy_complex64 *vt, int *ldvt, npy_complex64 *u, int *ldu, npy_complex64 *c, int *ldc, s *rwork, int *info) 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:
+    
+    _fortran_cbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbbrd "BLAS_FUNC(cgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *pt, int *ldpt, npy_complex64 *c, int *ldc, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbcon "BLAS_FUNC(cgbcon)"(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbequ "BLAS_FUNC(cgbequ)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) 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:
+    
+    _fortran_cgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbequb "BLAS_FUNC(cgbequb)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) 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:
+    
+    _fortran_cgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbrfs "BLAS_FUNC(cgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbsv "BLAS_FUNC(cgbsv)"(int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info) 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:
+    
+    _fortran_cgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbsvx "BLAS_FUNC(cgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtf2 "BLAS_FUNC(cgbtf2)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void cgbtf2(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtrf "BLAS_FUNC(cgbtrf)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void cgbtrf(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtrs "BLAS_FUNC(cgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info) 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:
+    
+    _fortran_cgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebak "BLAS_FUNC(cgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, npy_complex64 *v, int *ldv, int *info) 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:
+    
+    _fortran_cgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebal "BLAS_FUNC(cgebal)"(char *job, int *n, npy_complex64 *a, int *lda, int *ilo, int *ihi, s *scale, int *info) nogil
+cdef void cgebal(char *job, int *n, c *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil:
+    
+    _fortran_cgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebd2 "BLAS_FUNC(cgebd2)"(int *m, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebrd "BLAS_FUNC(cgebrd)"(int *m, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgecon "BLAS_FUNC(cgecon)"(char *norm, int *n, npy_complex64 *a, int *lda, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgecon(char *norm, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgecon(norm, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeequ "BLAS_FUNC(cgeequ)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) 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:
+    
+    _fortran_cgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeequb "BLAS_FUNC(cgeequb)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) 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:
+    
+    _fortran_cgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgees "BLAS_FUNC(cgees)"(char *jobvs, char *sort, _cselect1 *select, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) 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:
+    
+    _fortran_cgees(jobvs, sort, <_cselect1*>select, n, a, lda, sdim, w, vs, ldvs, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeesx "BLAS_FUNC(cgeesx)"(char *jobvs, char *sort, _cselect1 *select, char *sense, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) 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:
+    
+    _fortran_cgeesx(jobvs, sort, <_cselect1*>select, sense, n, a, lda, sdim, w, vs, ldvs, rconde, rcondv, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeev "BLAS_FUNC(cgeev)"(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_cgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeevx "BLAS_FUNC(cgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_cgeevx(balanc, jobvl, jobvr, sense, n, a, lda, w, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgehd2 "BLAS_FUNC(cgehd2)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgehd2(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgehrd "BLAS_FUNC(cgehrd)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgehrd(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelq2 "BLAS_FUNC(cgelq2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgelq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelqf "BLAS_FUNC(cgelqf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgelqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgels "BLAS_FUNC(cgels)"(char *trans, int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelsd "BLAS_FUNC(cgelsd)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *s, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *info) 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:
+    
+    _fortran_cgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelss "BLAS_FUNC(cgelss)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *s, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_cgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelsy "BLAS_FUNC(cgelsy)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *jpvt, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_cgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgemqrt "BLAS_FUNC(cgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeql2 "BLAS_FUNC(cgeql2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeql2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqlf "BLAS_FUNC(cgeqlf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqlf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqp3 "BLAS_FUNC(cgeqp3)"(int *m, int *n, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_cgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqr2 "BLAS_FUNC(cgeqr2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeqr2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqr2p "BLAS_FUNC(cgeqr2p)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeqr2p(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrf "BLAS_FUNC(cgeqrf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqrf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrfp "BLAS_FUNC(cgeqrfp)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqrfp(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt "BLAS_FUNC(cgeqrt)"(int *m, int *n, int *nb, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info) nogil
+cdef void cgeqrt(int *m, int *n, int *nb, c *a, int *lda, c *t, int *ldt, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt2 "BLAS_FUNC(cgeqrt2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info) nogil
+cdef void cgeqrt2(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt3 "BLAS_FUNC(cgeqrt3)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info) nogil
+cdef void cgeqrt3(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerfs "BLAS_FUNC(cgerfs)"(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerq2 "BLAS_FUNC(cgerq2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgerq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerqf "BLAS_FUNC(cgerqf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgerqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesc2 "BLAS_FUNC(cgesc2)"(int *n, npy_complex64 *a, int *lda, npy_complex64 *rhs, int *ipiv, int *jpiv, s *scale) nogil
+cdef void cgesc2(int *n, c *a, int *lda, c *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil:
+    
+    _fortran_cgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesdd "BLAS_FUNC(cgesdd)"(char *jobz, int *m, int *n, npy_complex64 *a, int *lda, s *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *info) 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:
+    
+    _fortran_cgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesv "BLAS_FUNC(cgesv)"(int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgesv(int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesvd "BLAS_FUNC(cgesvd)"(char *jobu, char *jobvt, int *m, int *n, npy_complex64 *a, int *lda, s *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_cgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesvx "BLAS_FUNC(cgesvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetc2 "BLAS_FUNC(cgetc2)"(int *n, npy_complex64 *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void cgetc2(int *n, c *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_cgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetf2 "BLAS_FUNC(cgetf2)"(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void cgetf2(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetrf "BLAS_FUNC(cgetrf)"(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void cgetrf(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetri "BLAS_FUNC(cgetri)"(int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgetri(int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetrs "BLAS_FUNC(cgetrs)"(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgetrs(char *trans, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggbak "BLAS_FUNC(cggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, npy_complex64 *v, int *ldv, int *info) 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:
+    
+    _fortran_cggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggbal "BLAS_FUNC(cggbal)"(char *job, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) 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:
+    
+    _fortran_cggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgges "BLAS_FUNC(cgges)"(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) 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:
+    
+    _fortran_cgges(jobvsl, jobvsr, sort, <_cselect2*>selctg, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggesx "BLAS_FUNC(cggesx)"(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) 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:
+    
+    _fortran_cggesx(jobvsl, jobvsr, sort, <_cselect2*>selctg, sense, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggev "BLAS_FUNC(cggev)"(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_cggev(jobvl, jobvr, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggevx "BLAS_FUNC(cggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) 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:
+    
+    _fortran_cggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, rwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggglm "BLAS_FUNC(cggglm)"(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *d, npy_complex64 *x, npy_complex64 *y, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgghrd "BLAS_FUNC(cgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *info) 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:
+    
+    _fortran_cgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgglse "BLAS_FUNC(cgglse)"(int *m, int *n, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, npy_complex64 *d, npy_complex64 *x, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggqrf "BLAS_FUNC(cggqrf)"(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggrqf "BLAS_FUNC(cggrqf)"(int *m, int *p, int *n, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtcon "BLAS_FUNC(cgtcon)"(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtrfs "BLAS_FUNC(cgtrfs)"(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtsv "BLAS_FUNC(cgtsv)"(int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgtsv(int *n, int *nrhs, c *dl, c *d, c *du, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtsvx "BLAS_FUNC(cgtsvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgttrf "BLAS_FUNC(cgttrf)"(int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, int *info) nogil
+cdef void cgttrf(int *n, c *dl, c *d, c *du, c *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgttrs "BLAS_FUNC(cgttrs)"(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, int *info) 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:
+    
+    _fortran_cgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtts2 "BLAS_FUNC(cgtts2)"(int *itrans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb) 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:
+    
+    _fortran_cgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbev "BLAS_FUNC(chbev)"(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_chbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbevd "BLAS_FUNC(chbevd)"(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_chbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbevx "BLAS_FUNC(chbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_chbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgst "BLAS_FUNC(chbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *x, int *ldx, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_chbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgv "BLAS_FUNC(chbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_chbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgvd "BLAS_FUNC(chbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_chbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgvx "BLAS_FUNC(chbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_chbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbtrd "BLAS_FUNC(chbtrd)"(char *vect, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info) 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:
+    
+    _fortran_chbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_checon "BLAS_FUNC(checon)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void checon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_checon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheequb "BLAS_FUNC(cheequb)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, npy_complex64 *work, int *info) nogil
+cdef void cheequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil:
+    
+    _fortran_cheequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheev "BLAS_FUNC(cheev)"(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, s *w, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_cheev(jobz, uplo, n, a, lda, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevd "BLAS_FUNC(cheevd)"(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, s *w, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_cheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevr "BLAS_FUNC(cheevr)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, int *isuppz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_cheevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevx "BLAS_FUNC(cheevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_cheevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegs2 "BLAS_FUNC(chegs2)"(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chegs2(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chegs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegst "BLAS_FUNC(chegst)"(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chegst(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chegst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegv "BLAS_FUNC(chegv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *w, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_chegv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegvd "BLAS_FUNC(chegvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *w, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_chegvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegvx "BLAS_FUNC(chegvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_chegvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cherfs "BLAS_FUNC(cherfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chesv "BLAS_FUNC(chesv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_chesv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chesvx "BLAS_FUNC(chesvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_chesvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheswapr "BLAS_FUNC(cheswapr)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2) nogil
+cdef void cheswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_cheswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetd2 "BLAS_FUNC(chetd2)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tau, int *info) nogil
+cdef void chetd2(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, int *info) noexcept nogil:
+    
+    _fortran_chetd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetf2 "BLAS_FUNC(chetf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void chetf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_chetf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrd "BLAS_FUNC(chetrd)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_chetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrf "BLAS_FUNC(chetrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chetrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chetrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri "BLAS_FUNC(chetri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void chetri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_chetri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri2 "BLAS_FUNC(chetri2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chetri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chetri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri2x "BLAS_FUNC(chetri2x)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info) nogil
+cdef void chetri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_chetri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrs "BLAS_FUNC(chetrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chetrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrs2 "BLAS_FUNC(chetrs2)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) 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:
+    
+    _fortran_chetrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chfrk "BLAS_FUNC(chfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c) 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:
+    
+    _fortran_chfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chgeqz "BLAS_FUNC(chgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *t, int *ldt, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_chgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alpha, beta, q, ldq, z, ldz, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    char _fortran_chla_transtype "BLAS_FUNC(chla_transtype)"(int *trans) nogil
+cdef char chla_transtype(int *trans) noexcept nogil:
+    
+    return _fortran_chla_transtype(trans)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpcon "BLAS_FUNC(chpcon)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void chpcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_chpcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpev "BLAS_FUNC(chpev)"(char *jobz, char *uplo, int *n, npy_complex64 *ap, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_chpev(jobz, uplo, n, ap, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpevd "BLAS_FUNC(chpevd)"(char *jobz, char *uplo, int *n, npy_complex64 *ap, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_chpevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpevx "BLAS_FUNC(chpevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_chpevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgst "BLAS_FUNC(chpgst)"(int *itype, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, int *info) nogil
+cdef void chpgst(int *itype, char *uplo, int *n, c *ap, c *bp, int *info) noexcept nogil:
+    
+    _fortran_chpgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgv "BLAS_FUNC(chpgv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_chpgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgvd "BLAS_FUNC(chpgvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_chpgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgvx "BLAS_FUNC(chpgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_chpgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chprfs "BLAS_FUNC(chprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_chprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpsv "BLAS_FUNC(chpsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chpsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chpsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpsvx "BLAS_FUNC(chpsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_chpsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrd "BLAS_FUNC(chptrd)"(char *uplo, int *n, npy_complex64 *ap, s *d, s *e, npy_complex64 *tau, int *info) nogil
+cdef void chptrd(char *uplo, int *n, c *ap, s *d, s *e, c *tau, int *info) noexcept nogil:
+    
+    _fortran_chptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrf "BLAS_FUNC(chptrf)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info) nogil
+cdef void chptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_chptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptri "BLAS_FUNC(chptri)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void chptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_chptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrs "BLAS_FUNC(chptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chsein "BLAS_FUNC(chsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *ifaill, int *ifailr, int *info) 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:
+    
+    _fortran_chsein(side, eigsrc, initv, select, n, h, ldh, w, vl, ldvl, vr, ldvr, mm, m, work, rwork, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chseqr "BLAS_FUNC(chseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_chseqr(job, compz, n, ilo, ihi, h, ldh, w, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clabrd "BLAS_FUNC(clabrd)"(int *m, int *n, int *nb, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *x, int *ldx, npy_complex64 *y, int *ldy) 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:
+    
+    _fortran_clabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacgv "BLAS_FUNC(clacgv)"(int *n, npy_complex64 *x, int *incx) nogil
+cdef void clacgv(int *n, c *x, int *incx) noexcept nogil:
+    
+    _fortran_clacgv(n, x, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacn2 "BLAS_FUNC(clacn2)"(int *n, npy_complex64 *v, npy_complex64 *x, s *est, int *kase, int *isave) nogil
+cdef void clacn2(int *n, c *v, c *x, s *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_clacn2(n, v, x, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacon "BLAS_FUNC(clacon)"(int *n, npy_complex64 *v, npy_complex64 *x, s *est, int *kase) nogil
+cdef void clacon(int *n, c *v, c *x, s *est, int *kase) noexcept nogil:
+    
+    _fortran_clacon(n, v, x, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacp2 "BLAS_FUNC(clacp2)"(char *uplo, int *m, int *n, s *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void clacp2(char *uplo, int *m, int *n, s *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_clacp2(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacpy "BLAS_FUNC(clacpy)"(char *uplo, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void clacpy(char *uplo, int *m, int *n, c *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_clacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacrm "BLAS_FUNC(clacrm)"(int *m, int *n, npy_complex64 *a, int *lda, s *b, int *ldb, npy_complex64 *c, int *ldc, s *rwork) nogil
+cdef void clacrm(int *m, int *n, c *a, int *lda, s *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil:
+    
+    _fortran_clacrm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacrt "BLAS_FUNC(clacrt)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, npy_complex64 *c, npy_complex64 *s) nogil
+cdef void clacrt(int *n, c *cx, int *incx, c *cy, int *incy, c *c, c *s) noexcept nogil:
+    
+    _fortran_clacrt(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cladiv "F_FUNC(cladivwrp,CLADIVWRP)"(npy_complex64 *out, npy_complex64 *x, npy_complex64 *y) nogil
+cdef c cladiv(c *x, c *y) noexcept nogil:
+    cdef c out
+    _fortran_cladiv(&out, x, y)
+    return out
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed0 "BLAS_FUNC(claed0)"(int *qsiz, int *n, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *qstore, int *ldqs, s *rwork, int *iwork, int *info) 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:
+    
+    _fortran_claed0(qsiz, n, d, e, q, ldq, qstore, ldqs, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed7 "BLAS_FUNC(claed7)"(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, npy_complex64 *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, npy_complex64 *work, s *rwork, int *iwork, int *info) 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:
+    
+    _fortran_claed7(n, cutpnt, qsiz, tlvls, curlvl, curpbm, d, q, ldq, rho, indxq, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed8 "BLAS_FUNC(claed8)"(int *k, int *n, int *qsiz, npy_complex64 *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, npy_complex64 *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) 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:
+    
+    _fortran_claed8(k, n, qsiz, q, ldq, d, rho, cutpnt, z, dlamda, q2, ldq2, w, indxp, indx, indxq, perm, givptr, givcol, givnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claein "BLAS_FUNC(claein)"(bint *rightv, bint *noinit, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *v, npy_complex64 *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) 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:
+    
+    _fortran_claein(rightv, noinit, n, h, ldh, w, v, b, ldb, rwork, eps3, smlnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claesy "BLAS_FUNC(claesy)"(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, npy_complex64 *rt1, npy_complex64 *rt2, npy_complex64 *evscal, npy_complex64 *cs1, npy_complex64 *sn1) nogil
+cdef void claesy(c *a, c *b, c *c, c *rt1, c *rt2, c *evscal, c *cs1, c *sn1) noexcept nogil:
+    
+    _fortran_claesy(a, b, c, rt1, rt2, evscal, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claev2 "BLAS_FUNC(claev2)"(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, s *rt1, s *rt2, s *cs1, npy_complex64 *sn1) nogil
+cdef void claev2(c *a, c *b, c *c, s *rt1, s *rt2, s *cs1, c *sn1) noexcept nogil:
+    
+    _fortran_claev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clag2z "BLAS_FUNC(clag2z)"(int *m, int *n, npy_complex64 *sa, int *ldsa, npy_complex128 *a, int *lda, int *info) nogil
+cdef void clag2z(int *m, int *n, c *sa, int *ldsa, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clag2z(m, n, sa, ldsa, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clags2 "BLAS_FUNC(clags2)"(bint *upper, s *a1, npy_complex64 *a2, s *a3, s *b1, npy_complex64 *b2, s *b3, s *csu, npy_complex64 *snu, s *csv, npy_complex64 *snv, s *csq, npy_complex64 *snq) 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:
+    
+    _fortran_clags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clagtm "BLAS_FUNC(clagtm)"(char *trans, int *n, int *nrhs, s *alpha, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *x, int *ldx, s *beta, npy_complex64 *b, int *ldb) 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:
+    
+    _fortran_clagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahef "BLAS_FUNC(clahef)"(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info) 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:
+    
+    _fortran_clahef(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahqr "BLAS_FUNC(clahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *info) 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:
+    
+    _fortran_clahqr(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahr2 "BLAS_FUNC(clahr2)"(int *n, int *k, int *nb, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *t, int *ldt, npy_complex64 *y, int *ldy) 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:
+    
+    _fortran_clahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claic1 "BLAS_FUNC(claic1)"(int *job, int *j, npy_complex64 *x, s *sest, npy_complex64 *w, npy_complex64 *gamma, s *sestpr, npy_complex64 *s, npy_complex64 *c) nogil
+cdef void claic1(int *job, int *j, c *x, s *sest, c *w, c *gamma, s *sestpr, c *s, c *c) noexcept nogil:
+    
+    _fortran_claic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clals0 "BLAS_FUNC(clals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *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) 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:
+    
+    _fortran_clals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clalsa "BLAS_FUNC(clalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *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) 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:
+    
+    _fortran_clalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clalsd "BLAS_FUNC(clalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, npy_complex64 *b, int *ldb, s *rcond, int *rank, npy_complex64 *work, s *rwork, int *iwork, int *info) 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:
+    
+    _fortran_clalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clangb "BLAS_FUNC(clangb)"(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clangb(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clange "BLAS_FUNC(clange)"(char *norm, int *m, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clange(char *norm, int *m, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clangt "BLAS_FUNC(clangt)"(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du) nogil
+cdef s clangt(char *norm, int *n, c *dl, c *d, c *du) noexcept nogil:
+    
+    return _fortran_clangt(norm, n, dl, d, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhb "BLAS_FUNC(clanhb)"(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clanhb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clanhb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhe "BLAS_FUNC(clanhe)"(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clanhe(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clanhe(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhf "BLAS_FUNC(clanhf)"(char *norm, char *transr, char *uplo, int *n, npy_complex64 *a, s *work) nogil
+cdef s clanhf(char *norm, char *transr, char *uplo, int *n, c *a, s *work) noexcept nogil:
+    
+    return _fortran_clanhf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhp "BLAS_FUNC(clanhp)"(char *norm, char *uplo, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clanhp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clanhp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhs "BLAS_FUNC(clanhs)"(char *norm, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clanhs(char *norm, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanht "BLAS_FUNC(clanht)"(char *norm, int *n, s *d, npy_complex64 *e) nogil
+cdef s clanht(char *norm, int *n, s *d, c *e) noexcept nogil:
+    
+    return _fortran_clanht(norm, n, d, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansb "BLAS_FUNC(clansb)"(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clansb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansp "BLAS_FUNC(clansp)"(char *norm, char *uplo, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clansp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansy "BLAS_FUNC(clansy)"(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clansy(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantb "BLAS_FUNC(clantb)"(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clantb(char *norm, char *uplo, char *diag, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantp "BLAS_FUNC(clantp)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clantp(char *norm, char *uplo, char *diag, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantr "BLAS_FUNC(clantr)"(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clantr(char *norm, char *uplo, char *diag, int *m, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapll "BLAS_FUNC(clapll)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *ssmin) nogil
+cdef void clapll(int *n, c *x, int *incx, c *y, int *incy, s *ssmin) noexcept nogil:
+    
+    _fortran_clapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapmr "BLAS_FUNC(clapmr)"(bint *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k) nogil
+cdef void clapmr(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_clapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapmt "BLAS_FUNC(clapmt)"(bint *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k) nogil
+cdef void clapmt(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_clapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqgb "BLAS_FUNC(claqgb)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) 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:
+    
+    _fortran_claqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqge "BLAS_FUNC(claqge)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) 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:
+    
+    _fortran_claqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhb "BLAS_FUNC(claqhb)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhe "BLAS_FUNC(claqhe)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhe(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhe(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhp "BLAS_FUNC(claqhp)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqp2 "BLAS_FUNC(claqp2)"(int *m, int *n, int *offset, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, s *vn1, s *vn2, npy_complex64 *work) 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:
+    
+    _fortran_claqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqps "BLAS_FUNC(claqps)"(int *m, int *n, int *offset, int *nb, int *kb, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, s *vn1, s *vn2, npy_complex64 *auxv, npy_complex64 *f, int *ldf) 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:
+    
+    _fortran_claqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr0 "BLAS_FUNC(claqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_claqr0(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr1 "BLAS_FUNC(claqr1)"(int *n, npy_complex64 *h, int *ldh, npy_complex64 *s1, npy_complex64 *s2, npy_complex64 *v) nogil
+cdef void claqr1(int *n, c *h, int *ldh, c *s1, c *s2, c *v) noexcept nogil:
+    
+    _fortran_claqr1(n, h, ldh, s1, s2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr2 "BLAS_FUNC(claqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork) 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:
+    
+    _fortran_claqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr3 "BLAS_FUNC(claqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork) 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:
+    
+    _fortran_claqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr4 "BLAS_FUNC(claqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_claqr4(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr5 "BLAS_FUNC(claqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex64 *s, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *v, int *ldv, npy_complex64 *u, int *ldu, int *nv, npy_complex64 *wv, int *ldwv, int *nh, npy_complex64 *wh, int *ldwh) 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:
+    
+    _fortran_claqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, s, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsb "BLAS_FUNC(claqsb)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsp "BLAS_FUNC(claqsp)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsy "BLAS_FUNC(claqsy)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsy(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clar1v "BLAS_FUNC(clar1v)"(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, npy_complex64 *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) 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:
+    
+    _fortran_clar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clar2v "BLAS_FUNC(clar2v)"(int *n, npy_complex64 *x, npy_complex64 *y, npy_complex64 *z, int *incx, s *c, npy_complex64 *s, int *incc) nogil
+cdef void clar2v(int *n, c *x, c *y, c *z, int *incx, s *c, c *s, int *incc) noexcept nogil:
+    
+    _fortran_clar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarcm "BLAS_FUNC(clarcm)"(int *m, int *n, s *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, s *rwork) nogil
+cdef void clarcm(int *m, int *n, s *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil:
+    
+    _fortran_clarcm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarf "BLAS_FUNC(clarf)"(char *side, int *m, int *n, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil
+cdef void clarf(char *side, int *m, int *n, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil:
+    
+    _fortran_clarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfb "BLAS_FUNC(clarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork) 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:
+    
+    _fortran_clarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfg "BLAS_FUNC(clarfg)"(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau) nogil
+cdef void clarfg(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil:
+    
+    _fortran_clarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfgp "BLAS_FUNC(clarfgp)"(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau) nogil
+cdef void clarfgp(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil:
+    
+    _fortran_clarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarft "BLAS_FUNC(clarft)"(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt) nogil
+cdef void clarft(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil:
+    
+    _fortran_clarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfx "BLAS_FUNC(clarfx)"(char *side, int *m, int *n, npy_complex64 *v, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil
+cdef void clarfx(char *side, int *m, int *n, c *v, c *tau, c *c, int *ldc, c *work) noexcept nogil:
+    
+    _fortran_clarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clargv "BLAS_FUNC(clargv)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *c, int *incc) nogil
+cdef void clargv(int *n, c *x, int *incx, c *y, int *incy, s *c, int *incc) noexcept nogil:
+    
+    _fortran_clargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarnv "BLAS_FUNC(clarnv)"(int *idist, int *iseed, int *n, npy_complex64 *x) nogil
+cdef void clarnv(int *idist, int *iseed, int *n, c *x) noexcept nogil:
+    
+    _fortran_clarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarrv "BLAS_FUNC(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, npy_complex64 *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) 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:
+    
+    _fortran_clarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clartg "BLAS_FUNC(clartg)"(npy_complex64 *f, npy_complex64 *g, s *cs, npy_complex64 *sn, npy_complex64 *r) nogil
+cdef void clartg(c *f, c *g, s *cs, c *sn, c *r) noexcept nogil:
+    
+    _fortran_clartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clartv "BLAS_FUNC(clartv)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *c, npy_complex64 *s, int *incc) nogil
+cdef void clartv(int *n, c *x, int *incx, c *y, int *incy, s *c, c *s, int *incc) noexcept nogil:
+    
+    _fortran_clartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarz "BLAS_FUNC(clarz)"(char *side, int *m, int *n, int *l, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) 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:
+    
+    _fortran_clarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarzb "BLAS_FUNC(clarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork) 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:
+    
+    _fortran_clarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarzt "BLAS_FUNC(clarzt)"(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt) nogil
+cdef void clarzt(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil:
+    
+    _fortran_clarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clascl "BLAS_FUNC(clascl)"(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, npy_complex64 *a, int *lda, int *info) 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:
+    
+    _fortran_clascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claset "BLAS_FUNC(claset)"(char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *a, int *lda) nogil
+cdef void claset(char *uplo, int *m, int *n, c *alpha, c *beta, c *a, int *lda) noexcept nogil:
+    
+    _fortran_claset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clasr "BLAS_FUNC(clasr)"(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, npy_complex64 *a, int *lda) nogil
+cdef void clasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, c *a, int *lda) noexcept nogil:
+    
+    _fortran_clasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_classq "BLAS_FUNC(classq)"(int *n, npy_complex64 *x, int *incx, s *scale, s *sumsq) nogil
+cdef void classq(int *n, c *x, int *incx, s *scale, s *sumsq) noexcept nogil:
+    
+    _fortran_classq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claswp "BLAS_FUNC(claswp)"(int *n, npy_complex64 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void claswp(int *n, c *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_claswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clasyf "BLAS_FUNC(clasyf)"(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info) 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:
+    
+    _fortran_clasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatbs "BLAS_FUNC(clatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *x, s *scale, s *cnorm, int *info) 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:
+    
+    _fortran_clatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatdf "BLAS_FUNC(clatdf)"(int *ijob, int *n, npy_complex64 *z, int *ldz, npy_complex64 *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) nogil
+cdef void clatdf(int *ijob, int *n, c *z, int *ldz, c *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_clatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatps "BLAS_FUNC(clatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *ap, npy_complex64 *x, s *scale, s *cnorm, int *info) 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:
+    
+    _fortran_clatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrd "BLAS_FUNC(clatrd)"(char *uplo, int *n, int *nb, npy_complex64 *a, int *lda, s *e, npy_complex64 *tau, npy_complex64 *w, int *ldw) nogil
+cdef void clatrd(char *uplo, int *n, int *nb, c *a, int *lda, s *e, c *tau, c *w, int *ldw) noexcept nogil:
+    
+    _fortran_clatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrs "BLAS_FUNC(clatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, s *scale, s *cnorm, int *info) 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:
+    
+    _fortran_clatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrz "BLAS_FUNC(clatrz)"(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work) nogil
+cdef void clatrz(int *m, int *n, int *l, c *a, int *lda, c *tau, c *work) noexcept nogil:
+    
+    _fortran_clatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clauu2 "BLAS_FUNC(clauu2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void clauu2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clauum "BLAS_FUNC(clauum)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void clauum(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbcon "BLAS_FUNC(cpbcon)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbequ "BLAS_FUNC(cpbequ)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpbequ(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbrfs "BLAS_FUNC(cpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbstf "BLAS_FUNC(cpbstf)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbstf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbsv "BLAS_FUNC(cpbsv)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpbsv(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbsvx "BLAS_FUNC(cpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtf2 "BLAS_FUNC(cpbtf2)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbtf2(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtrf "BLAS_FUNC(cpbtrf)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbtrf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtrs "BLAS_FUNC(cpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpbtrs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftrf "BLAS_FUNC(cpftrf)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *info) nogil
+cdef void cpftrf(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_cpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftri "BLAS_FUNC(cpftri)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *info) nogil
+cdef void cpftri(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_cpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftrs "BLAS_FUNC(cpftrs)"(char *transr, char *uplo, int *n, int *nrhs, npy_complex64 *a, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpftrs(char *transr, char *uplo, int *n, int *nrhs, c *a, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpocon "BLAS_FUNC(cpocon)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpocon(char *uplo, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpoequ "BLAS_FUNC(cpoequ)"(int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpoequ(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpoequb "BLAS_FUNC(cpoequb)"(int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpoequb(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cporfs "BLAS_FUNC(cporfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cposv "BLAS_FUNC(cposv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cposv(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cposvx "BLAS_FUNC(cposvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotf2 "BLAS_FUNC(cpotf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotf2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotrf "BLAS_FUNC(cpotrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotrf(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotri "BLAS_FUNC(cpotri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotri(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotrs "BLAS_FUNC(cpotrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpotrs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppcon "BLAS_FUNC(cppcon)"(char *uplo, int *n, npy_complex64 *ap, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cppcon(char *uplo, int *n, c *ap, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cppcon(uplo, n, ap, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppequ "BLAS_FUNC(cppequ)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, int *info) nogil
+cdef void cppequ(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpprfs "BLAS_FUNC(cpprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppsv "BLAS_FUNC(cppsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cppsv(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppsvx "BLAS_FUNC(cppsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptrf "BLAS_FUNC(cpptrf)"(char *uplo, int *n, npy_complex64 *ap, int *info) nogil
+cdef void cpptrf(char *uplo, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_cpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptri "BLAS_FUNC(cpptri)"(char *uplo, int *n, npy_complex64 *ap, int *info) nogil
+cdef void cpptri(char *uplo, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_cpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptrs "BLAS_FUNC(cpptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpptrs(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpstf2 "BLAS_FUNC(cpstf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void cpstf2(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpstrf "BLAS_FUNC(cpstrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void cpstrf(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptcon "BLAS_FUNC(cptcon)"(int *n, s *d, npy_complex64 *e, s *anorm, s *rcond, s *rwork, int *info) nogil
+cdef void cptcon(int *n, s *d, c *e, s *anorm, s *rcond, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cptcon(n, d, e, anorm, rcond, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpteqr "BLAS_FUNC(cpteqr)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, s *work, int *info) nogil
+cdef void cpteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptrfs "BLAS_FUNC(cptrfs)"(char *uplo, int *n, int *nrhs, s *d, npy_complex64 *e, s *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cptrfs(uplo, n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptsv "BLAS_FUNC(cptsv)"(int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cptsv(int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptsvx "BLAS_FUNC(cptsvx)"(char *fact, int *n, int *nrhs, s *d, npy_complex64 *e, s *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpttrf "BLAS_FUNC(cpttrf)"(int *n, s *d, npy_complex64 *e, int *info) nogil
+cdef void cpttrf(int *n, s *d, c *e, int *info) noexcept nogil:
+    
+    _fortran_cpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpttrs "BLAS_FUNC(cpttrs)"(char *uplo, int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpttrs(char *uplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpttrs(uplo, n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptts2 "BLAS_FUNC(cptts2)"(int *iuplo, int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb) nogil
+cdef void cptts2(int *iuplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_cptts2(iuplo, n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_crot "BLAS_FUNC(crot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, npy_complex64 *s) nogil
+cdef void crot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, c *s) noexcept nogil:
+    
+    _fortran_crot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspcon "BLAS_FUNC(cspcon)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void cspcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_cspcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspmv "BLAS_FUNC(cspmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void cspmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_cspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspr "BLAS_FUNC(cspr)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil
+cdef void cspr(char *uplo, int *n, c *alpha, c *x, int *incx, c *ap) noexcept nogil:
+    
+    _fortran_cspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csprfs "BLAS_FUNC(csprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_csprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspsv "BLAS_FUNC(cspsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cspsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspsvx "BLAS_FUNC(cspsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_cspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptrf "BLAS_FUNC(csptrf)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info) nogil
+cdef void csptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_csptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptri "BLAS_FUNC(csptri)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptrs "BLAS_FUNC(csptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void csptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_csptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csrscl "BLAS_FUNC(csrscl)"(int *n, s *sa, npy_complex64 *sx, int *incx) nogil
+cdef void csrscl(int *n, s *sa, c *sx, int *incx) noexcept nogil:
+    
+    _fortran_csrscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstedc "BLAS_FUNC(cstedc)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_cstedc(compz, n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstegr "BLAS_FUNC(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, npy_complex64 *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_cstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstein "BLAS_FUNC(cstein)"(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, npy_complex64 *z, int *ldz, s *work, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_cstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstemr "BLAS_FUNC(cstemr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, npy_complex64 *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_cstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csteqr "BLAS_FUNC(csteqr)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, s *work, int *info) nogil
+cdef void csteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_csteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csycon "BLAS_FUNC(csycon)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void csycon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_csycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyconv "BLAS_FUNC(csyconv)"(char *uplo, char *way, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csyconv(char *uplo, char *way, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyequb "BLAS_FUNC(csyequb)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, npy_complex64 *work, int *info) nogil
+cdef void csyequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil:
+    
+    _fortran_csyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csymv "BLAS_FUNC(csymv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) 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:
+    
+    _fortran_csymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyr "BLAS_FUNC(csyr)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil
+cdef void csyr(char *uplo, int *n, c *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil:
+    
+    _fortran_csyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyrfs "BLAS_FUNC(csyrfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_csyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csysv "BLAS_FUNC(csysv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_csysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csysvx "BLAS_FUNC(csysvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, int *lwork, s *rwork, int *info) 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:
+    
+    _fortran_csysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyswapr "BLAS_FUNC(csyswapr)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2) nogil
+cdef void csyswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_csyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytf2 "BLAS_FUNC(csytf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void csytf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_csytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrf "BLAS_FUNC(csytrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void csytrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_csytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri "BLAS_FUNC(csytri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csytri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri2 "BLAS_FUNC(csytri2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void csytri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_csytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri2x "BLAS_FUNC(csytri2x)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info) nogil
+cdef void csytri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_csytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrs "BLAS_FUNC(csytrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void csytrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_csytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrs2 "BLAS_FUNC(csytrs2)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) 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:
+    
+    _fortran_csytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbcon "BLAS_FUNC(ctbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex64 *ab, int *ldab, s *rcond, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_ctbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbrfs "BLAS_FUNC(ctbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_ctbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbtrs "BLAS_FUNC(ctbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) 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:
+    
+    _fortran_ctbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfsm "BLAS_FUNC(ctfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, npy_complex64 *b, int *ldb) 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:
+    
+    _fortran_ctfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctftri "BLAS_FUNC(ctftri)"(char *transr, char *uplo, char *diag, int *n, npy_complex64 *a, int *info) nogil
+cdef void ctftri(char *transr, char *uplo, char *diag, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_ctftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfttp "BLAS_FUNC(ctfttp)"(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *ap, int *info) nogil
+cdef void ctfttp(char *transr, char *uplo, int *n, c *arf, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfttr "BLAS_FUNC(ctfttr)"(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctfttr(char *transr, char *uplo, int *n, c *arf, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgevc "BLAS_FUNC(ctgevc)"(char *side, char *howmny, bint *select, int *n, npy_complex64 *s, int *lds, npy_complex64 *p, int *ldp, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_ctgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgex2 "BLAS_FUNC(ctgex2)"(bint *wantq, bint *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *j1, int *info) 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:
+    
+    _fortran_ctgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgexc "BLAS_FUNC(ctgexc)"(bint *wantq, bint *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *ifst, int *ilst, int *info) 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:
+    
+    _fortran_ctgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsen "BLAS_FUNC(ctgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *m, s *pl, s *pr, s *dif, npy_complex64 *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_ctgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsja "BLAS_FUNC(ctgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, npy_complex64 *u, int *ldu, npy_complex64 *v, int *ldv, npy_complex64 *q, int *ldq, npy_complex64 *work, int *ncycle, int *info) 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:
+    
+    _fortran_ctgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsna "BLAS_FUNC(ctgsna)"(char *job, char *howmny, bint *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, s *s, s *dif, int *mm, int *m, npy_complex64 *work, int *lwork, int *iwork, int *info) 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:
+    
+    _fortran_ctgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsy2 "BLAS_FUNC(ctgsy2)"(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) 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:
+    
+    _fortran_ctgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsyl "BLAS_FUNC(ctgsyl)"(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, s *scale, s *dif, npy_complex64 *work, int *lwork, int *iwork, int *info) 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:
+    
+    _fortran_ctgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpcon "BLAS_FUNC(ctpcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctpcon(char *norm, char *uplo, char *diag, int *n, c *ap, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpmqrt "BLAS_FUNC(ctpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) 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:
+    
+    _fortran_ctpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpqrt "BLAS_FUNC(ctpqrt)"(int *m, int *n, int *l, int *nb, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info) 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:
+    
+    _fortran_ctpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpqrt2 "BLAS_FUNC(ctpqrt2)"(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, int *info) 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:
+    
+    _fortran_ctpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctprfb "BLAS_FUNC(ctprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *ldwork) 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:
+    
+    _fortran_ctprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctprfs "BLAS_FUNC(ctprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_ctprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctptri "BLAS_FUNC(ctptri)"(char *uplo, char *diag, int *n, npy_complex64 *ap, int *info) nogil
+cdef void ctptri(char *uplo, char *diag, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctptrs "BLAS_FUNC(ctptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void ctptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ctptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpttf "BLAS_FUNC(ctpttf)"(char *transr, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *arf, int *info) nogil
+cdef void ctpttf(char *transr, char *uplo, int *n, c *ap, c *arf, int *info) noexcept nogil:
+    
+    _fortran_ctpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpttr "BLAS_FUNC(ctpttr)"(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctpttr(char *uplo, int *n, c *ap, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrcon "BLAS_FUNC(ctrcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, s *rcond, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_ctrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrevc "BLAS_FUNC(ctrevc)"(char *side, char *howmny, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_ctrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrexc "BLAS_FUNC(ctrexc)"(char *compq, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, int *ifst, int *ilst, int *info) nogil
+cdef void ctrexc(char *compq, int *n, c *t, int *ldt, c *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ctrexc(compq, n, t, ldt, q, ldq, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrrfs "BLAS_FUNC(ctrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) 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:
+    
+    _fortran_ctrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsen "BLAS_FUNC(ctrsen)"(char *job, char *compq, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, npy_complex64 *w, int *m, s *s, s *sep, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_ctrsen(job, compq, select, n, t, ldt, q, ldq, w, m, s, sep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsna "BLAS_FUNC(ctrsna)"(char *job, char *howmny, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, s *s, s *sep, int *mm, int *m, npy_complex64 *work, int *ldwork, s *rwork, int *info) 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:
+    
+    _fortran_ctrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsyl "BLAS_FUNC(ctrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, s *scale, int *info) 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:
+    
+    _fortran_ctrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrti2 "BLAS_FUNC(ctrti2)"(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctrti2(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrtri "BLAS_FUNC(ctrtri)"(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctrtri(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrtrs "BLAS_FUNC(ctrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) 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:
+    
+    _fortran_ctrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrttf "BLAS_FUNC(ctrttf)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *arf, int *info) nogil
+cdef void ctrttf(char *transr, char *uplo, int *n, c *a, int *lda, c *arf, int *info) noexcept nogil:
+    
+    _fortran_ctrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrttp "BLAS_FUNC(ctrttp)"(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *ap, int *info) nogil
+cdef void ctrttp(char *uplo, int *n, c *a, int *lda, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctzrzf "BLAS_FUNC(ctzrzf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void ctzrzf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ctzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunbdb "BLAS_FUNC(cunbdb)"(char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, s *theta, s *phi, npy_complex64 *taup1, npy_complex64 *taup2, npy_complex64 *tauq1, npy_complex64 *tauq2, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cuncsd "BLAS_FUNC(cuncsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, s *theta, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) 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:
+    
+    _fortran_cuncsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, lrwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cung2l "BLAS_FUNC(cung2l)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cung2l(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cung2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cung2r "BLAS_FUNC(cung2r)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cung2r(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cung2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungbr "BLAS_FUNC(cungbr)"(char *vect, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cungbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunghr "BLAS_FUNC(cunghr)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunghr(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungl2 "BLAS_FUNC(cungl2)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cungl2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cungl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunglq "BLAS_FUNC(cunglq)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunglq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungql "BLAS_FUNC(cungql)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungql(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungqr "BLAS_FUNC(cungqr)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungqr(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungr2 "BLAS_FUNC(cungr2)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cungr2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cungr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungrq "BLAS_FUNC(cungrq)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungrq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungtr "BLAS_FUNC(cungtr)"(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungtr(char *uplo, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunm2l "BLAS_FUNC(cunm2l)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cunm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunm2r "BLAS_FUNC(cunm2r)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cunm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmbr "BLAS_FUNC(cunmbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunmbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmhr "BLAS_FUNC(cunmhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunmhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunml2 "BLAS_FUNC(cunml2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cunml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmlq "BLAS_FUNC(cunmlq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunmlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmql "BLAS_FUNC(cunmql)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunmql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmqr "BLAS_FUNC(cunmqr)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunmqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmr2 "BLAS_FUNC(cunmr2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cunmr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmr3 "BLAS_FUNC(cunmr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cunmr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmrq "BLAS_FUNC(cunmrq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunmrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmrz "BLAS_FUNC(cunmrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunmrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmtr "BLAS_FUNC(cunmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) 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:
+    
+    _fortran_cunmtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cupgtr "BLAS_FUNC(cupgtr)"(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info) nogil
+cdef void cupgtr(char *uplo, int *n, c *ap, c *tau, c *q, int *ldq, c *work, int *info) noexcept nogil:
+    
+    _fortran_cupgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cupmtr "BLAS_FUNC(cupmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) 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:
+    
+    _fortran_cupmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbbcsd "BLAS_FUNC(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) 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:
+    
+    _fortran_dbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbdsdc "BLAS_FUNC(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) 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:
+    
+    _fortran_dbdsdc(uplo, compq, n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbdsqr "BLAS_FUNC(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) 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:
+    
+    _fortran_dbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ddisna "BLAS_FUNC(ddisna)"(char *job, int *m, int *n, d *d, d *sep, int *info) nogil
+cdef void ddisna(char *job, int *m, int *n, d *d, d *sep, int *info) noexcept nogil:
+    
+    _fortran_ddisna(job, m, n, d, sep, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbbrd "BLAS_FUNC(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) 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:
+    
+    _fortran_dgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbcon "BLAS_FUNC(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) 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:
+    
+    _fortran_dgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbequ "BLAS_FUNC(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) 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:
+    
+    _fortran_dgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbequb "BLAS_FUNC(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) 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:
+    
+    _fortran_dgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbsv "BLAS_FUNC(dgbsv)"(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) 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:
+    
+    _fortran_dgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtf2 "BLAS_FUNC(dgbtf2)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void dgbtf2(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtrf "BLAS_FUNC(dgbtrf)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void dgbtrf(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtrs "BLAS_FUNC(dgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) 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:
+    
+    _fortran_dgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebak "BLAS_FUNC(dgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) 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:
+    
+    _fortran_dgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebal "BLAS_FUNC(dgebal)"(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) nogil
+cdef void dgebal(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil:
+    
+    _fortran_dgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebd2 "BLAS_FUNC(dgebd2)"(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) 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:
+    
+    _fortran_dgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebrd "BLAS_FUNC(dgebrd)"(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) 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:
+    
+    _fortran_dgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgecon "BLAS_FUNC(dgecon)"(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dgecon(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgecon(norm, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeequ "BLAS_FUNC(dgeequ)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) 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:
+    
+    _fortran_dgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeequb "BLAS_FUNC(dgeequb)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) 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:
+    
+    _fortran_dgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgees "BLAS_FUNC(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) 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:
+    
+    _fortran_dgees(jobvs, sort, <_dselect2*>select, n, a, lda, sdim, wr, wi, vs, ldvs, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeesx "BLAS_FUNC(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) 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:
+    
+    _fortran_dgeesx(jobvs, sort, <_dselect2*>select, sense, n, a, lda, sdim, wr, wi, vs, ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeev "BLAS_FUNC(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) 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:
+    
+    _fortran_dgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeevx "BLAS_FUNC(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) 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:
+    
+    _fortran_dgeevx(balanc, jobvl, jobvr, sense, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgehd2 "BLAS_FUNC(dgehd2)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgehd2(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgehrd "BLAS_FUNC(dgehrd)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgehrd(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgejsv "BLAS_FUNC(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) 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:
+    
+    _fortran_dgejsv(joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelq2 "BLAS_FUNC(dgelq2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgelq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelqf "BLAS_FUNC(dgelqf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgelqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgels "BLAS_FUNC(dgels)"(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) 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:
+    
+    _fortran_dgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelsd "BLAS_FUNC(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) 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:
+    
+    _fortran_dgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelss "BLAS_FUNC(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) 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:
+    
+    _fortran_dgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelsy "BLAS_FUNC(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) 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:
+    
+    _fortran_dgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgemqrt "BLAS_FUNC(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) 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:
+    
+    _fortran_dgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeql2 "BLAS_FUNC(dgeql2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeql2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqlf "BLAS_FUNC(dgeqlf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqlf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqp3 "BLAS_FUNC(dgeqp3)"(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqp3(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqr2 "BLAS_FUNC(dgeqr2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeqr2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqr2p "BLAS_FUNC(dgeqr2p)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeqr2p(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrf "BLAS_FUNC(dgeqrf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqrf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrfp "BLAS_FUNC(dgeqrfp)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqrfp(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt "BLAS_FUNC(dgeqrt)"(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) nogil
+cdef void dgeqrt(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt2 "BLAS_FUNC(dgeqrt2)"(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) nogil
+cdef void dgeqrt2(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt3 "BLAS_FUNC(dgeqrt3)"(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) nogil
+cdef void dgeqrt3(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerq2 "BLAS_FUNC(dgerq2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgerq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerqf "BLAS_FUNC(dgerqf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgerqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesc2 "BLAS_FUNC(dgesc2)"(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) nogil
+cdef void dgesc2(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil:
+    
+    _fortran_dgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesdd "BLAS_FUNC(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) 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:
+    
+    _fortran_dgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesv "BLAS_FUNC(dgesv)"(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvd "BLAS_FUNC(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) 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:
+    
+    _fortran_dgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvj "BLAS_FUNC(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) 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:
+    
+    _fortran_dgesvj(joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetc2 "BLAS_FUNC(dgetc2)"(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void dgetc2(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_dgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetf2 "BLAS_FUNC(dgetf2)"(int *m, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dgetf2(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetrf "BLAS_FUNC(dgetrf)"(int *m, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dgetrf(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetri "BLAS_FUNC(dgetri)"(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dgetri(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetrs "BLAS_FUNC(dgetrs)"(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgetrs(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggbak "BLAS_FUNC(dggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) 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:
+    
+    _fortran_dggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggbal "BLAS_FUNC(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) 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:
+    
+    _fortran_dggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgges "BLAS_FUNC(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) 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:
+    
+    _fortran_dgges(jobvsl, jobvsr, sort, <_dselect3*>selctg, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggesx "BLAS_FUNC(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) 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:
+    
+    _fortran_dggesx(jobvsl, jobvsr, sort, <_dselect3*>selctg, sense, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggev "BLAS_FUNC(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) 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:
+    
+    _fortran_dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggevx "BLAS_FUNC(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) 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:
+    
+    _fortran_dggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggglm "BLAS_FUNC(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) 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:
+    
+    _fortran_dggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgghrd "BLAS_FUNC(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) 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:
+    
+    _fortran_dgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgglse "BLAS_FUNC(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) 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:
+    
+    _fortran_dgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggqrf "BLAS_FUNC(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) 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:
+    
+    _fortran_dggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggrqf "BLAS_FUNC(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) 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:
+    
+    _fortran_dggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgsvj0 "BLAS_FUNC(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) 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:
+    
+    _fortran_dgsvj0(jobv, m, n, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgsvj1 "BLAS_FUNC(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) 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:
+    
+    _fortran_dgsvj1(jobv, m, n, n1, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtcon "BLAS_FUNC(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) 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:
+    
+    _fortran_dgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtsv "BLAS_FUNC(dgtsv)"(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) nogil
+cdef void dgtsv(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgttrf "BLAS_FUNC(dgttrf)"(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) nogil
+cdef void dgttrf(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgttrs "BLAS_FUNC(dgttrs)"(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) 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:
+    
+    _fortran_dgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtts2 "BLAS_FUNC(dgtts2)"(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) 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:
+    
+    _fortran_dgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhgeqz "BLAS_FUNC(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) 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:
+    
+    _fortran_dhgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alphar, alphai, beta, q, ldq, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhsein "BLAS_FUNC(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) 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:
+    
+    _fortran_dhsein(side, eigsrc, initv, select, n, h, ldh, wr, wi, vl, ldvl, vr, ldvr, mm, m, work, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhseqr "BLAS_FUNC(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) 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:
+    
+    _fortran_dhseqr(job, compz, n, ilo, ihi, h, ldh, wr, wi, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    bint _fortran_disnan "BLAS_FUNC(disnan)"(d *din) nogil
+cdef bint disnan(d *din) noexcept nogil:
+    
+    return _fortran_disnan(din)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlabad "BLAS_FUNC(dlabad)"(d *small, d *large) nogil
+cdef void dlabad(d *small, d *large) noexcept nogil:
+    
+    _fortran_dlabad(small, large)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlabrd "BLAS_FUNC(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) 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:
+    
+    _fortran_dlabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacn2 "BLAS_FUNC(dlacn2)"(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) nogil
+cdef void dlacn2(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_dlacn2(n, v, x, isgn, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacon "BLAS_FUNC(dlacon)"(int *n, d *v, d *x, int *isgn, d *est, int *kase) nogil
+cdef void dlacon(int *n, d *v, d *x, int *isgn, d *est, int *kase) noexcept nogil:
+    
+    _fortran_dlacon(n, v, x, isgn, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacpy "BLAS_FUNC(dlacpy)"(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) nogil
+cdef void dlacpy(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dlacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dladiv "BLAS_FUNC(dladiv)"(d *a, d *b, d *c, d *d, d *p, d *q) nogil
+cdef void dladiv(d *a, d *b, d *c, d *d, d *p, d *q) noexcept nogil:
+    
+    _fortran_dladiv(a, b, c, d, p, q)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlae2 "BLAS_FUNC(dlae2)"(d *a, d *b, d *c, d *rt1, d *rt2) nogil
+cdef void dlae2(d *a, d *b, d *c, d *rt1, d *rt2) noexcept nogil:
+    
+    _fortran_dlae2(a, b, c, rt1, rt2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaebz "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaebz(ijob, nitmax, n, mmax, minp, nbmin, abstol, reltol, pivmin, d, e, e2, nval, ab, c, mout, nab, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed0 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaed0(icompq, qsiz, n, d, e, q, ldq, qstore, ldqs, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed1 "BLAS_FUNC(dlaed1)"(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) 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:
+    
+    _fortran_dlaed1(n, d, q, ldq, indxq, rho, cutpnt, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaed2(k, n, n1, d, q, ldq, indxq, rho, z, dlamda, w, q2, indx, indxc, indxp, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed3 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaed3(k, n, n1, d, q, ldq, rho, dlamda, q2, indx, ctot, w, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed4 "BLAS_FUNC(dlaed4)"(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) nogil
+cdef void dlaed4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) noexcept nogil:
+    
+    _fortran_dlaed4(n, i, d, z, delta, rho, dlam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed5 "BLAS_FUNC(dlaed5)"(int *i, d *d, d *z, d *delta, d *rho, d *dlam) nogil
+cdef void dlaed5(int *i, d *d, d *z, d *delta, d *rho, d *dlam) noexcept nogil:
+    
+    _fortran_dlaed5(i, d, z, delta, rho, dlam)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed6 "BLAS_FUNC(dlaed6)"(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) nogil
+cdef void dlaed6(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dlaed6(kniter, orgati, rho, d, z, finit, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed7 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaed7(icompq, n, qsiz, tlvls, curlvl, curpbm, d, q, ldq, indxq, rho, cutpnt, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed8 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaed8(icompq, k, n, qsiz, d, q, ldq, indxq, rho, cutpnt, z, dlamda, q2, ldq2, w, perm, givptr, givcol, givnum, indxp, indx, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed9 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaed9(k, kstart, kstop, n, d, q, ldq, rho, dlamda, w, s, lds, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaeda "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaeda(n, tlvls, curlvl, curpbm, prmptr, perm, givptr, givcol, givnum, q, qptr, z, ztemp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaein "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaein(rightv, noinit, n, h, ldh, wr, wi, vr, vi, b, ldb, work, eps3, smlnum, bignum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaev2 "BLAS_FUNC(dlaev2)"(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) nogil
+cdef void dlaev2(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) noexcept nogil:
+    
+    _fortran_dlaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaexc "BLAS_FUNC(dlaexc)"(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) 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:
+    
+    _fortran_dlaexc(wantq, n, t, ldt, q, ldq, j1, n1, n2, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlag2 "BLAS_FUNC(dlag2)"(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) 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:
+    
+    _fortran_dlag2(a, lda, b, ldb, safmin, scale1, scale2, wr1, wr2, wi)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlag2s "BLAS_FUNC(dlag2s)"(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) nogil
+cdef void dlag2s(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_dlag2s(m, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlags2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagtf "BLAS_FUNC(dlagtf)"(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) nogil
+cdef void dlagtf(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) noexcept nogil:
+    
+    _fortran_dlagtf(n, a, lambda_, b, c, tol, d, in_, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagtm "BLAS_FUNC(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) 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:
+    
+    _fortran_dlagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagts "BLAS_FUNC(dlagts)"(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) 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:
+    
+    _fortran_dlagts(job, n, a, b, c, d, in_, y, tol, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagv2 "BLAS_FUNC(dlagv2)"(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) 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:
+    
+    _fortran_dlagv2(a, lda, b, ldb, alphar, alphai, beta, csl, snl, csr, snr)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlahqr "BLAS_FUNC(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) 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:
+    
+    _fortran_dlahqr(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlahr2 "BLAS_FUNC(dlahr2)"(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) 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:
+    
+    _fortran_dlahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaic1 "BLAS_FUNC(dlaic1)"(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) nogil
+cdef void dlaic1(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) noexcept nogil:
+    
+    _fortran_dlaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaln2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaln2(ltrans, na, nw, smin, ca, a, lda, d1, d2, b, ldb, wr, wi, x, ldx, scale, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlals0 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlalsa "BLAS_FUNC(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) 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:
+    
+    _fortran_dlalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlalsd "BLAS_FUNC(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) 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:
+    
+    _fortran_dlalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlamch "BLAS_FUNC(dlamch)"(char *cmach) nogil
+cdef d dlamch(char *cmach) noexcept nogil:
+    
+    return _fortran_dlamch(cmach)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlamrg "BLAS_FUNC(dlamrg)"(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) nogil
+cdef void dlamrg(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) noexcept nogil:
+    
+    _fortran_dlamrg(n1, n2, a, dtrd1, dtrd2, index_bn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_dlaneg "BLAS_FUNC(dlaneg)"(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) nogil
+cdef int dlaneg(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) noexcept nogil:
+    
+    return _fortran_dlaneg(n, d, lld, sigma, pivmin, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlangb "BLAS_FUNC(dlangb)"(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) nogil
+cdef d dlangb(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlange "BLAS_FUNC(dlange)"(char *norm, int *m, int *n, d *a, int *lda, d *work) nogil
+cdef d dlange(char *norm, int *m, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlangt "BLAS_FUNC(dlangt)"(char *norm, int *n, d *dl, d *d_, d *du) nogil
+cdef d dlangt(char *norm, int *n, d *dl, d *d_, d *du) noexcept nogil:
+    
+    return _fortran_dlangt(norm, n, dl, d_, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlanhs "BLAS_FUNC(dlanhs)"(char *norm, int *n, d *a, int *lda, d *work) nogil
+cdef d dlanhs(char *norm, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansb "BLAS_FUNC(dlansb)"(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) nogil
+cdef d dlansb(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansf "BLAS_FUNC(dlansf)"(char *norm, char *transr, char *uplo, int *n, d *a, d *work) nogil
+cdef d dlansf(char *norm, char *transr, char *uplo, int *n, d *a, d *work) noexcept nogil:
+    
+    return _fortran_dlansf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansp "BLAS_FUNC(dlansp)"(char *norm, char *uplo, int *n, d *ap, d *work) nogil
+cdef d dlansp(char *norm, char *uplo, int *n, d *ap, d *work) noexcept nogil:
+    
+    return _fortran_dlansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlanst "BLAS_FUNC(dlanst)"(char *norm, int *n, d *d_, d *e) nogil
+cdef d dlanst(char *norm, int *n, d *d_, d *e) noexcept nogil:
+    
+    return _fortran_dlanst(norm, n, d_, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansy "BLAS_FUNC(dlansy)"(char *norm, char *uplo, int *n, d *a, int *lda, d *work) nogil
+cdef d dlansy(char *norm, char *uplo, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantb "BLAS_FUNC(dlantb)"(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) nogil
+cdef d dlantb(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantp "BLAS_FUNC(dlantp)"(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) nogil
+cdef d dlantp(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) noexcept nogil:
+    
+    return _fortran_dlantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantr "BLAS_FUNC(dlantr)"(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) nogil
+cdef d dlantr(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlanv2 "BLAS_FUNC(dlanv2)"(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) 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:
+    
+    _fortran_dlanv2(a, b, c, d, rt1r, rt1i, rt2r, rt2i, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapll "BLAS_FUNC(dlapll)"(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) nogil
+cdef void dlapll(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) noexcept nogil:
+    
+    _fortran_dlapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapmr "BLAS_FUNC(dlapmr)"(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) nogil
+cdef void dlapmr(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_dlapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapmt "BLAS_FUNC(dlapmt)"(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) nogil
+cdef void dlapmt(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_dlapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlapy2 "BLAS_FUNC(dlapy2)"(d *x, d *y) nogil
+cdef d dlapy2(d *x, d *y) noexcept nogil:
+    
+    return _fortran_dlapy2(x, y)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlapy3 "BLAS_FUNC(dlapy3)"(d *x, d *y, d *z) nogil
+cdef d dlapy3(d *x, d *y, d *z) noexcept nogil:
+    
+    return _fortran_dlapy3(x, y, z)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqgb "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqge "BLAS_FUNC(dlaqge)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) 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:
+    
+    _fortran_dlaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqp2 "BLAS_FUNC(dlaqp2)"(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) 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:
+    
+    _fortran_dlaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqps "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr0 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaqr0(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr1 "BLAS_FUNC(dlaqr1)"(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) nogil
+cdef void dlaqr1(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) noexcept nogil:
+    
+    _fortran_dlaqr1(n, h, ldh, sr1, si1, sr2, si2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr3 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr4 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaqr4(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr5 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, sr, si, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsb "BLAS_FUNC(dlaqsb)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsb(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsp "BLAS_FUNC(dlaqsp)"(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsp(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsy "BLAS_FUNC(dlaqsy)"(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsy(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqtr "BLAS_FUNC(dlaqtr)"(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) 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:
+    
+    _fortran_dlaqtr(ltran, lreal, n, t, ldt, b, w, scale, x, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlar1v "BLAS_FUNC(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) 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:
+    
+    _fortran_dlar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlar2v "BLAS_FUNC(dlar2v)"(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) nogil
+cdef void dlar2v(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) noexcept nogil:
+    
+    _fortran_dlar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarf "BLAS_FUNC(dlarf)"(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) nogil
+cdef void dlarf(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil:
+    
+    _fortran_dlarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfb "BLAS_FUNC(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) 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:
+    
+    _fortran_dlarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfg "BLAS_FUNC(dlarfg)"(int *n, d *alpha, d *x, int *incx, d *tau) nogil
+cdef void dlarfg(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil:
+    
+    _fortran_dlarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfgp "BLAS_FUNC(dlarfgp)"(int *n, d *alpha, d *x, int *incx, d *tau) nogil
+cdef void dlarfgp(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil:
+    
+    _fortran_dlarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarft "BLAS_FUNC(dlarft)"(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) nogil
+cdef void dlarft(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil:
+    
+    _fortran_dlarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfx "BLAS_FUNC(dlarfx)"(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) nogil
+cdef void dlarfx(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) noexcept nogil:
+    
+    _fortran_dlarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlargv "BLAS_FUNC(dlargv)"(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) nogil
+cdef void dlargv(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) noexcept nogil:
+    
+    _fortran_dlargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarnv "BLAS_FUNC(dlarnv)"(int *idist, int *iseed, int *n, d *x) nogil
+cdef void dlarnv(int *idist, int *iseed, int *n, d *x) noexcept nogil:
+    
+    _fortran_dlarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarra "BLAS_FUNC(dlarra)"(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) nogil
+cdef void dlarra(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil:
+    
+    _fortran_dlarra(n, d, e, e2, spltol, tnrm, nsplit, isplit, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrb "BLAS_FUNC(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) 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:
+    
+    _fortran_dlarrb(n, d, lld, ifirst, ilast, rtol1, rtol2, offset, w, wgap, werr, work, iwork, pivmin, spdiam, twist, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrc "BLAS_FUNC(dlarrc)"(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) 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:
+    
+    _fortran_dlarrc(jobt, n, vl, vu, d, e, pivmin, eigcnt, lcnt, rcnt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrd "BLAS_FUNC(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) 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:
+    
+    _fortran_dlarrd(range, order, n, vl, vu, il, iu, gers, reltol, d, e, e2, pivmin, nsplit, isplit, m, w, werr, wl, wu, iblock, indexw, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarre "BLAS_FUNC(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) 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:
+    
+    _fortran_dlarre(range, n, vl, vu, il, iu, d, e, e2, rtol1, rtol2, spltol, nsplit, isplit, m, w, werr, wgap, iblock, indexw, gers, pivmin, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrf "BLAS_FUNC(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) 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:
+    
+    _fortran_dlarrf(n, d, l, ld, clstrt, clend, w, wgap, werr, spdiam, clgapl, clgapr, pivmin, sigma, dplus, lplus, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrj "BLAS_FUNC(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) 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:
+    
+    _fortran_dlarrj(n, d, e2, ifirst, ilast, rtol, offset, w, werr, work, iwork, pivmin, spdiam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrk "BLAS_FUNC(dlarrk)"(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) 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:
+    
+    _fortran_dlarrk(n, iw, gl, gu, d, e2, pivmin, reltol, w, werr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrr "BLAS_FUNC(dlarrr)"(int *n, d *d, d *e, int *info) nogil
+cdef void dlarrr(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dlarrr(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrv "BLAS_FUNC(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) 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:
+    
+    _fortran_dlarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartg "BLAS_FUNC(dlartg)"(d *f, d *g, d *cs, d *sn, d *r) nogil
+cdef void dlartg(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil:
+    
+    _fortran_dlartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartgp "BLAS_FUNC(dlartgp)"(d *f, d *g, d *cs, d *sn, d *r) nogil
+cdef void dlartgp(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil:
+    
+    _fortran_dlartgp(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartgs "BLAS_FUNC(dlartgs)"(d *x, d *y, d *sigma, d *cs, d *sn) nogil
+cdef void dlartgs(d *x, d *y, d *sigma, d *cs, d *sn) noexcept nogil:
+    
+    _fortran_dlartgs(x, y, sigma, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartv "BLAS_FUNC(dlartv)"(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) nogil
+cdef void dlartv(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) noexcept nogil:
+    
+    _fortran_dlartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaruv "BLAS_FUNC(dlaruv)"(int *iseed, int *n, d *x) nogil
+cdef void dlaruv(int *iseed, int *n, d *x) noexcept nogil:
+    
+    _fortran_dlaruv(iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarz "BLAS_FUNC(dlarz)"(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) 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:
+    
+    _fortran_dlarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarzb "BLAS_FUNC(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) 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:
+    
+    _fortran_dlarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarzt "BLAS_FUNC(dlarzt)"(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) nogil
+cdef void dlarzt(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil:
+    
+    _fortran_dlarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlas2 "BLAS_FUNC(dlas2)"(d *f, d *g, d *h, d *ssmin, d *ssmax) nogil
+cdef void dlas2(d *f, d *g, d *h, d *ssmin, d *ssmax) noexcept nogil:
+    
+    _fortran_dlas2(f, g, h, ssmin, ssmax)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlascl "BLAS_FUNC(dlascl)"(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) 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:
+    
+    _fortran_dlascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd0 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasd0(n, sqre, d, e, u, ldu, vt, ldvt, smlsiz, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd1 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasd1(nl, nr, sqre, d, alpha, beta, u, ldu, vt, ldvt, idxq, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasd2(nl, nr, sqre, k, d, z, alpha, beta, u, ldu, vt, ldvt, dsigma, u2, ldu2, vt2, ldvt2, idxp, idx, idxc, idxq, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd3 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasd3(nl, nr, sqre, k, d, q, ldq, dsigma, u, ldu, u2, ldu2, vt, ldvt, vt2, ldvt2, idxc, ctot, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd4 "BLAS_FUNC(dlasd4)"(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) nogil
+cdef void dlasd4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd4(n, i, d, z, delta, rho, sigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd5 "BLAS_FUNC(dlasd5)"(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) nogil
+cdef void dlasd5(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) noexcept nogil:
+    
+    _fortran_dlasd5(i, d, z, delta, rho, dsigma, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd6 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasd6(icompq, nl, nr, sqre, d, vf, vl, alpha, beta, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd7 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasd7(icompq, nl, nr, sqre, k, d, z, zw, vf, vfw, vl, vlw, alpha, beta, dsigma, idx, idxp, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, c, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd8 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasd8(icompq, k, d, z, vf, vl, difl, difr, lddifr, dsigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasda "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasda(icompq, smlsiz, n, sqre, d, e, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasdq "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasdq(uplo, sqre, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasdt "BLAS_FUNC(dlasdt)"(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) nogil
+cdef void dlasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil:
+    
+    _fortran_dlasdt(n, lvl, nd, inode, ndiml, ndimr, msub)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaset "BLAS_FUNC(dlaset)"(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) nogil
+cdef void dlaset(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dlaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq1 "BLAS_FUNC(dlasq1)"(int *n, d *d, d *e, d *work, int *info) nogil
+cdef void dlasq1(int *n, d *d, d *e, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasq1(n, d, e, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq2 "BLAS_FUNC(dlasq2)"(int *n, d *z, int *info) nogil
+cdef void dlasq2(int *n, d *z, int *info) noexcept nogil:
+    
+    _fortran_dlasq2(n, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq3 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasq3(i0, n0, z, pp, dmin, sigma, desig, qmax, nfail, iter, ndiv, ieee, ttype, dmin1, dmin2, dn, dn1, dn2, g, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq4 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasq4(i0, n0, z, pp, n0in, dmin, dmin1, dmin2, dn, dn1, dn2, tau, ttype, g)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq6 "BLAS_FUNC(dlasq6)"(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) 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:
+    
+    _fortran_dlasq6(i0, n0, z, pp, dmin, dmin1, dmin2, dn, dnm1, dnm2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasr "BLAS_FUNC(dlasr)"(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) nogil
+cdef void dlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dlasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasrt "BLAS_FUNC(dlasrt)"(char *id, int *n, d *d, int *info) nogil
+cdef void dlasrt(char *id, int *n, d *d, int *info) noexcept nogil:
+    
+    _fortran_dlasrt(id, n, d, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlassq "BLAS_FUNC(dlassq)"(int *n, d *x, int *incx, d *scale, d *sumsq) nogil
+cdef void dlassq(int *n, d *x, int *incx, d *scale, d *sumsq) noexcept nogil:
+    
+    _fortran_dlassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasv2 "BLAS_FUNC(dlasv2)"(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) nogil
+cdef void dlasv2(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) noexcept nogil:
+    
+    _fortran_dlasv2(f, g, h, ssmin, ssmax, snr, csr, snl, csl)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaswp "BLAS_FUNC(dlaswp)"(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void dlaswp(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_dlaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasy2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dlasy2(ltranl, ltranr, isgn, n1, n2, tl, ldtl, tr, ldtr, b, ldb, scale, x, ldx, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasyf "BLAS_FUNC(dlasyf)"(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) 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:
+    
+    _fortran_dlasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlat2s "BLAS_FUNC(dlat2s)"(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) nogil
+cdef void dlat2s(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_dlat2s(uplo, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatbs "BLAS_FUNC(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) 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:
+    
+    _fortran_dlatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatdf "BLAS_FUNC(dlatdf)"(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) nogil
+cdef void dlatdf(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_dlatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatps "BLAS_FUNC(dlatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) 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:
+    
+    _fortran_dlatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrd "BLAS_FUNC(dlatrd)"(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) nogil
+cdef void dlatrd(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) noexcept nogil:
+    
+    _fortran_dlatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrs "BLAS_FUNC(dlatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) 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:
+    
+    _fortran_dlatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrz "BLAS_FUNC(dlatrz)"(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) nogil
+cdef void dlatrz(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) noexcept nogil:
+    
+    _fortran_dlatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlauu2 "BLAS_FUNC(dlauu2)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dlauu2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dlauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlauum "BLAS_FUNC(dlauum)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dlauum(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dlauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dopgtr "BLAS_FUNC(dopgtr)"(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) nogil
+cdef void dopgtr(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) noexcept nogil:
+    
+    _fortran_dopgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dopmtr "BLAS_FUNC(dopmtr)"(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) 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:
+    
+    _fortran_dopmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorbdb "BLAS_FUNC(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) 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:
+    
+    _fortran_dorbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorcsd "BLAS_FUNC(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) 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:
+    
+    _fortran_dorcsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorg2l "BLAS_FUNC(dorg2l)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorg2l(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorg2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorg2r "BLAS_FUNC(dorg2r)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorg2r(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorg2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgbr "BLAS_FUNC(dorgbr)"(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) 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:
+    
+    _fortran_dorgbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorghr "BLAS_FUNC(dorghr)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorghr(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgl2 "BLAS_FUNC(dorgl2)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorgl2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorgl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorglq "BLAS_FUNC(dorglq)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorglq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgql "BLAS_FUNC(dorgql)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgql(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgqr "BLAS_FUNC(dorgqr)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgqr(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgr2 "BLAS_FUNC(dorgr2)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorgr2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorgr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgrq "BLAS_FUNC(dorgrq)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgrq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgtr "BLAS_FUNC(dorgtr)"(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgtr(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorm2l "BLAS_FUNC(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) 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:
+    
+    _fortran_dorm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorm2r "BLAS_FUNC(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) 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:
+    
+    _fortran_dorm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormbr "BLAS_FUNC(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) 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:
+    
+    _fortran_dormbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormhr "BLAS_FUNC(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) 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:
+    
+    _fortran_dormhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorml2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dorml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormlq "BLAS_FUNC(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) 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:
+    
+    _fortran_dormlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormql "BLAS_FUNC(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) 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:
+    
+    _fortran_dormql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormqr "BLAS_FUNC(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) 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:
+    
+    _fortran_dormqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormr2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dormr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormr3 "BLAS_FUNC(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) 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:
+    
+    _fortran_dormr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormrq "BLAS_FUNC(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) 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:
+    
+    _fortran_dormrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormrz "BLAS_FUNC(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) 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:
+    
+    _fortran_dormrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormtr "BLAS_FUNC(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) 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:
+    
+    _fortran_dormtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbcon "BLAS_FUNC(dpbcon)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) 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:
+    
+    _fortran_dpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbequ "BLAS_FUNC(dpbequ)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpbequ(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbstf "BLAS_FUNC(dpbstf)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbstf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbsv "BLAS_FUNC(dpbsv)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil
+cdef void dpbsv(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtf2 "BLAS_FUNC(dpbtf2)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbtf2(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtrf "BLAS_FUNC(dpbtrf)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbtrf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtrs "BLAS_FUNC(dpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil
+cdef void dpbtrs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftrf "BLAS_FUNC(dpftrf)"(char *transr, char *uplo, int *n, d *a, int *info) nogil
+cdef void dpftrf(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftri "BLAS_FUNC(dpftri)"(char *transr, char *uplo, int *n, d *a, int *info) nogil
+cdef void dpftri(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftrs "BLAS_FUNC(dpftrs)"(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) nogil
+cdef void dpftrs(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpocon "BLAS_FUNC(dpocon)"(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dpocon(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpocon(uplo, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpoequ "BLAS_FUNC(dpoequ)"(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpoequ(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpoequb "BLAS_FUNC(dpoequb)"(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpoequb(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dporfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dposv "BLAS_FUNC(dposv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dposvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotf2 "BLAS_FUNC(dpotf2)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotf2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotrf "BLAS_FUNC(dpotrf)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotrf(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotri "BLAS_FUNC(dpotri)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotri(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotrs "BLAS_FUNC(dpotrs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dpotrs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppcon "BLAS_FUNC(dppcon)"(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dppcon(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dppcon(uplo, n, ap, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppequ "BLAS_FUNC(dppequ)"(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) nogil
+cdef void dppequ(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpprfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppsv "BLAS_FUNC(dppsv)"(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dppsv(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptrf "BLAS_FUNC(dpptrf)"(char *uplo, int *n, d *ap, int *info) nogil
+cdef void dpptrf(char *uplo, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptri "BLAS_FUNC(dpptri)"(char *uplo, int *n, d *ap, int *info) nogil
+cdef void dpptri(char *uplo, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptrs "BLAS_FUNC(dpptrs)"(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dpptrs(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpstf2 "BLAS_FUNC(dpstf2)"(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void dpstf2(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpstrf "BLAS_FUNC(dpstrf)"(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void dpstrf(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptcon "BLAS_FUNC(dptcon)"(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) nogil
+cdef void dptcon(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) noexcept nogil:
+    
+    _fortran_dptcon(n, d, e, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpteqr "BLAS_FUNC(dpteqr)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dpteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptsv "BLAS_FUNC(dptsv)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) nogil
+cdef void dptsv(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpttrf "BLAS_FUNC(dpttrf)"(int *n, d *d, d *e, int *info) nogil
+cdef void dpttrf(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpttrs "BLAS_FUNC(dpttrs)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) nogil
+cdef void dpttrs(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpttrs(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptts2 "BLAS_FUNC(dptts2)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) nogil
+cdef void dptts2(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dptts2(n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_drscl "BLAS_FUNC(drscl)"(int *n, d *sa, d *sx, int *incx) nogil
+cdef void drscl(int *n, d *sa, d *sx, int *incx) noexcept nogil:
+    
+    _fortran_drscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbev "BLAS_FUNC(dsbev)"(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) 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:
+    
+    _fortran_dsbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbevd "BLAS_FUNC(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) 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:
+    
+    _fortran_dsbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbevx "BLAS_FUNC(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) 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:
+    
+    _fortran_dsbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgst "BLAS_FUNC(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) 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:
+    
+    _fortran_dsbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgv "BLAS_FUNC(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) 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:
+    
+    _fortran_dsbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgvd "BLAS_FUNC(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) 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:
+    
+    _fortran_dsbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dsbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbtrd "BLAS_FUNC(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) 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:
+    
+    _fortran_dsbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsfrk "BLAS_FUNC(dsfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) 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:
+    
+    _fortran_dsfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsgesv "BLAS_FUNC(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) 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:
+    
+    _fortran_dsgesv(n, nrhs, a, lda, ipiv, b, ldb, x, ldx, work, swork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspcon "BLAS_FUNC(dspcon)"(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dspcon(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspev "BLAS_FUNC(dspev)"(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dspev(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dspev(jobz, uplo, n, ap, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspevd "BLAS_FUNC(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) 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:
+    
+    _fortran_dspevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspevx "BLAS_FUNC(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) 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:
+    
+    _fortran_dspevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgst "BLAS_FUNC(dspgst)"(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) nogil
+cdef void dspgst(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) noexcept nogil:
+    
+    _fortran_dspgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgv "BLAS_FUNC(dspgv)"(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) 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:
+    
+    _fortran_dspgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgvd "BLAS_FUNC(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) 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:
+    
+    _fortran_dspgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dspgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsposv "BLAS_FUNC(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) 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:
+    
+    _fortran_dsposv(uplo, n, nrhs, a, lda, b, ldb, x, ldx, work, swork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsprfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspsv "BLAS_FUNC(dspsv)"(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dspsv(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrd "BLAS_FUNC(dsptrd)"(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) nogil
+cdef void dsptrd(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dsptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrf "BLAS_FUNC(dsptrf)"(char *uplo, int *n, d *ap, int *ipiv, int *info) nogil
+cdef void dsptrf(char *uplo, int *n, d *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dsptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptri "BLAS_FUNC(dsptri)"(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) nogil
+cdef void dsptri(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrs "BLAS_FUNC(dsptrs)"(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dsptrs(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstebz "BLAS_FUNC(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) 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:
+    
+    _fortran_dstebz(range, order, n, vl, vu, il, iu, abstol, d, e, m, nsplit, w, iblock, isplit, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstedc "BLAS_FUNC(dstedc)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_dstedc(compz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstegr "BLAS_FUNC(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) 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:
+    
+    _fortran_dstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstein "BLAS_FUNC(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) 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:
+    
+    _fortran_dstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstemr "BLAS_FUNC(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) 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:
+    
+    _fortran_dstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsteqr "BLAS_FUNC(dsteqr)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dsteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsterf "BLAS_FUNC(dsterf)"(int *n, d *d, d *e, int *info) nogil
+cdef void dsterf(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dsterf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstev "BLAS_FUNC(dstev)"(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dstev(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dstev(jobz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevd "BLAS_FUNC(dstevd)"(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_dstevd(jobz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevr "BLAS_FUNC(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) 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:
+    
+    _fortran_dstevr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevx "BLAS_FUNC(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) 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:
+    
+    _fortran_dstevx(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsycon "BLAS_FUNC(dsycon)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) 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:
+    
+    _fortran_dsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyconv "BLAS_FUNC(dsyconv)"(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) nogil
+cdef void dsyconv(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyequb "BLAS_FUNC(dsyequb)"(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) nogil
+cdef void dsyequb(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyev "BLAS_FUNC(dsyev)"(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) nogil
+cdef void dsyev(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsyev(jobz, uplo, n, a, lda, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevd "BLAS_FUNC(dsyevd)"(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_dsyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevr "BLAS_FUNC(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) 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:
+    
+    _fortran_dsyevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevx "BLAS_FUNC(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) 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:
+    
+    _fortran_dsyevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygs2 "BLAS_FUNC(dsygs2)"(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dsygs2(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsygs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygst "BLAS_FUNC(dsygst)"(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dsygst(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsygst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygv "BLAS_FUNC(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) 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:
+    
+    _fortran_dsygv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygvd "BLAS_FUNC(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) 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:
+    
+    _fortran_dsygvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dsygvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsysv "BLAS_FUNC(dsysv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) 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:
+    
+    _fortran_dsysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsysvx "BLAS_FUNC(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) 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:
+    
+    _fortran_dsysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyswapr "BLAS_FUNC(dsyswapr)"(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) nogil
+cdef void dsyswapr(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_dsyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytd2 "BLAS_FUNC(dsytd2)"(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) nogil
+cdef void dsytd2(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dsytd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytf2 "BLAS_FUNC(dsytf2)"(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dsytf2(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dsytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrd "BLAS_FUNC(dsytrd)"(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) 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:
+    
+    _fortran_dsytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrf "BLAS_FUNC(dsytrf)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dsytrf(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri "BLAS_FUNC(dsytri)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) nogil
+cdef void dsytri(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri2 "BLAS_FUNC(dsytri2)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dsytri2(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri2x "BLAS_FUNC(dsytri2x)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) nogil
+cdef void dsytri2x(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_dsytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrs "BLAS_FUNC(dsytrs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dsytrs(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrs2 "BLAS_FUNC(dsytrs2)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) 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:
+    
+    _fortran_dsytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbcon "BLAS_FUNC(dtbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) 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:
+    
+    _fortran_dtbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dtbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbtrs "BLAS_FUNC(dtbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) 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:
+    
+    _fortran_dtbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfsm "BLAS_FUNC(dtfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) 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:
+    
+    _fortran_dtfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtftri "BLAS_FUNC(dtftri)"(char *transr, char *uplo, char *diag, int *n, d *a, int *info) nogil
+cdef void dtftri(char *transr, char *uplo, char *diag, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dtftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfttp "BLAS_FUNC(dtfttp)"(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) nogil
+cdef void dtfttp(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfttr "BLAS_FUNC(dtfttr)"(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) nogil
+cdef void dtfttr(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgevc "BLAS_FUNC(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) 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:
+    
+    _fortran_dtgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgex2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dtgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, n1, n2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgexc "BLAS_FUNC(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) 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:
+    
+    _fortran_dtgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsen "BLAS_FUNC(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) 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:
+    
+    _fortran_dtgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsja "BLAS_FUNC(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) 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:
+    
+    _fortran_dtgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsna "BLAS_FUNC(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) 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:
+    
+    _fortran_dtgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsy2 "BLAS_FUNC(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) 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:
+    
+    _fortran_dtgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, iwork, pq, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsyl "BLAS_FUNC(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) 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:
+    
+    _fortran_dtgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpcon "BLAS_FUNC(dtpcon)"(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dtpcon(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpmqrt "BLAS_FUNC(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) 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:
+    
+    _fortran_dtpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpqrt "BLAS_FUNC(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) 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:
+    
+    _fortran_dtpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpqrt2 "BLAS_FUNC(dtpqrt2)"(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) 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:
+    
+    _fortran_dtpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtprfb "BLAS_FUNC(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) 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:
+    
+    _fortran_dtprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtprfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dtprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtptri "BLAS_FUNC(dtptri)"(char *uplo, char *diag, int *n, d *ap, int *info) nogil
+cdef void dtptri(char *uplo, char *diag, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtptrs "BLAS_FUNC(dtptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dtptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dtptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpttf "BLAS_FUNC(dtpttf)"(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) nogil
+cdef void dtpttf(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) noexcept nogil:
+    
+    _fortran_dtpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpttr "BLAS_FUNC(dtpttr)"(char *uplo, int *n, d *ap, d *a, int *lda, int *info) nogil
+cdef void dtpttr(char *uplo, int *n, d *ap, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrcon "BLAS_FUNC(dtrcon)"(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) 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:
+    
+    _fortran_dtrcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrevc "BLAS_FUNC(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) 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:
+    
+    _fortran_dtrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrexc "BLAS_FUNC(dtrexc)"(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) 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:
+    
+    _fortran_dtrexc(compq, n, t, ldt, q, ldq, ifst, ilst, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_dtrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsen "BLAS_FUNC(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) 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:
+    
+    _fortran_dtrsen(job, compq, select, n, t, ldt, q, ldq, wr, wi, m, s, sep, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsna "BLAS_FUNC(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) 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:
+    
+    _fortran_dtrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsyl "BLAS_FUNC(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) 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:
+    
+    _fortran_dtrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrti2 "BLAS_FUNC(dtrti2)"(char *uplo, char *diag, int *n, d *a, int *lda, int *info) nogil
+cdef void dtrti2(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrtri "BLAS_FUNC(dtrtri)"(char *uplo, char *diag, int *n, d *a, int *lda, int *info) nogil
+cdef void dtrtri(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrtrs "BLAS_FUNC(dtrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) 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:
+    
+    _fortran_dtrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrttf "BLAS_FUNC(dtrttf)"(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) nogil
+cdef void dtrttf(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) noexcept nogil:
+    
+    _fortran_dtrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrttp "BLAS_FUNC(dtrttp)"(char *uplo, int *n, d *a, int *lda, d *ap, int *info) nogil
+cdef void dtrttp(char *uplo, int *n, d *a, int *lda, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtzrzf "BLAS_FUNC(dtzrzf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dtzrzf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dtzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dzsum1 "BLAS_FUNC(dzsum1)"(int *n, npy_complex128 *cx, int *incx) nogil
+cdef d dzsum1(int *n, z *cx, int *incx) noexcept nogil:
+    
+    return _fortran_dzsum1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_icmax1 "BLAS_FUNC(icmax1)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef int icmax1(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_icmax1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ieeeck "BLAS_FUNC(ieeeck)"(int *ispec, s *zero, s *one) nogil
+cdef int ieeeck(int *ispec, s *zero, s *one) noexcept nogil:
+    
+    return _fortran_ieeeck(ispec, zero, one)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaclc "BLAS_FUNC(ilaclc)"(int *m, int *n, npy_complex64 *a, int *lda) nogil
+cdef int ilaclc(int *m, int *n, c *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaclc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaclr "BLAS_FUNC(ilaclr)"(int *m, int *n, npy_complex64 *a, int *lda) nogil
+cdef int ilaclr(int *m, int *n, c *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaclr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladiag "BLAS_FUNC(iladiag)"(char *diag) nogil
+cdef int iladiag(char *diag) noexcept nogil:
+    
+    return _fortran_iladiag(diag)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladlc "BLAS_FUNC(iladlc)"(int *m, int *n, d *a, int *lda) nogil
+cdef int iladlc(int *m, int *n, d *a, int *lda) noexcept nogil:
+    
+    return _fortran_iladlc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladlr "BLAS_FUNC(iladlr)"(int *m, int *n, d *a, int *lda) nogil
+cdef int iladlr(int *m, int *n, d *a, int *lda) noexcept nogil:
+    
+    return _fortran_iladlr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaprec "BLAS_FUNC(ilaprec)"(char *prec) nogil
+cdef int ilaprec(char *prec) noexcept nogil:
+    
+    return _fortran_ilaprec(prec)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaslc "BLAS_FUNC(ilaslc)"(int *m, int *n, s *a, int *lda) nogil
+cdef int ilaslc(int *m, int *n, s *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaslc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaslr "BLAS_FUNC(ilaslr)"(int *m, int *n, s *a, int *lda) nogil
+cdef int ilaslr(int *m, int *n, s *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaslr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilatrans "BLAS_FUNC(ilatrans)"(char *trans) nogil
+cdef int ilatrans(char *trans) noexcept nogil:
+    
+    return _fortran_ilatrans(trans)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilauplo "BLAS_FUNC(ilauplo)"(char *uplo) nogil
+cdef int ilauplo(char *uplo) noexcept nogil:
+    
+    return _fortran_ilauplo(uplo)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ilaver "BLAS_FUNC(ilaver)"(int *vers_major, int *vers_minor, int *vers_patch) nogil
+cdef void ilaver(int *vers_major, int *vers_minor, int *vers_patch) noexcept nogil:
+    
+    _fortran_ilaver(vers_major, vers_minor, vers_patch)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilazlc "BLAS_FUNC(ilazlc)"(int *m, int *n, npy_complex128 *a, int *lda) nogil
+cdef int ilazlc(int *m, int *n, z *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilazlc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilazlr "BLAS_FUNC(ilazlr)"(int *m, int *n, npy_complex128 *a, int *lda) nogil
+cdef int ilazlr(int *m, int *n, z *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilazlr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_izmax1 "BLAS_FUNC(izmax1)"(int *n, npy_complex128 *cx, int *incx) nogil
+cdef int izmax1(int *n, z *cx, int *incx) noexcept nogil:
+    
+    return _fortran_izmax1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbbcsd "BLAS_FUNC(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) 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:
+    
+    _fortran_sbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbdsdc "BLAS_FUNC(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) 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:
+    
+    _fortran_sbdsdc(uplo, compq, n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbdsqr "BLAS_FUNC(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) 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:
+    
+    _fortran_sbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_scsum1 "BLAS_FUNC(scsum1)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef s scsum1(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_scsum1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sdisna "BLAS_FUNC(sdisna)"(char *job, int *m, int *n, s *d, s *sep, int *info) nogil
+cdef void sdisna(char *job, int *m, int *n, s *d, s *sep, int *info) noexcept nogil:
+    
+    _fortran_sdisna(job, m, n, d, sep, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbbrd "BLAS_FUNC(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) 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:
+    
+    _fortran_sgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbcon "BLAS_FUNC(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) 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:
+    
+    _fortran_sgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbequ "BLAS_FUNC(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) 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:
+    
+    _fortran_sgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbequb "BLAS_FUNC(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) 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:
+    
+    _fortran_sgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_sgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbsv "BLAS_FUNC(sgbsv)"(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) 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:
+    
+    _fortran_sgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_sgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtf2 "BLAS_FUNC(sgbtf2)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void sgbtf2(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtrf "BLAS_FUNC(sgbtrf)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void sgbtrf(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtrs "BLAS_FUNC(sgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) 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:
+    
+    _fortran_sgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebak "BLAS_FUNC(sgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) 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:
+    
+    _fortran_sgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebal "BLAS_FUNC(sgebal)"(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) nogil
+cdef void sgebal(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil:
+    
+    _fortran_sgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebd2 "BLAS_FUNC(sgebd2)"(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) 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:
+    
+    _fortran_sgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebrd "BLAS_FUNC(sgebrd)"(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) 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:
+    
+    _fortran_sgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgecon "BLAS_FUNC(sgecon)"(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sgecon(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgecon(norm, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeequ "BLAS_FUNC(sgeequ)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) 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:
+    
+    _fortran_sgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeequb "BLAS_FUNC(sgeequb)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) 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:
+    
+    _fortran_sgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgees "BLAS_FUNC(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) 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:
+    
+    _fortran_sgees(jobvs, sort, <_sselect2*>select, n, a, lda, sdim, wr, wi, vs, ldvs, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeesx "BLAS_FUNC(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) 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:
+    
+    _fortran_sgeesx(jobvs, sort, <_sselect2*>select, sense, n, a, lda, sdim, wr, wi, vs, ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeev "BLAS_FUNC(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) 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:
+    
+    _fortran_sgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeevx "BLAS_FUNC(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) 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:
+    
+    _fortran_sgeevx(balanc, jobvl, jobvr, sense, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgehd2 "BLAS_FUNC(sgehd2)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgehd2(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgehrd "BLAS_FUNC(sgehrd)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgehrd(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgejsv "BLAS_FUNC(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) 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:
+    
+    _fortran_sgejsv(joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelq2 "BLAS_FUNC(sgelq2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgelq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelqf "BLAS_FUNC(sgelqf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgelqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgels "BLAS_FUNC(sgels)"(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) 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:
+    
+    _fortran_sgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelsd "BLAS_FUNC(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) 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:
+    
+    _fortran_sgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelss "BLAS_FUNC(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) 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:
+    
+    _fortran_sgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelsy "BLAS_FUNC(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) 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:
+    
+    _fortran_sgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgemqrt "BLAS_FUNC(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) 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:
+    
+    _fortran_sgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeql2 "BLAS_FUNC(sgeql2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeql2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqlf "BLAS_FUNC(sgeqlf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqlf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqp3 "BLAS_FUNC(sgeqp3)"(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqp3(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqr2 "BLAS_FUNC(sgeqr2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeqr2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqr2p "BLAS_FUNC(sgeqr2p)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeqr2p(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrf "BLAS_FUNC(sgeqrf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqrf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrfp "BLAS_FUNC(sgeqrfp)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqrfp(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt "BLAS_FUNC(sgeqrt)"(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) nogil
+cdef void sgeqrt(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt2 "BLAS_FUNC(sgeqrt2)"(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) nogil
+cdef void sgeqrt2(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt3 "BLAS_FUNC(sgeqrt3)"(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) nogil
+cdef void sgeqrt3(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerfs "BLAS_FUNC(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) 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:
+    
+    _fortran_sgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerq2 "BLAS_FUNC(sgerq2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgerq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerqf "BLAS_FUNC(sgerqf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgerqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesc2 "BLAS_FUNC(sgesc2)"(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) nogil
+cdef void sgesc2(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil:
+    
+    _fortran_sgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesdd "BLAS_FUNC(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) 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:
+    
+    _fortran_sgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesv "BLAS_FUNC(sgesv)"(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgesv(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvd "BLAS_FUNC(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) 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:
+    
+    _fortran_sgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvj "BLAS_FUNC(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) 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:
+    
+    _fortran_sgesvj(joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvx "BLAS_FUNC(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) 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:
+    
+    _fortran_sgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetc2 "BLAS_FUNC(sgetc2)"(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void sgetc2(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_sgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetf2 "BLAS_FUNC(sgetf2)"(int *m, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void sgetf2(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetrf "BLAS_FUNC(sgetrf)"(int *m, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void sgetrf(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetri "BLAS_FUNC(sgetri)"(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void sgetri(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetrs "BLAS_FUNC(sgetrs)"(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgetrs(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggbak "BLAS_FUNC(sggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) 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:
+    
+    _fortran_sggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggbal "BLAS_FUNC(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) 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:
+    
+    _fortran_sggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgges "BLAS_FUNC(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) 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:
+    
+    _fortran_sgges(jobvsl, jobvsr, sort, <_sselect3*>selctg, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggesx "BLAS_FUNC(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) 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:
+    
+    _fortran_sggesx(jobvsl, jobvsr, sort, <_sselect3*>selctg, sense, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggev "BLAS_FUNC(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) 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:
+    
+    _fortran_sggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggevx "BLAS_FUNC(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) 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:
+    
+    _fortran_sggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggglm "BLAS_FUNC(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) 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:
+    
+    _fortran_sggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgghrd "BLAS_FUNC(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) 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:
+    
+    _fortran_sgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgglse "BLAS_FUNC(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) 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:
+    
+    _fortran_sgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggqrf "BLAS_FUNC(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) 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:
+    
+    _fortran_sggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggrqf "BLAS_FUNC(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) 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:
+    
+    _fortran_sggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgsvj0 "BLAS_FUNC(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) 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:
+    
+    _fortran_sgsvj0(jobv, m, n, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgsvj1 "BLAS_FUNC(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) 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:
+    
+    _fortran_sgsvj1(jobv, m, n, n1, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtcon "BLAS_FUNC(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) 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:
+    
+    _fortran_sgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_sgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtsv "BLAS_FUNC(sgtsv)"(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) nogil
+cdef void sgtsv(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_sgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgttrf "BLAS_FUNC(sgttrf)"(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) nogil
+cdef void sgttrf(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgttrs "BLAS_FUNC(sgttrs)"(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) 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:
+    
+    _fortran_sgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtts2 "BLAS_FUNC(sgtts2)"(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) 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:
+    
+    _fortran_sgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shgeqz "BLAS_FUNC(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) 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:
+    
+    _fortran_shgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alphar, alphai, beta, q, ldq, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shsein "BLAS_FUNC(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) 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:
+    
+    _fortran_shsein(side, eigsrc, initv, select, n, h, ldh, wr, wi, vl, ldvl, vr, ldvr, mm, m, work, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shseqr "BLAS_FUNC(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) 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:
+    
+    _fortran_shseqr(job, compz, n, ilo, ihi, h, ldh, wr, wi, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slabad "BLAS_FUNC(slabad)"(s *small, s *large) nogil
+cdef void slabad(s *small, s *large) noexcept nogil:
+    
+    _fortran_slabad(small, large)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slabrd "BLAS_FUNC(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) 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:
+    
+    _fortran_slabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacn2 "BLAS_FUNC(slacn2)"(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) nogil
+cdef void slacn2(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_slacn2(n, v, x, isgn, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacon "BLAS_FUNC(slacon)"(int *n, s *v, s *x, int *isgn, s *est, int *kase) nogil
+cdef void slacon(int *n, s *v, s *x, int *isgn, s *est, int *kase) noexcept nogil:
+    
+    _fortran_slacon(n, v, x, isgn, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacpy "BLAS_FUNC(slacpy)"(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) nogil
+cdef void slacpy(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_slacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sladiv "BLAS_FUNC(sladiv)"(s *a, s *b, s *c, s *d, s *p, s *q) nogil
+cdef void sladiv(s *a, s *b, s *c, s *d, s *p, s *q) noexcept nogil:
+    
+    _fortran_sladiv(a, b, c, d, p, q)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slae2 "BLAS_FUNC(slae2)"(s *a, s *b, s *c, s *rt1, s *rt2) nogil
+cdef void slae2(s *a, s *b, s *c, s *rt1, s *rt2) noexcept nogil:
+    
+    _fortran_slae2(a, b, c, rt1, rt2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaebz "BLAS_FUNC(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) 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:
+    
+    _fortran_slaebz(ijob, nitmax, n, mmax, minp, nbmin, abstol, reltol, pivmin, d, e, e2, nval, ab, c, mout, nab, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed0 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaed0(icompq, qsiz, n, d, e, q, ldq, qstore, ldqs, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed1 "BLAS_FUNC(slaed1)"(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) 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:
+    
+    _fortran_slaed1(n, d, q, ldq, indxq, rho, cutpnt, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed2 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaed2(k, n, n1, d, q, ldq, indxq, rho, z, dlamda, w, q2, indx, indxc, indxp, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed3 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaed3(k, n, n1, d, q, ldq, rho, dlamda, q2, indx, ctot, w, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed4 "BLAS_FUNC(slaed4)"(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) nogil
+cdef void slaed4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) noexcept nogil:
+    
+    _fortran_slaed4(n, i, d, z, delta, rho, dlam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed5 "BLAS_FUNC(slaed5)"(int *i, s *d, s *z, s *delta, s *rho, s *dlam) nogil
+cdef void slaed5(int *i, s *d, s *z, s *delta, s *rho, s *dlam) noexcept nogil:
+    
+    _fortran_slaed5(i, d, z, delta, rho, dlam)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed6 "BLAS_FUNC(slaed6)"(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) nogil
+cdef void slaed6(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) noexcept nogil:
+    
+    _fortran_slaed6(kniter, orgati, rho, d, z, finit, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed7 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaed7(icompq, n, qsiz, tlvls, curlvl, curpbm, d, q, ldq, indxq, rho, cutpnt, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed8 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaed8(icompq, k, n, qsiz, d, q, ldq, indxq, rho, cutpnt, z, dlamda, q2, ldq2, w, perm, givptr, givcol, givnum, indxp, indx, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed9 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaed9(k, kstart, kstop, n, d, q, ldq, rho, dlamda, w, s, lds, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaeda "BLAS_FUNC(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) 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:
+    
+    _fortran_slaeda(n, tlvls, curlvl, curpbm, prmptr, perm, givptr, givcol, givnum, q, qptr, z, ztemp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaein "BLAS_FUNC(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) 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:
+    
+    _fortran_slaein(rightv, noinit, n, h, ldh, wr, wi, vr, vi, b, ldb, work, eps3, smlnum, bignum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaev2 "BLAS_FUNC(slaev2)"(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) nogil
+cdef void slaev2(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) noexcept nogil:
+    
+    _fortran_slaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaexc "BLAS_FUNC(slaexc)"(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) 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:
+    
+    _fortran_slaexc(wantq, n, t, ldt, q, ldq, j1, n1, n2, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slag2 "BLAS_FUNC(slag2)"(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) 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:
+    
+    _fortran_slag2(a, lda, b, ldb, safmin, scale1, scale2, wr1, wr2, wi)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slag2d "BLAS_FUNC(slag2d)"(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) nogil
+cdef void slag2d(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slag2d(m, n, sa, ldsa, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slags2 "BLAS_FUNC(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) 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:
+    
+    _fortran_slags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagtf "BLAS_FUNC(slagtf)"(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) nogil
+cdef void slagtf(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) noexcept nogil:
+    
+    _fortran_slagtf(n, a, lambda_, b, c, tol, d, in_, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagtm "BLAS_FUNC(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) 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:
+    
+    _fortran_slagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagts "BLAS_FUNC(slagts)"(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) 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:
+    
+    _fortran_slagts(job, n, a, b, c, d, in_, y, tol, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagv2 "BLAS_FUNC(slagv2)"(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) 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:
+    
+    _fortran_slagv2(a, lda, b, ldb, alphar, alphai, beta, csl, snl, csr, snr)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slahqr "BLAS_FUNC(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) 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:
+    
+    _fortran_slahqr(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slahr2 "BLAS_FUNC(slahr2)"(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) 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:
+    
+    _fortran_slahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaic1 "BLAS_FUNC(slaic1)"(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) nogil
+cdef void slaic1(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) noexcept nogil:
+    
+    _fortran_slaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaln2 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaln2(ltrans, na, nw, smin, ca, a, lda, d1, d2, b, ldb, wr, wi, x, ldx, scale, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slals0 "BLAS_FUNC(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) 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:
+    
+    _fortran_slals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slalsa "BLAS_FUNC(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) 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:
+    
+    _fortran_slalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slalsd "BLAS_FUNC(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) 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:
+    
+    _fortran_slalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slamch "BLAS_FUNC(slamch)"(char *cmach) nogil
+cdef s slamch(char *cmach) noexcept nogil:
+    
+    return _fortran_slamch(cmach)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slamrg "BLAS_FUNC(slamrg)"(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) nogil
+cdef void slamrg(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) noexcept nogil:
+    
+    _fortran_slamrg(n1, n2, a, strd1, strd2, index_bn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slangb "BLAS_FUNC(slangb)"(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) nogil
+cdef s slangb(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slange "BLAS_FUNC(slange)"(char *norm, int *m, int *n, s *a, int *lda, s *work) nogil
+cdef s slange(char *norm, int *m, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slangt "BLAS_FUNC(slangt)"(char *norm, int *n, s *dl, s *d, s *du) nogil
+cdef s slangt(char *norm, int *n, s *dl, s *d, s *du) noexcept nogil:
+    
+    return _fortran_slangt(norm, n, dl, d, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slanhs "BLAS_FUNC(slanhs)"(char *norm, int *n, s *a, int *lda, s *work) nogil
+cdef s slanhs(char *norm, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansb "BLAS_FUNC(slansb)"(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) nogil
+cdef s slansb(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansf "BLAS_FUNC(slansf)"(char *norm, char *transr, char *uplo, int *n, s *a, s *work) nogil
+cdef s slansf(char *norm, char *transr, char *uplo, int *n, s *a, s *work) noexcept nogil:
+    
+    return _fortran_slansf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansp "BLAS_FUNC(slansp)"(char *norm, char *uplo, int *n, s *ap, s *work) nogil
+cdef s slansp(char *norm, char *uplo, int *n, s *ap, s *work) noexcept nogil:
+    
+    return _fortran_slansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slanst "BLAS_FUNC(slanst)"(char *norm, int *n, s *d, s *e) nogil
+cdef s slanst(char *norm, int *n, s *d, s *e) noexcept nogil:
+    
+    return _fortran_slanst(norm, n, d, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansy "BLAS_FUNC(slansy)"(char *norm, char *uplo, int *n, s *a, int *lda, s *work) nogil
+cdef s slansy(char *norm, char *uplo, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantb "BLAS_FUNC(slantb)"(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) nogil
+cdef s slantb(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantp "BLAS_FUNC(slantp)"(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) nogil
+cdef s slantp(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) noexcept nogil:
+    
+    return _fortran_slantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantr "BLAS_FUNC(slantr)"(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) nogil
+cdef s slantr(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slanv2 "BLAS_FUNC(slanv2)"(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) 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:
+    
+    _fortran_slanv2(a, b, c, d, rt1r, rt1i, rt2r, rt2i, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapll "BLAS_FUNC(slapll)"(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) nogil
+cdef void slapll(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) noexcept nogil:
+    
+    _fortran_slapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapmr "BLAS_FUNC(slapmr)"(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) nogil
+cdef void slapmr(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_slapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapmt "BLAS_FUNC(slapmt)"(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) nogil
+cdef void slapmt(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_slapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slapy2 "BLAS_FUNC(slapy2)"(s *x, s *y) nogil
+cdef s slapy2(s *x, s *y) noexcept nogil:
+    
+    return _fortran_slapy2(x, y)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slapy3 "BLAS_FUNC(slapy3)"(s *x, s *y, s *z) nogil
+cdef s slapy3(s *x, s *y, s *z) noexcept nogil:
+    
+    return _fortran_slapy3(x, y, z)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqgb "BLAS_FUNC(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) 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:
+    
+    _fortran_slaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqge "BLAS_FUNC(slaqge)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) 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:
+    
+    _fortran_slaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqp2 "BLAS_FUNC(slaqp2)"(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) 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:
+    
+    _fortran_slaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqps "BLAS_FUNC(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) 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:
+    
+    _fortran_slaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr0 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaqr0(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr1 "BLAS_FUNC(slaqr1)"(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) nogil
+cdef void slaqr1(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) noexcept nogil:
+    
+    _fortran_slaqr1(n, h, ldh, sr1, si1, sr2, si2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr2 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr3 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr4 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaqr4(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr5 "BLAS_FUNC(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) 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:
+    
+    _fortran_slaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, sr, si, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsb "BLAS_FUNC(slaqsb)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsb(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsp "BLAS_FUNC(slaqsp)"(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsp(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsy "BLAS_FUNC(slaqsy)"(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsy(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqtr "BLAS_FUNC(slaqtr)"(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) 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:
+    
+    _fortran_slaqtr(ltran, lreal, n, t, ldt, b, w, scale, x, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slar1v "BLAS_FUNC(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) 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:
+    
+    _fortran_slar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slar2v "BLAS_FUNC(slar2v)"(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) nogil
+cdef void slar2v(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) noexcept nogil:
+    
+    _fortran_slar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarf "BLAS_FUNC(slarf)"(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) nogil
+cdef void slarf(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil:
+    
+    _fortran_slarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfb "BLAS_FUNC(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) 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:
+    
+    _fortran_slarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfg "BLAS_FUNC(slarfg)"(int *n, s *alpha, s *x, int *incx, s *tau) nogil
+cdef void slarfg(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil:
+    
+    _fortran_slarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfgp "BLAS_FUNC(slarfgp)"(int *n, s *alpha, s *x, int *incx, s *tau) nogil
+cdef void slarfgp(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil:
+    
+    _fortran_slarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarft "BLAS_FUNC(slarft)"(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) nogil
+cdef void slarft(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil:
+    
+    _fortran_slarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfx "BLAS_FUNC(slarfx)"(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) nogil
+cdef void slarfx(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) noexcept nogil:
+    
+    _fortran_slarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slargv "BLAS_FUNC(slargv)"(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) nogil
+cdef void slargv(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) noexcept nogil:
+    
+    _fortran_slargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarnv "BLAS_FUNC(slarnv)"(int *idist, int *iseed, int *n, s *x) nogil
+cdef void slarnv(int *idist, int *iseed, int *n, s *x) noexcept nogil:
+    
+    _fortran_slarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarra "BLAS_FUNC(slarra)"(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) nogil
+cdef void slarra(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil:
+    
+    _fortran_slarra(n, d, e, e2, spltol, tnrm, nsplit, isplit, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrb "BLAS_FUNC(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) 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:
+    
+    _fortran_slarrb(n, d, lld, ifirst, ilast, rtol1, rtol2, offset, w, wgap, werr, work, iwork, pivmin, spdiam, twist, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrc "BLAS_FUNC(slarrc)"(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) 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:
+    
+    _fortran_slarrc(jobt, n, vl, vu, d, e, pivmin, eigcnt, lcnt, rcnt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrd "BLAS_FUNC(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) 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:
+    
+    _fortran_slarrd(range, order, n, vl, vu, il, iu, gers, reltol, d, e, e2, pivmin, nsplit, isplit, m, w, werr, wl, wu, iblock, indexw, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarre "BLAS_FUNC(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) 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:
+    
+    _fortran_slarre(range, n, vl, vu, il, iu, d, e, e2, rtol1, rtol2, spltol, nsplit, isplit, m, w, werr, wgap, iblock, indexw, gers, pivmin, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrf "BLAS_FUNC(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) 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:
+    
+    _fortran_slarrf(n, d, l, ld, clstrt, clend, w, wgap, werr, spdiam, clgapl, clgapr, pivmin, sigma, dplus, lplus, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrj "BLAS_FUNC(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) 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:
+    
+    _fortran_slarrj(n, d, e2, ifirst, ilast, rtol, offset, w, werr, work, iwork, pivmin, spdiam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrk "BLAS_FUNC(slarrk)"(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) 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:
+    
+    _fortran_slarrk(n, iw, gl, gu, d, e2, pivmin, reltol, w, werr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrr "BLAS_FUNC(slarrr)"(int *n, s *d, s *e, int *info) nogil
+cdef void slarrr(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_slarrr(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrv "BLAS_FUNC(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) 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:
+    
+    _fortran_slarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartg "BLAS_FUNC(slartg)"(s *f, s *g, s *cs, s *sn, s *r) nogil
+cdef void slartg(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil:
+    
+    _fortran_slartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartgp "BLAS_FUNC(slartgp)"(s *f, s *g, s *cs, s *sn, s *r) nogil
+cdef void slartgp(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil:
+    
+    _fortran_slartgp(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartgs "BLAS_FUNC(slartgs)"(s *x, s *y, s *sigma, s *cs, s *sn) nogil
+cdef void slartgs(s *x, s *y, s *sigma, s *cs, s *sn) noexcept nogil:
+    
+    _fortran_slartgs(x, y, sigma, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartv "BLAS_FUNC(slartv)"(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) nogil
+cdef void slartv(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) noexcept nogil:
+    
+    _fortran_slartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaruv "BLAS_FUNC(slaruv)"(int *iseed, int *n, s *x) nogil
+cdef void slaruv(int *iseed, int *n, s *x) noexcept nogil:
+    
+    _fortran_slaruv(iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarz "BLAS_FUNC(slarz)"(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) 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:
+    
+    _fortran_slarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarzb "BLAS_FUNC(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) 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:
+    
+    _fortran_slarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarzt "BLAS_FUNC(slarzt)"(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) nogil
+cdef void slarzt(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil:
+    
+    _fortran_slarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slas2 "BLAS_FUNC(slas2)"(s *f, s *g, s *h, s *ssmin, s *ssmax) nogil
+cdef void slas2(s *f, s *g, s *h, s *ssmin, s *ssmax) noexcept nogil:
+    
+    _fortran_slas2(f, g, h, ssmin, ssmax)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slascl "BLAS_FUNC(slascl)"(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) 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:
+    
+    _fortran_slascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd0 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasd0(n, sqre, d, e, u, ldu, vt, ldvt, smlsiz, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd1 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasd1(nl, nr, sqre, d, alpha, beta, u, ldu, vt, ldvt, idxq, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd2 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasd2(nl, nr, sqre, k, d, z, alpha, beta, u, ldu, vt, ldvt, dsigma, u2, ldu2, vt2, ldvt2, idxp, idx, idxc, idxq, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd3 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasd3(nl, nr, sqre, k, d, q, ldq, dsigma, u, ldu, u2, ldu2, vt, ldvt, vt2, ldvt2, idxc, ctot, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd4 "BLAS_FUNC(slasd4)"(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) nogil
+cdef void slasd4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd4(n, i, d, z, delta, rho, sigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd5 "BLAS_FUNC(slasd5)"(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) nogil
+cdef void slasd5(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) noexcept nogil:
+    
+    _fortran_slasd5(i, d, z, delta, rho, dsigma, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd6 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasd6(icompq, nl, nr, sqre, d, vf, vl, alpha, beta, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd7 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasd7(icompq, nl, nr, sqre, k, d, z, zw, vf, vfw, vl, vlw, alpha, beta, dsigma, idx, idxp, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, c, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd8 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasd8(icompq, k, d, z, vf, vl, difl, difr, lddifr, dsigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasda "BLAS_FUNC(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) 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:
+    
+    _fortran_slasda(icompq, smlsiz, n, sqre, d, e, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasdq "BLAS_FUNC(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) 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:
+    
+    _fortran_slasdq(uplo, sqre, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasdt "BLAS_FUNC(slasdt)"(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) nogil
+cdef void slasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil:
+    
+    _fortran_slasdt(n, lvl, nd, inode, ndiml, ndimr, msub)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaset "BLAS_FUNC(slaset)"(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) nogil
+cdef void slaset(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) noexcept nogil:
+    
+    _fortran_slaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq1 "BLAS_FUNC(slasq1)"(int *n, s *d, s *e, s *work, int *info) nogil
+cdef void slasq1(int *n, s *d, s *e, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasq1(n, d, e, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq2 "BLAS_FUNC(slasq2)"(int *n, s *z, int *info) nogil
+cdef void slasq2(int *n, s *z, int *info) noexcept nogil:
+    
+    _fortran_slasq2(n, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq3 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasq3(i0, n0, z, pp, dmin, sigma, desig, qmax, nfail, iter, ndiv, ieee, ttype, dmin1, dmin2, dn, dn1, dn2, g, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq4 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasq4(i0, n0, z, pp, n0in, dmin, dmin1, dmin2, dn, dn1, dn2, tau, ttype, g)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq6 "BLAS_FUNC(slasq6)"(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) 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:
+    
+    _fortran_slasq6(i0, n0, z, pp, dmin, dmin1, dmin2, dn, dnm1, dnm2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasr "BLAS_FUNC(slasr)"(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) nogil
+cdef void slasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) noexcept nogil:
+    
+    _fortran_slasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasrt "BLAS_FUNC(slasrt)"(char *id, int *n, s *d, int *info) nogil
+cdef void slasrt(char *id, int *n, s *d, int *info) noexcept nogil:
+    
+    _fortran_slasrt(id, n, d, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slassq "BLAS_FUNC(slassq)"(int *n, s *x, int *incx, s *scale, s *sumsq) nogil
+cdef void slassq(int *n, s *x, int *incx, s *scale, s *sumsq) noexcept nogil:
+    
+    _fortran_slassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasv2 "BLAS_FUNC(slasv2)"(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) nogil
+cdef void slasv2(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) noexcept nogil:
+    
+    _fortran_slasv2(f, g, h, ssmin, ssmax, snr, csr, snl, csl)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaswp "BLAS_FUNC(slaswp)"(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void slaswp(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_slaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasy2 "BLAS_FUNC(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) 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:
+    
+    _fortran_slasy2(ltranl, ltranr, isgn, n1, n2, tl, ldtl, tr, ldtr, b, ldb, scale, x, ldx, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasyf "BLAS_FUNC(slasyf)"(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) 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:
+    
+    _fortran_slasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatbs "BLAS_FUNC(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) 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:
+    
+    _fortran_slatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatdf "BLAS_FUNC(slatdf)"(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) nogil
+cdef void slatdf(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_slatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatps "BLAS_FUNC(slatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) 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:
+    
+    _fortran_slatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrd "BLAS_FUNC(slatrd)"(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) nogil
+cdef void slatrd(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) noexcept nogil:
+    
+    _fortran_slatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrs "BLAS_FUNC(slatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) 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:
+    
+    _fortran_slatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrz "BLAS_FUNC(slatrz)"(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) nogil
+cdef void slatrz(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) noexcept nogil:
+    
+    _fortran_slatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slauu2 "BLAS_FUNC(slauu2)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void slauu2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slauum "BLAS_FUNC(slauum)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void slauum(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sopgtr "BLAS_FUNC(sopgtr)"(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) nogil
+cdef void sopgtr(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) noexcept nogil:
+    
+    _fortran_sopgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sopmtr "BLAS_FUNC(sopmtr)"(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) 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:
+    
+    _fortran_sopmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorbdb "BLAS_FUNC(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) 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:
+    
+    _fortran_sorbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorcsd "BLAS_FUNC(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) 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:
+    
+    _fortran_sorcsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorg2l "BLAS_FUNC(sorg2l)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorg2l(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorg2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorg2r "BLAS_FUNC(sorg2r)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorg2r(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorg2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgbr "BLAS_FUNC(sorgbr)"(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) 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:
+    
+    _fortran_sorgbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorghr "BLAS_FUNC(sorghr)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorghr(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgl2 "BLAS_FUNC(sorgl2)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorgl2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorgl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorglq "BLAS_FUNC(sorglq)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorglq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgql "BLAS_FUNC(sorgql)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgql(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgqr "BLAS_FUNC(sorgqr)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgqr(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgr2 "BLAS_FUNC(sorgr2)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorgr2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorgr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgrq "BLAS_FUNC(sorgrq)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgrq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgtr "BLAS_FUNC(sorgtr)"(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgtr(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorm2l "BLAS_FUNC(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) 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:
+    
+    _fortran_sorm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorm2r "BLAS_FUNC(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) 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:
+    
+    _fortran_sorm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormbr "BLAS_FUNC(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) 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:
+    
+    _fortran_sormbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormhr "BLAS_FUNC(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) 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:
+    
+    _fortran_sormhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorml2 "BLAS_FUNC(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) 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:
+    
+    _fortran_sorml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormlq "BLAS_FUNC(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) 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:
+    
+    _fortran_sormlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormql "BLAS_FUNC(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) 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:
+    
+    _fortran_sormql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormqr "BLAS_FUNC(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) 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:
+    
+    _fortran_sormqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormr2 "BLAS_FUNC(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) 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:
+    
+    _fortran_sormr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormr3 "BLAS_FUNC(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) 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:
+    
+    _fortran_sormr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormrq "BLAS_FUNC(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) 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:
+    
+    _fortran_sormrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormrz "BLAS_FUNC(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) 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:
+    
+    _fortran_sormrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormtr "BLAS_FUNC(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) 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:
+    
+    _fortran_sormtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbcon "BLAS_FUNC(spbcon)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) 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:
+    
+    _fortran_spbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbequ "BLAS_FUNC(spbequ)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) nogil
+cdef void spbequ(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_spbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbstf "BLAS_FUNC(spbstf)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbstf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbsv "BLAS_FUNC(spbsv)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil
+cdef void spbsv(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_spbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtf2 "BLAS_FUNC(spbtf2)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbtf2(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtrf "BLAS_FUNC(spbtrf)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbtrf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtrs "BLAS_FUNC(spbtrs)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil
+cdef void spbtrs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftrf "BLAS_FUNC(spftrf)"(char *transr, char *uplo, int *n, s *a, int *info) nogil
+cdef void spftrf(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_spftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftri "BLAS_FUNC(spftri)"(char *transr, char *uplo, int *n, s *a, int *info) nogil
+cdef void spftri(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_spftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftrs "BLAS_FUNC(spftrs)"(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) nogil
+cdef void spftrs(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spocon "BLAS_FUNC(spocon)"(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void spocon(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spocon(uplo, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spoequ "BLAS_FUNC(spoequ)"(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void spoequ(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spoequb "BLAS_FUNC(spoequb)"(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void spoequb(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sporfs "BLAS_FUNC(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) 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:
+    
+    _fortran_sporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sposv "BLAS_FUNC(sposv)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void sposv(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sposvx "BLAS_FUNC(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) 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:
+    
+    _fortran_sposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotf2 "BLAS_FUNC(spotf2)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotf2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotrf "BLAS_FUNC(spotrf)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotrf(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotri "BLAS_FUNC(spotri)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotri(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotrs "BLAS_FUNC(spotrs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void spotrs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppcon "BLAS_FUNC(sppcon)"(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sppcon(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sppcon(uplo, n, ap, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppequ "BLAS_FUNC(sppequ)"(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) nogil
+cdef void sppequ(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spprfs "BLAS_FUNC(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) 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:
+    
+    _fortran_spprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppsv "BLAS_FUNC(sppsv)"(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void sppsv(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_sppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptrf "BLAS_FUNC(spptrf)"(char *uplo, int *n, s *ap, int *info) nogil
+cdef void spptrf(char *uplo, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_spptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptri "BLAS_FUNC(spptri)"(char *uplo, int *n, s *ap, int *info) nogil
+cdef void spptri(char *uplo, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_spptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptrs "BLAS_FUNC(spptrs)"(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void spptrs(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spstf2 "BLAS_FUNC(spstf2)"(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void spstf2(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_spstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spstrf "BLAS_FUNC(spstrf)"(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void spstrf(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_spstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptcon "BLAS_FUNC(sptcon)"(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) nogil
+cdef void sptcon(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) noexcept nogil:
+    
+    _fortran_sptcon(n, d, e, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spteqr "BLAS_FUNC(spteqr)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void spteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_spteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_sptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptsv "BLAS_FUNC(sptsv)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) nogil
+cdef void sptsv(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_sptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spttrf "BLAS_FUNC(spttrf)"(int *n, s *d, s *e, int *info) nogil
+cdef void spttrf(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_spttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spttrs "BLAS_FUNC(spttrs)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) nogil
+cdef void spttrs(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spttrs(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptts2 "BLAS_FUNC(sptts2)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) nogil
+cdef void sptts2(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_sptts2(n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_srscl "BLAS_FUNC(srscl)"(int *n, s *sa, s *sx, int *incx) nogil
+cdef void srscl(int *n, s *sa, s *sx, int *incx) noexcept nogil:
+    
+    _fortran_srscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbev "BLAS_FUNC(ssbev)"(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) 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:
+    
+    _fortran_ssbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbevd "BLAS_FUNC(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) 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:
+    
+    _fortran_ssbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbevx "BLAS_FUNC(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) 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:
+    
+    _fortran_ssbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgst "BLAS_FUNC(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) 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:
+    
+    _fortran_ssbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgv "BLAS_FUNC(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) 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:
+    
+    _fortran_ssbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgvd "BLAS_FUNC(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) 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:
+    
+    _fortran_ssbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgvx "BLAS_FUNC(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) 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:
+    
+    _fortran_ssbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbtrd "BLAS_FUNC(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) 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:
+    
+    _fortran_ssbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssfrk "BLAS_FUNC(ssfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) 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:
+    
+    _fortran_ssfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspcon "BLAS_FUNC(sspcon)"(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sspcon(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspev "BLAS_FUNC(sspev)"(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void sspev(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_sspev(jobz, uplo, n, ap, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspevd "BLAS_FUNC(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) 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:
+    
+    _fortran_sspevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspevx "BLAS_FUNC(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) 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:
+    
+    _fortran_sspevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgst "BLAS_FUNC(sspgst)"(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) nogil
+cdef void sspgst(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) noexcept nogil:
+    
+    _fortran_sspgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgv "BLAS_FUNC(sspgv)"(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) 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:
+    
+    _fortran_sspgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgvd "BLAS_FUNC(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) 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:
+    
+    _fortran_sspgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgvx "BLAS_FUNC(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) 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:
+    
+    _fortran_sspgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssprfs "BLAS_FUNC(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) 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:
+    
+    _fortran_ssprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspsv "BLAS_FUNC(sspsv)"(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sspsv(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspsvx "BLAS_FUNC(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) 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:
+    
+    _fortran_sspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrd "BLAS_FUNC(ssptrd)"(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) nogil
+cdef void ssptrd(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) noexcept nogil:
+    
+    _fortran_ssptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrf "BLAS_FUNC(ssptrf)"(char *uplo, int *n, s *ap, int *ipiv, int *info) nogil
+cdef void ssptrf(char *uplo, int *n, s *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_ssptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptri "BLAS_FUNC(ssptri)"(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) nogil
+cdef void ssptri(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrs "BLAS_FUNC(ssptrs)"(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void ssptrs(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstebz "BLAS_FUNC(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) 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:
+    
+    _fortran_sstebz(range, order, n, vl, vu, il, iu, abstol, d, e, m, nsplit, w, iblock, isplit, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstedc "BLAS_FUNC(sstedc)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_sstedc(compz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstegr "BLAS_FUNC(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) 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:
+    
+    _fortran_sstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstein "BLAS_FUNC(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) 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:
+    
+    _fortran_sstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstemr "BLAS_FUNC(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) 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:
+    
+    _fortran_sstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssteqr "BLAS_FUNC(ssteqr)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void ssteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssterf "BLAS_FUNC(ssterf)"(int *n, s *d, s *e, int *info) nogil
+cdef void ssterf(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_ssterf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstev "BLAS_FUNC(sstev)"(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void sstev(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_sstev(jobz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevd "BLAS_FUNC(sstevd)"(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_sstevd(jobz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevr "BLAS_FUNC(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) 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:
+    
+    _fortran_sstevr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevx "BLAS_FUNC(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) 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:
+    
+    _fortran_sstevx(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssycon "BLAS_FUNC(ssycon)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) 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:
+    
+    _fortran_ssycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyconv "BLAS_FUNC(ssyconv)"(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) nogil
+cdef void ssyconv(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyequb "BLAS_FUNC(ssyequb)"(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) nogil
+cdef void ssyequb(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyev "BLAS_FUNC(ssyev)"(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) nogil
+cdef void ssyev(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssyev(jobz, uplo, n, a, lda, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevd "BLAS_FUNC(ssyevd)"(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_ssyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevr "BLAS_FUNC(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) 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:
+    
+    _fortran_ssyevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevx "BLAS_FUNC(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) 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:
+    
+    _fortran_ssyevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygs2 "BLAS_FUNC(ssygs2)"(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void ssygs2(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssygs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygst "BLAS_FUNC(ssygst)"(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void ssygst(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssygst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygv "BLAS_FUNC(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) 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:
+    
+    _fortran_ssygv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygvd "BLAS_FUNC(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) 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:
+    
+    _fortran_ssygvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygvx "BLAS_FUNC(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) 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:
+    
+    _fortran_ssygvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_ssyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssysv "BLAS_FUNC(ssysv)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) 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:
+    
+    _fortran_ssysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssysvx "BLAS_FUNC(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) 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:
+    
+    _fortran_ssysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyswapr "BLAS_FUNC(ssyswapr)"(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) nogil
+cdef void ssyswapr(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_ssyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytd2 "BLAS_FUNC(ssytd2)"(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) nogil
+cdef void ssytd2(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) noexcept nogil:
+    
+    _fortran_ssytd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytf2 "BLAS_FUNC(ssytf2)"(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void ssytf2(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_ssytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrd "BLAS_FUNC(ssytrd)"(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) 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:
+    
+    _fortran_ssytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrf "BLAS_FUNC(ssytrf)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void ssytrf(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri "BLAS_FUNC(ssytri)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) nogil
+cdef void ssytri(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri2 "BLAS_FUNC(ssytri2)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void ssytri2(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri2x "BLAS_FUNC(ssytri2x)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) nogil
+cdef void ssytri2x(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_ssytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrs "BLAS_FUNC(ssytrs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void ssytrs(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrs2 "BLAS_FUNC(ssytrs2)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) 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:
+    
+    _fortran_ssytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbcon "BLAS_FUNC(stbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) 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:
+    
+    _fortran_stbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_stbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbtrs "BLAS_FUNC(stbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) 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:
+    
+    _fortran_stbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfsm "BLAS_FUNC(stfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) 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:
+    
+    _fortran_stfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stftri "BLAS_FUNC(stftri)"(char *transr, char *uplo, char *diag, int *n, s *a, int *info) nogil
+cdef void stftri(char *transr, char *uplo, char *diag, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_stftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfttp "BLAS_FUNC(stfttp)"(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) nogil
+cdef void stfttp(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) noexcept nogil:
+    
+    _fortran_stfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfttr "BLAS_FUNC(stfttr)"(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) nogil
+cdef void stfttr(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_stfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgevc "BLAS_FUNC(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) 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:
+    
+    _fortran_stgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgex2 "BLAS_FUNC(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) 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:
+    
+    _fortran_stgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, n1, n2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgexc "BLAS_FUNC(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) 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:
+    
+    _fortran_stgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsen "BLAS_FUNC(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) 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:
+    
+    _fortran_stgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsja "BLAS_FUNC(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) 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:
+    
+    _fortran_stgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsna "BLAS_FUNC(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) 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:
+    
+    _fortran_stgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsy2 "BLAS_FUNC(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) 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:
+    
+    _fortran_stgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, iwork, pq, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsyl "BLAS_FUNC(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) 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:
+    
+    _fortran_stgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpcon "BLAS_FUNC(stpcon)"(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void stpcon(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpmqrt "BLAS_FUNC(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) 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:
+    
+    _fortran_stpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpqrt "BLAS_FUNC(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) 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:
+    
+    _fortran_stpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpqrt2 "BLAS_FUNC(stpqrt2)"(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) 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:
+    
+    _fortran_stpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stprfb "BLAS_FUNC(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) 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:
+    
+    _fortran_stprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stprfs "BLAS_FUNC(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) 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:
+    
+    _fortran_stprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stptri "BLAS_FUNC(stptri)"(char *uplo, char *diag, int *n, s *ap, int *info) nogil
+cdef void stptri(char *uplo, char *diag, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_stptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stptrs "BLAS_FUNC(stptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void stptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_stptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpttf "BLAS_FUNC(stpttf)"(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) nogil
+cdef void stpttf(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) noexcept nogil:
+    
+    _fortran_stpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpttr "BLAS_FUNC(stpttr)"(char *uplo, int *n, s *ap, s *a, int *lda, int *info) nogil
+cdef void stpttr(char *uplo, int *n, s *ap, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_stpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strcon "BLAS_FUNC(strcon)"(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) 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:
+    
+    _fortran_strcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strevc "BLAS_FUNC(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) 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:
+    
+    _fortran_strevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strexc "BLAS_FUNC(strexc)"(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) 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:
+    
+    _fortran_strexc(compq, n, t, ldt, q, ldq, ifst, ilst, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strrfs "BLAS_FUNC(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) 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:
+    
+    _fortran_strrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsen "BLAS_FUNC(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) 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:
+    
+    _fortran_strsen(job, compq, select, n, t, ldt, q, ldq, wr, wi, m, s, sep, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsna "BLAS_FUNC(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) 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:
+    
+    _fortran_strsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsyl "BLAS_FUNC(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) 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:
+    
+    _fortran_strsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strti2 "BLAS_FUNC(strti2)"(char *uplo, char *diag, int *n, s *a, int *lda, int *info) nogil
+cdef void strti2(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_strti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strtri "BLAS_FUNC(strtri)"(char *uplo, char *diag, int *n, s *a, int *lda, int *info) nogil
+cdef void strtri(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_strtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strtrs "BLAS_FUNC(strtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) 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:
+    
+    _fortran_strtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strttf "BLAS_FUNC(strttf)"(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) nogil
+cdef void strttf(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) noexcept nogil:
+    
+    _fortran_strttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strttp "BLAS_FUNC(strttp)"(char *uplo, int *n, s *a, int *lda, s *ap, int *info) nogil
+cdef void strttp(char *uplo, int *n, s *a, int *lda, s *ap, int *info) noexcept nogil:
+    
+    _fortran_strttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stzrzf "BLAS_FUNC(stzrzf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void stzrzf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_stzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_xerbla_array "BLAS_FUNC(xerbla_array)"(char *srname_array, int *srname_len, int *info) nogil
+cdef void xerbla_array(char *srname_array, int *srname_len, int *info) noexcept nogil:
+    
+    _fortran_xerbla_array(srname_array, srname_len, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zbbcsd "BLAS_FUNC(zbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *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) 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:
+    
+    _fortran_zbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, rwork, lrwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zbdsqr "BLAS_FUNC(zbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, npy_complex128 *vt, int *ldvt, npy_complex128 *u, int *ldu, npy_complex128 *c, int *ldc, d *rwork, int *info) 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:
+    
+    _fortran_zbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zcgesv "BLAS_FUNC(zcgesv)"(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, d *rwork, int *iter, int *info) 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:
+    
+    _fortran_zcgesv(n, nrhs, a, lda, ipiv, b, ldb, x, ldx, work, swork, rwork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zcposv "BLAS_FUNC(zcposv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, d *rwork, int *iter, int *info) 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:
+    
+    _fortran_zcposv(uplo, n, nrhs, a, lda, b, ldb, x, ldx, work, swork, rwork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zdrscl "BLAS_FUNC(zdrscl)"(int *n, d *sa, npy_complex128 *sx, int *incx) nogil
+cdef void zdrscl(int *n, d *sa, z *sx, int *incx) noexcept nogil:
+    
+    _fortran_zdrscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbbrd "BLAS_FUNC(zgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *pt, int *ldpt, npy_complex128 *c, int *ldc, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbcon "BLAS_FUNC(zgbcon)"(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbequ "BLAS_FUNC(zgbequ)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) 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:
+    
+    _fortran_zgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbequb "BLAS_FUNC(zgbequb)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) 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:
+    
+    _fortran_zgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbrfs "BLAS_FUNC(zgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbsv "BLAS_FUNC(zgbsv)"(int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info) 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:
+    
+    _fortran_zgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbsvx "BLAS_FUNC(zgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtf2 "BLAS_FUNC(zgbtf2)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void zgbtf2(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtrf "BLAS_FUNC(zgbtrf)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void zgbtrf(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtrs "BLAS_FUNC(zgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info) 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:
+    
+    _fortran_zgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebak "BLAS_FUNC(zgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, npy_complex128 *v, int *ldv, int *info) 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:
+    
+    _fortran_zgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebal "BLAS_FUNC(zgebal)"(char *job, int *n, npy_complex128 *a, int *lda, int *ilo, int *ihi, d *scale, int *info) nogil
+cdef void zgebal(char *job, int *n, z *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil:
+    
+    _fortran_zgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebd2 "BLAS_FUNC(zgebd2)"(int *m, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebrd "BLAS_FUNC(zgebrd)"(int *m, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgecon "BLAS_FUNC(zgecon)"(char *norm, int *n, npy_complex128 *a, int *lda, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgecon(char *norm, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgecon(norm, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeequ "BLAS_FUNC(zgeequ)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) 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:
+    
+    _fortran_zgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeequb "BLAS_FUNC(zgeequb)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) 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:
+    
+    _fortran_zgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgees "BLAS_FUNC(zgees)"(char *jobvs, char *sort, _zselect1 *select, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) 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:
+    
+    _fortran_zgees(jobvs, sort, <_zselect1*>select, n, a, lda, sdim, w, vs, ldvs, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeesx "BLAS_FUNC(zgeesx)"(char *jobvs, char *sort, _zselect1 *select, char *sense, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) 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:
+    
+    _fortran_zgeesx(jobvs, sort, <_zselect1*>select, sense, n, a, lda, sdim, w, vs, ldvs, rconde, rcondv, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeev "BLAS_FUNC(zgeev)"(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeevx "BLAS_FUNC(zgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zgeevx(balanc, jobvl, jobvr, sense, n, a, lda, w, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgehd2 "BLAS_FUNC(zgehd2)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgehd2(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgehrd "BLAS_FUNC(zgehrd)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgehrd(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelq2 "BLAS_FUNC(zgelq2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgelq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelqf "BLAS_FUNC(zgelqf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgelqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgels "BLAS_FUNC(zgels)"(char *trans, int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelsd "BLAS_FUNC(zgelsd)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *s, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *info) 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:
+    
+    _fortran_zgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelss "BLAS_FUNC(zgelss)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *s, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelsy "BLAS_FUNC(zgelsy)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *jpvt, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgemqrt "BLAS_FUNC(zgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeql2 "BLAS_FUNC(zgeql2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeql2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqlf "BLAS_FUNC(zgeqlf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqlf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqp3 "BLAS_FUNC(zgeqp3)"(int *m, int *n, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqr2 "BLAS_FUNC(zgeqr2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeqr2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqr2p "BLAS_FUNC(zgeqr2p)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeqr2p(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrf "BLAS_FUNC(zgeqrf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqrf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrfp "BLAS_FUNC(zgeqrfp)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqrfp(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt "BLAS_FUNC(zgeqrt)"(int *m, int *n, int *nb, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info) nogil
+cdef void zgeqrt(int *m, int *n, int *nb, z *a, int *lda, z *t, int *ldt, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt2 "BLAS_FUNC(zgeqrt2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info) nogil
+cdef void zgeqrt2(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt3 "BLAS_FUNC(zgeqrt3)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info) nogil
+cdef void zgeqrt3(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerfs "BLAS_FUNC(zgerfs)"(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerq2 "BLAS_FUNC(zgerq2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgerq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerqf "BLAS_FUNC(zgerqf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgerqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesc2 "BLAS_FUNC(zgesc2)"(int *n, npy_complex128 *a, int *lda, npy_complex128 *rhs, int *ipiv, int *jpiv, d *scale) nogil
+cdef void zgesc2(int *n, z *a, int *lda, z *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil:
+    
+    _fortran_zgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesdd "BLAS_FUNC(zgesdd)"(char *jobz, int *m, int *n, npy_complex128 *a, int *lda, d *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *info) 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:
+    
+    _fortran_zgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesv "BLAS_FUNC(zgesv)"(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesvd "BLAS_FUNC(zgesvd)"(char *jobu, char *jobvt, int *m, int *n, npy_complex128 *a, int *lda, d *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesvx "BLAS_FUNC(zgesvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetc2 "BLAS_FUNC(zgetc2)"(int *n, npy_complex128 *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void zgetc2(int *n, z *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_zgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetf2 "BLAS_FUNC(zgetf2)"(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zgetf2(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetrf "BLAS_FUNC(zgetrf)"(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zgetrf(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetri "BLAS_FUNC(zgetri)"(int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgetri(int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetrs "BLAS_FUNC(zgetrs)"(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgetrs(char *trans, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggbak "BLAS_FUNC(zggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, npy_complex128 *v, int *ldv, int *info) 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:
+    
+    _fortran_zggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggbal "BLAS_FUNC(zggbal)"(char *job, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) 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:
+    
+    _fortran_zggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgges "BLAS_FUNC(zgges)"(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) 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:
+    
+    _fortran_zgges(jobvsl, jobvsr, sort, <_zselect2*>selctg, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggesx "BLAS_FUNC(zggesx)"(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) 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:
+    
+    _fortran_zggesx(jobvsl, jobvsr, sort, <_zselect2*>selctg, sense, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggev "BLAS_FUNC(zggev)"(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zggev(jobvl, jobvr, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggevx "BLAS_FUNC(zggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) 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:
+    
+    _fortran_zggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, rwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggglm "BLAS_FUNC(zggglm)"(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *d, npy_complex128 *x, npy_complex128 *y, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgghrd "BLAS_FUNC(zgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *info) 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:
+    
+    _fortran_zgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgglse "BLAS_FUNC(zgglse)"(int *m, int *n, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, npy_complex128 *d, npy_complex128 *x, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggqrf "BLAS_FUNC(zggqrf)"(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggrqf "BLAS_FUNC(zggrqf)"(int *m, int *p, int *n, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtcon "BLAS_FUNC(zgtcon)"(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtrfs "BLAS_FUNC(zgtrfs)"(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtsv "BLAS_FUNC(zgtsv)"(int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgtsv(int *n, int *nrhs, z *dl, z *d, z *du, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtsvx "BLAS_FUNC(zgtsvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgttrf "BLAS_FUNC(zgttrf)"(int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, int *info) nogil
+cdef void zgttrf(int *n, z *dl, z *d, z *du, z *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgttrs "BLAS_FUNC(zgttrs)"(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, int *info) 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:
+    
+    _fortran_zgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtts2 "BLAS_FUNC(zgtts2)"(int *itrans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb) 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:
+    
+    _fortran_zgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbev "BLAS_FUNC(zhbev)"(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zhbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbevd "BLAS_FUNC(zhbevd)"(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zhbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbevx "BLAS_FUNC(zhbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_zhbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgst "BLAS_FUNC(zhbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *x, int *ldx, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zhbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgv "BLAS_FUNC(zhbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zhbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgvd "BLAS_FUNC(zhbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zhbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgvx "BLAS_FUNC(zhbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_zhbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbtrd "BLAS_FUNC(zhbtrd)"(char *vect, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zhbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhecon "BLAS_FUNC(zhecon)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zhecon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhecon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheequb "BLAS_FUNC(zheequb)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, npy_complex128 *work, int *info) nogil
+cdef void zheequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil:
+    
+    _fortran_zheequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheev "BLAS_FUNC(zheev)"(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, d *w, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zheev(jobz, uplo, n, a, lda, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevd "BLAS_FUNC(zheevd)"(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, d *w, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevr "BLAS_FUNC(zheevr)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, int *isuppz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zheevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevx "BLAS_FUNC(zheevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_zheevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegs2 "BLAS_FUNC(zhegs2)"(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhegs2(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhegs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegst "BLAS_FUNC(zhegst)"(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhegst(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhegst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegv "BLAS_FUNC(zhegv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *w, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zhegv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegvd "BLAS_FUNC(zhegvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *w, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zhegvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegvx "BLAS_FUNC(zhegvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_zhegvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zherfs "BLAS_FUNC(zherfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhesv "BLAS_FUNC(zhesv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zhesv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhesvx "BLAS_FUNC(zhesvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zhesvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheswapr "BLAS_FUNC(zheswapr)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2) nogil
+cdef void zheswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_zheswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetd2 "BLAS_FUNC(zhetd2)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tau, int *info) nogil
+cdef void zhetd2(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, int *info) noexcept nogil:
+    
+    _fortran_zhetd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetf2 "BLAS_FUNC(zhetf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zhetf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zhetf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrd "BLAS_FUNC(zhetrd)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrf "BLAS_FUNC(zhetrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhetrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhetrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri "BLAS_FUNC(zhetri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zhetri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhetri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri2 "BLAS_FUNC(zhetri2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhetri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhetri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri2x "BLAS_FUNC(zhetri2x)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info) nogil
+cdef void zhetri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_zhetri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrs "BLAS_FUNC(zhetrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhetrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrs2 "BLAS_FUNC(zhetrs2)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zhetrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhfrk "BLAS_FUNC(zhfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c) 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:
+    
+    _fortran_zhfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhgeqz "BLAS_FUNC(zhgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *t, int *ldt, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zhgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alpha, beta, q, ldq, z, ldz, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpcon "BLAS_FUNC(zhpcon)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zhpcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhpcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpev "BLAS_FUNC(zhpev)"(char *jobz, char *uplo, int *n, npy_complex128 *ap, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zhpev(jobz, uplo, n, ap, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpevd "BLAS_FUNC(zhpevd)"(char *jobz, char *uplo, int *n, npy_complex128 *ap, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zhpevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpevx "BLAS_FUNC(zhpevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_zhpevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgst "BLAS_FUNC(zhpgst)"(int *itype, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, int *info) nogil
+cdef void zhpgst(int *itype, char *uplo, int *n, z *ap, z *bp, int *info) noexcept nogil:
+    
+    _fortran_zhpgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgv "BLAS_FUNC(zhpgv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zhpgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgvd "BLAS_FUNC(zhpgvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zhpgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgvx "BLAS_FUNC(zhpgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_zhpgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhprfs "BLAS_FUNC(zhprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zhprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpsv "BLAS_FUNC(zhpsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhpsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhpsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpsvx "BLAS_FUNC(zhpsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zhpsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrd "BLAS_FUNC(zhptrd)"(char *uplo, int *n, npy_complex128 *ap, d *d, d *e, npy_complex128 *tau, int *info) nogil
+cdef void zhptrd(char *uplo, int *n, z *ap, d *d, d *e, z *tau, int *info) noexcept nogil:
+    
+    _fortran_zhptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrf "BLAS_FUNC(zhptrf)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info) nogil
+cdef void zhptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zhptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptri "BLAS_FUNC(zhptri)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zhptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrs "BLAS_FUNC(zhptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhsein "BLAS_FUNC(zhsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *ifaill, int *ifailr, int *info) 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:
+    
+    _fortran_zhsein(side, eigsrc, initv, select, n, h, ldh, w, vl, ldvl, vr, ldvr, mm, m, work, rwork, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhseqr "BLAS_FUNC(zhseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zhseqr(job, compz, n, ilo, ihi, h, ldh, w, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlabrd "BLAS_FUNC(zlabrd)"(int *m, int *n, int *nb, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *x, int *ldx, npy_complex128 *y, int *ldy) 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:
+    
+    _fortran_zlabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacgv "BLAS_FUNC(zlacgv)"(int *n, npy_complex128 *x, int *incx) nogil
+cdef void zlacgv(int *n, z *x, int *incx) noexcept nogil:
+    
+    _fortran_zlacgv(n, x, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacn2 "BLAS_FUNC(zlacn2)"(int *n, npy_complex128 *v, npy_complex128 *x, d *est, int *kase, int *isave) nogil
+cdef void zlacn2(int *n, z *v, z *x, d *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_zlacn2(n, v, x, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacon "BLAS_FUNC(zlacon)"(int *n, npy_complex128 *v, npy_complex128 *x, d *est, int *kase) nogil
+cdef void zlacon(int *n, z *v, z *x, d *est, int *kase) noexcept nogil:
+    
+    _fortran_zlacon(n, v, x, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacp2 "BLAS_FUNC(zlacp2)"(char *uplo, int *m, int *n, d *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void zlacp2(char *uplo, int *m, int *n, d *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zlacp2(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacpy "BLAS_FUNC(zlacpy)"(char *uplo, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void zlacpy(char *uplo, int *m, int *n, z *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zlacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacrm "BLAS_FUNC(zlacrm)"(int *m, int *n, npy_complex128 *a, int *lda, d *b, int *ldb, npy_complex128 *c, int *ldc, d *rwork) nogil
+cdef void zlacrm(int *m, int *n, z *a, int *lda, d *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil:
+    
+    _fortran_zlacrm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacrt "BLAS_FUNC(zlacrt)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, npy_complex128 *c, npy_complex128 *s) nogil
+cdef void zlacrt(int *n, z *cx, int *incx, z *cy, int *incy, z *c, z *s) noexcept nogil:
+    
+    _fortran_zlacrt(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zladiv "F_FUNC(zladivwrp,ZLADIVWRP)"(npy_complex128 *out, npy_complex128 *x, npy_complex128 *y) nogil
+cdef z zladiv(z *x, z *y) noexcept nogil:
+    cdef z out
+    _fortran_zladiv(&out, x, y)
+    return out
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed0 "BLAS_FUNC(zlaed0)"(int *qsiz, int *n, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *qstore, int *ldqs, d *rwork, int *iwork, int *info) 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:
+    
+    _fortran_zlaed0(qsiz, n, d, e, q, ldq, qstore, ldqs, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed7 "BLAS_FUNC(zlaed7)"(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, npy_complex128 *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, npy_complex128 *work, d *rwork, int *iwork, int *info) 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:
+    
+    _fortran_zlaed7(n, cutpnt, qsiz, tlvls, curlvl, curpbm, d, q, ldq, rho, indxq, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed8 "BLAS_FUNC(zlaed8)"(int *k, int *n, int *qsiz, npy_complex128 *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, npy_complex128 *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) 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:
+    
+    _fortran_zlaed8(k, n, qsiz, q, ldq, d, rho, cutpnt, z, dlamda, q2, ldq2, w, indxp, indx, indxq, perm, givptr, givcol, givnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaein "BLAS_FUNC(zlaein)"(bint *rightv, bint *noinit, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *v, npy_complex128 *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) 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:
+    
+    _fortran_zlaein(rightv, noinit, n, h, ldh, w, v, b, ldb, rwork, eps3, smlnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaesy "BLAS_FUNC(zlaesy)"(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, npy_complex128 *rt1, npy_complex128 *rt2, npy_complex128 *evscal, npy_complex128 *cs1, npy_complex128 *sn1) nogil
+cdef void zlaesy(z *a, z *b, z *c, z *rt1, z *rt2, z *evscal, z *cs1, z *sn1) noexcept nogil:
+    
+    _fortran_zlaesy(a, b, c, rt1, rt2, evscal, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaev2 "BLAS_FUNC(zlaev2)"(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, d *rt1, d *rt2, d *cs1, npy_complex128 *sn1) nogil
+cdef void zlaev2(z *a, z *b, z *c, d *rt1, d *rt2, d *cs1, z *sn1) noexcept nogil:
+    
+    _fortran_zlaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlag2c "BLAS_FUNC(zlag2c)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info) nogil
+cdef void zlag2c(int *m, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_zlag2c(m, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlags2 "BLAS_FUNC(zlags2)"(bint *upper, d *a1, npy_complex128 *a2, d *a3, d *b1, npy_complex128 *b2, d *b3, d *csu, npy_complex128 *snu, d *csv, npy_complex128 *snv, d *csq, npy_complex128 *snq) 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:
+    
+    _fortran_zlags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlagtm "BLAS_FUNC(zlagtm)"(char *trans, int *n, int *nrhs, d *alpha, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *x, int *ldx, d *beta, npy_complex128 *b, int *ldb) 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:
+    
+    _fortran_zlagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahef "BLAS_FUNC(zlahef)"(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info) 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:
+    
+    _fortran_zlahef(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahqr "BLAS_FUNC(zlahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *info) 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:
+    
+    _fortran_zlahqr(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahr2 "BLAS_FUNC(zlahr2)"(int *n, int *k, int *nb, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *t, int *ldt, npy_complex128 *y, int *ldy) 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:
+    
+    _fortran_zlahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaic1 "BLAS_FUNC(zlaic1)"(int *job, int *j, npy_complex128 *x, d *sest, npy_complex128 *w, npy_complex128 *gamma, d *sestpr, npy_complex128 *s, npy_complex128 *c) nogil
+cdef void zlaic1(int *job, int *j, z *x, d *sest, z *w, z *gamma, d *sestpr, z *s, z *c) noexcept nogil:
+    
+    _fortran_zlaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlals0 "BLAS_FUNC(zlals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *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) 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:
+    
+    _fortran_zlals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlalsa "BLAS_FUNC(zlalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *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) 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:
+    
+    _fortran_zlalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlalsd "BLAS_FUNC(zlalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, npy_complex128 *b, int *ldb, d *rcond, int *rank, npy_complex128 *work, d *rwork, int *iwork, int *info) 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:
+    
+    _fortran_zlalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlangb "BLAS_FUNC(zlangb)"(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlangb(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlange "BLAS_FUNC(zlange)"(char *norm, int *m, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlange(char *norm, int *m, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlangt "BLAS_FUNC(zlangt)"(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d_, npy_complex128 *du) nogil
+cdef d zlangt(char *norm, int *n, z *dl, z *d_, z *du) noexcept nogil:
+    
+    return _fortran_zlangt(norm, n, dl, d_, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhb "BLAS_FUNC(zlanhb)"(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlanhb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlanhb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhe "BLAS_FUNC(zlanhe)"(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlanhe(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlanhe(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhf "BLAS_FUNC(zlanhf)"(char *norm, char *transr, char *uplo, int *n, npy_complex128 *a, d *work) nogil
+cdef d zlanhf(char *norm, char *transr, char *uplo, int *n, z *a, d *work) noexcept nogil:
+    
+    return _fortran_zlanhf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhp "BLAS_FUNC(zlanhp)"(char *norm, char *uplo, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlanhp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlanhp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhs "BLAS_FUNC(zlanhs)"(char *norm, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlanhs(char *norm, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanht "BLAS_FUNC(zlanht)"(char *norm, int *n, d *d_, npy_complex128 *e) nogil
+cdef d zlanht(char *norm, int *n, d *d_, z *e) noexcept nogil:
+    
+    return _fortran_zlanht(norm, n, d_, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansb "BLAS_FUNC(zlansb)"(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlansb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansp "BLAS_FUNC(zlansp)"(char *norm, char *uplo, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlansp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansy "BLAS_FUNC(zlansy)"(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlansy(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantb "BLAS_FUNC(zlantb)"(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlantb(char *norm, char *uplo, char *diag, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantp "BLAS_FUNC(zlantp)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlantp(char *norm, char *uplo, char *diag, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantr "BLAS_FUNC(zlantr)"(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlantr(char *norm, char *uplo, char *diag, int *m, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapll "BLAS_FUNC(zlapll)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *ssmin) nogil
+cdef void zlapll(int *n, z *x, int *incx, z *y, int *incy, d *ssmin) noexcept nogil:
+    
+    _fortran_zlapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapmr "BLAS_FUNC(zlapmr)"(bint *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k) nogil
+cdef void zlapmr(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_zlapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapmt "BLAS_FUNC(zlapmt)"(bint *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k) nogil
+cdef void zlapmt(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_zlapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqgb "BLAS_FUNC(zlaqgb)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) 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:
+    
+    _fortran_zlaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqge "BLAS_FUNC(zlaqge)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) 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:
+    
+    _fortran_zlaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhb "BLAS_FUNC(zlaqhb)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhe "BLAS_FUNC(zlaqhe)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhe(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhe(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhp "BLAS_FUNC(zlaqhp)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqp2 "BLAS_FUNC(zlaqp2)"(int *m, int *n, int *offset, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, d *vn1, d *vn2, npy_complex128 *work) 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:
+    
+    _fortran_zlaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqps "BLAS_FUNC(zlaqps)"(int *m, int *n, int *offset, int *nb, int *kb, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, d *vn1, d *vn2, npy_complex128 *auxv, npy_complex128 *f, int *ldf) 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:
+    
+    _fortran_zlaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr0 "BLAS_FUNC(zlaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zlaqr0(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr1 "BLAS_FUNC(zlaqr1)"(int *n, npy_complex128 *h, int *ldh, npy_complex128 *s1, npy_complex128 *s2, npy_complex128 *v) nogil
+cdef void zlaqr1(int *n, z *h, int *ldh, z *s1, z *s2, z *v) noexcept nogil:
+    
+    _fortran_zlaqr1(n, h, ldh, s1, s2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr2 "BLAS_FUNC(zlaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork) 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:
+    
+    _fortran_zlaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr3 "BLAS_FUNC(zlaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork) 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:
+    
+    _fortran_zlaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr4 "BLAS_FUNC(zlaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zlaqr4(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr5 "BLAS_FUNC(zlaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex128 *s, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *v, int *ldv, npy_complex128 *u, int *ldu, int *nv, npy_complex128 *wv, int *ldwv, int *nh, npy_complex128 *wh, int *ldwh) 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:
+    
+    _fortran_zlaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, s, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsb "BLAS_FUNC(zlaqsb)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsp "BLAS_FUNC(zlaqsp)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsy "BLAS_FUNC(zlaqsy)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsy(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlar1v "BLAS_FUNC(zlar1v)"(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, npy_complex128 *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) 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:
+    
+    _fortran_zlar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlar2v "BLAS_FUNC(zlar2v)"(int *n, npy_complex128 *x, npy_complex128 *y, npy_complex128 *z, int *incx, d *c, npy_complex128 *s, int *incc) nogil
+cdef void zlar2v(int *n, z *x, z *y, z *z, int *incx, d *c, z *s, int *incc) noexcept nogil:
+    
+    _fortran_zlar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarcm "BLAS_FUNC(zlarcm)"(int *m, int *n, d *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, d *rwork) nogil
+cdef void zlarcm(int *m, int *n, d *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil:
+    
+    _fortran_zlarcm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarf "BLAS_FUNC(zlarf)"(char *side, int *m, int *n, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil
+cdef void zlarf(char *side, int *m, int *n, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil:
+    
+    _fortran_zlarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfb "BLAS_FUNC(zlarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork) 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:
+    
+    _fortran_zlarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfg "BLAS_FUNC(zlarfg)"(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau) nogil
+cdef void zlarfg(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil:
+    
+    _fortran_zlarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfgp "BLAS_FUNC(zlarfgp)"(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau) nogil
+cdef void zlarfgp(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil:
+    
+    _fortran_zlarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarft "BLAS_FUNC(zlarft)"(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt) nogil
+cdef void zlarft(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil:
+    
+    _fortran_zlarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfx "BLAS_FUNC(zlarfx)"(char *side, int *m, int *n, npy_complex128 *v, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil
+cdef void zlarfx(char *side, int *m, int *n, z *v, z *tau, z *c, int *ldc, z *work) noexcept nogil:
+    
+    _fortran_zlarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlargv "BLAS_FUNC(zlargv)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *c, int *incc) nogil
+cdef void zlargv(int *n, z *x, int *incx, z *y, int *incy, d *c, int *incc) noexcept nogil:
+    
+    _fortran_zlargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarnv "BLAS_FUNC(zlarnv)"(int *idist, int *iseed, int *n, npy_complex128 *x) nogil
+cdef void zlarnv(int *idist, int *iseed, int *n, z *x) noexcept nogil:
+    
+    _fortran_zlarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarrv "BLAS_FUNC(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, npy_complex128 *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) 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:
+    
+    _fortran_zlarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlartg "BLAS_FUNC(zlartg)"(npy_complex128 *f, npy_complex128 *g, d *cs, npy_complex128 *sn, npy_complex128 *r) nogil
+cdef void zlartg(z *f, z *g, d *cs, z *sn, z *r) noexcept nogil:
+    
+    _fortran_zlartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlartv "BLAS_FUNC(zlartv)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *c, npy_complex128 *s, int *incc) nogil
+cdef void zlartv(int *n, z *x, int *incx, z *y, int *incy, d *c, z *s, int *incc) noexcept nogil:
+    
+    _fortran_zlartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarz "BLAS_FUNC(zlarz)"(char *side, int *m, int *n, int *l, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) 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:
+    
+    _fortran_zlarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarzb "BLAS_FUNC(zlarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork) 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:
+    
+    _fortran_zlarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarzt "BLAS_FUNC(zlarzt)"(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt) nogil
+cdef void zlarzt(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil:
+    
+    _fortran_zlarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlascl "BLAS_FUNC(zlascl)"(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, npy_complex128 *a, int *lda, int *info) 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:
+    
+    _fortran_zlascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaset "BLAS_FUNC(zlaset)"(char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *a, int *lda) nogil
+cdef void zlaset(char *uplo, int *m, int *n, z *alpha, z *beta, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zlaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlasr "BLAS_FUNC(zlasr)"(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, npy_complex128 *a, int *lda) nogil
+cdef void zlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zlasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlassq "BLAS_FUNC(zlassq)"(int *n, npy_complex128 *x, int *incx, d *scale, d *sumsq) nogil
+cdef void zlassq(int *n, z *x, int *incx, d *scale, d *sumsq) noexcept nogil:
+    
+    _fortran_zlassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaswp "BLAS_FUNC(zlaswp)"(int *n, npy_complex128 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void zlaswp(int *n, z *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_zlaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlasyf "BLAS_FUNC(zlasyf)"(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info) 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:
+    
+    _fortran_zlasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlat2c "BLAS_FUNC(zlat2c)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info) nogil
+cdef void zlat2c(char *uplo, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_zlat2c(uplo, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatbs "BLAS_FUNC(zlatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *x, d *scale, d *cnorm, int *info) 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:
+    
+    _fortran_zlatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatdf "BLAS_FUNC(zlatdf)"(int *ijob, int *n, npy_complex128 *z, int *ldz, npy_complex128 *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) nogil
+cdef void zlatdf(int *ijob, int *n, z *z, int *ldz, z *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_zlatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatps "BLAS_FUNC(zlatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *ap, npy_complex128 *x, d *scale, d *cnorm, int *info) 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:
+    
+    _fortran_zlatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrd "BLAS_FUNC(zlatrd)"(char *uplo, int *n, int *nb, npy_complex128 *a, int *lda, d *e, npy_complex128 *tau, npy_complex128 *w, int *ldw) nogil
+cdef void zlatrd(char *uplo, int *n, int *nb, z *a, int *lda, d *e, z *tau, z *w, int *ldw) noexcept nogil:
+    
+    _fortran_zlatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrs "BLAS_FUNC(zlatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, d *scale, d *cnorm, int *info) 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:
+    
+    _fortran_zlatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrz "BLAS_FUNC(zlatrz)"(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work) nogil
+cdef void zlatrz(int *m, int *n, int *l, z *a, int *lda, z *tau, z *work) noexcept nogil:
+    
+    _fortran_zlatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlauu2 "BLAS_FUNC(zlauu2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zlauu2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zlauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlauum "BLAS_FUNC(zlauum)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zlauum(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zlauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbcon "BLAS_FUNC(zpbcon)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbequ "BLAS_FUNC(zpbequ)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpbequ(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbrfs "BLAS_FUNC(zpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbstf "BLAS_FUNC(zpbstf)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbstf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbsv "BLAS_FUNC(zpbsv)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpbsv(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbsvx "BLAS_FUNC(zpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtf2 "BLAS_FUNC(zpbtf2)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbtf2(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtrf "BLAS_FUNC(zpbtrf)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbtrf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtrs "BLAS_FUNC(zpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpbtrs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftrf "BLAS_FUNC(zpftrf)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *info) nogil
+cdef void zpftrf(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_zpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftri "BLAS_FUNC(zpftri)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *info) nogil
+cdef void zpftri(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_zpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftrs "BLAS_FUNC(zpftrs)"(char *transr, char *uplo, int *n, int *nrhs, npy_complex128 *a, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpftrs(char *transr, char *uplo, int *n, int *nrhs, z *a, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpocon "BLAS_FUNC(zpocon)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpocon(char *uplo, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpoequ "BLAS_FUNC(zpoequ)"(int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpoequ(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpoequb "BLAS_FUNC(zpoequb)"(int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpoequb(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zporfs "BLAS_FUNC(zporfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zposv "BLAS_FUNC(zposv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zposvx "BLAS_FUNC(zposvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotf2 "BLAS_FUNC(zpotf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotf2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotrf "BLAS_FUNC(zpotrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotrf(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotri "BLAS_FUNC(zpotri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotri(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotrs "BLAS_FUNC(zpotrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpotrs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppcon "BLAS_FUNC(zppcon)"(char *uplo, int *n, npy_complex128 *ap, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zppcon(char *uplo, int *n, z *ap, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zppcon(uplo, n, ap, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppequ "BLAS_FUNC(zppequ)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, int *info) nogil
+cdef void zppequ(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpprfs "BLAS_FUNC(zpprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppsv "BLAS_FUNC(zppsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zppsv(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppsvx "BLAS_FUNC(zppsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptrf "BLAS_FUNC(zpptrf)"(char *uplo, int *n, npy_complex128 *ap, int *info) nogil
+cdef void zpptrf(char *uplo, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_zpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptri "BLAS_FUNC(zpptri)"(char *uplo, int *n, npy_complex128 *ap, int *info) nogil
+cdef void zpptri(char *uplo, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_zpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptrs "BLAS_FUNC(zpptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpptrs(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpstf2 "BLAS_FUNC(zpstf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void zpstf2(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpstrf "BLAS_FUNC(zpstrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void zpstrf(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptcon "BLAS_FUNC(zptcon)"(int *n, d *d, npy_complex128 *e, d *anorm, d *rcond, d *rwork, int *info) nogil
+cdef void zptcon(int *n, d *d, z *e, d *anorm, d *rcond, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zptcon(n, d, e, anorm, rcond, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpteqr "BLAS_FUNC(zpteqr)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, d *work, int *info) nogil
+cdef void zpteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptrfs "BLAS_FUNC(zptrfs)"(char *uplo, int *n, int *nrhs, d *d, npy_complex128 *e, d *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zptrfs(uplo, n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptsv "BLAS_FUNC(zptsv)"(int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zptsv(int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptsvx "BLAS_FUNC(zptsvx)"(char *fact, int *n, int *nrhs, d *d, npy_complex128 *e, d *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpttrf "BLAS_FUNC(zpttrf)"(int *n, d *d, npy_complex128 *e, int *info) nogil
+cdef void zpttrf(int *n, d *d, z *e, int *info) noexcept nogil:
+    
+    _fortran_zpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpttrs "BLAS_FUNC(zpttrs)"(char *uplo, int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpttrs(char *uplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpttrs(uplo, n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptts2 "BLAS_FUNC(zptts2)"(int *iuplo, int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb) nogil
+cdef void zptts2(int *iuplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zptts2(iuplo, n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zrot "BLAS_FUNC(zrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, npy_complex128 *s) nogil
+cdef void zrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, z *s) noexcept nogil:
+    
+    _fortran_zrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspcon "BLAS_FUNC(zspcon)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zspcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zspcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspmv "BLAS_FUNC(zspmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zspmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspr "BLAS_FUNC(zspr)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil
+cdef void zspr(char *uplo, int *n, z *alpha, z *x, int *incx, z *ap) noexcept nogil:
+    
+    _fortran_zspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsprfs "BLAS_FUNC(zsprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspsv "BLAS_FUNC(zspsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zspsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspsvx "BLAS_FUNC(zspsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptrf "BLAS_FUNC(zsptrf)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info) nogil
+cdef void zsptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zsptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptri "BLAS_FUNC(zsptri)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptrs "BLAS_FUNC(zsptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zsptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstedc "BLAS_FUNC(zstedc)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zstedc(compz, n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstegr "BLAS_FUNC(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, npy_complex128 *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstein "BLAS_FUNC(zstein)"(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, npy_complex128 *z, int *ldz, d *work, int *iwork, int *ifail, int *info) 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:
+    
+    _fortran_zstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstemr "BLAS_FUNC(zstemr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, npy_complex128 *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_zstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsteqr "BLAS_FUNC(zsteqr)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, d *work, int *info) nogil
+cdef void zsteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_zsteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsycon "BLAS_FUNC(zsycon)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zsycon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyconv "BLAS_FUNC(zsyconv)"(char *uplo, char *way, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsyconv(char *uplo, char *way, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyequb "BLAS_FUNC(zsyequb)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, npy_complex128 *work, int *info) nogil
+cdef void zsyequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsymv "BLAS_FUNC(zsymv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) 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:
+    
+    _fortran_zsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyr "BLAS_FUNC(zsyr)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil
+cdef void zsyr(char *uplo, int *n, z *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zsyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyrfs "BLAS_FUNC(zsyrfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_zsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsysv "BLAS_FUNC(zsysv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zsysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsysvx "BLAS_FUNC(zsysvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, int *lwork, d *rwork, int *info) 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:
+    
+    _fortran_zsysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyswapr "BLAS_FUNC(zsyswapr)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2) nogil
+cdef void zsyswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_zsyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytf2 "BLAS_FUNC(zsytf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zsytf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zsytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrf "BLAS_FUNC(zsytrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zsytrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zsytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri "BLAS_FUNC(zsytri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsytri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri2 "BLAS_FUNC(zsytri2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zsytri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zsytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri2x "BLAS_FUNC(zsytri2x)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info) nogil
+cdef void zsytri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_zsytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrs "BLAS_FUNC(zsytrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zsytrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrs2 "BLAS_FUNC(zsytrs2)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zsytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbcon "BLAS_FUNC(ztbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex128 *ab, int *ldab, d *rcond, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_ztbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbrfs "BLAS_FUNC(ztbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_ztbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbtrs "BLAS_FUNC(ztbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) 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:
+    
+    _fortran_ztbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfsm "BLAS_FUNC(ztfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, npy_complex128 *b, int *ldb) 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:
+    
+    _fortran_ztfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztftri "BLAS_FUNC(ztftri)"(char *transr, char *uplo, char *diag, int *n, npy_complex128 *a, int *info) nogil
+cdef void ztftri(char *transr, char *uplo, char *diag, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_ztftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfttp "BLAS_FUNC(ztfttp)"(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *ap, int *info) nogil
+cdef void ztfttp(char *transr, char *uplo, int *n, z *arf, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfttr "BLAS_FUNC(ztfttr)"(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztfttr(char *transr, char *uplo, int *n, z *arf, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgevc "BLAS_FUNC(ztgevc)"(char *side, char *howmny, bint *select, int *n, npy_complex128 *s, int *lds, npy_complex128 *p, int *ldp, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_ztgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgex2 "BLAS_FUNC(ztgex2)"(bint *wantq, bint *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *j1, int *info) 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:
+    
+    _fortran_ztgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgexc "BLAS_FUNC(ztgexc)"(bint *wantq, bint *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *ifst, int *ilst, int *info) 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:
+    
+    _fortran_ztgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsen "BLAS_FUNC(ztgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *m, d *pl, d *pr, d *dif, npy_complex128 *work, int *lwork, int *iwork, int *liwork, int *info) 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:
+    
+    _fortran_ztgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsja "BLAS_FUNC(ztgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, npy_complex128 *u, int *ldu, npy_complex128 *v, int *ldv, npy_complex128 *q, int *ldq, npy_complex128 *work, int *ncycle, int *info) 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:
+    
+    _fortran_ztgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsna "BLAS_FUNC(ztgsna)"(char *job, char *howmny, bint *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, d *s, d *dif, int *mm, int *m, npy_complex128 *work, int *lwork, int *iwork, int *info) 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:
+    
+    _fortran_ztgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsy2 "BLAS_FUNC(ztgsy2)"(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) 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:
+    
+    _fortran_ztgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsyl "BLAS_FUNC(ztgsyl)"(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, d *scale, d *dif, npy_complex128 *work, int *lwork, int *iwork, int *info) 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:
+    
+    _fortran_ztgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpcon "BLAS_FUNC(ztpcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztpcon(char *norm, char *uplo, char *diag, int *n, z *ap, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpmqrt "BLAS_FUNC(ztpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) 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:
+    
+    _fortran_ztpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpqrt "BLAS_FUNC(ztpqrt)"(int *m, int *n, int *l, int *nb, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info) 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:
+    
+    _fortran_ztpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpqrt2 "BLAS_FUNC(ztpqrt2)"(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, int *info) 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:
+    
+    _fortran_ztpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztprfb "BLAS_FUNC(ztprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *ldwork) 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:
+    
+    _fortran_ztprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztprfs "BLAS_FUNC(ztprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_ztprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztptri "BLAS_FUNC(ztptri)"(char *uplo, char *diag, int *n, npy_complex128 *ap, int *info) nogil
+cdef void ztptri(char *uplo, char *diag, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztptrs "BLAS_FUNC(ztptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void ztptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ztptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpttf "BLAS_FUNC(ztpttf)"(char *transr, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *arf, int *info) nogil
+cdef void ztpttf(char *transr, char *uplo, int *n, z *ap, z *arf, int *info) noexcept nogil:
+    
+    _fortran_ztpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpttr "BLAS_FUNC(ztpttr)"(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztpttr(char *uplo, int *n, z *ap, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrcon "BLAS_FUNC(ztrcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, d *rcond, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_ztrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrevc "BLAS_FUNC(ztrevc)"(char *side, char *howmny, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_ztrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrexc "BLAS_FUNC(ztrexc)"(char *compq, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, int *ifst, int *ilst, int *info) nogil
+cdef void ztrexc(char *compq, int *n, z *t, int *ldt, z *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ztrexc(compq, n, t, ldt, q, ldq, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrrfs "BLAS_FUNC(ztrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) 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:
+    
+    _fortran_ztrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsen "BLAS_FUNC(ztrsen)"(char *job, char *compq, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, npy_complex128 *w, int *m, d *s, d *sep, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_ztrsen(job, compq, select, n, t, ldt, q, ldq, w, m, s, sep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsna "BLAS_FUNC(ztrsna)"(char *job, char *howmny, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, d *s, d *sep, int *mm, int *m, npy_complex128 *work, int *ldwork, d *rwork, int *info) 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:
+    
+    _fortran_ztrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsyl "BLAS_FUNC(ztrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, d *scale, int *info) 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:
+    
+    _fortran_ztrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrti2 "BLAS_FUNC(ztrti2)"(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztrti2(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrtri "BLAS_FUNC(ztrtri)"(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztrtri(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrtrs "BLAS_FUNC(ztrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) 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:
+    
+    _fortran_ztrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrttf "BLAS_FUNC(ztrttf)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *arf, int *info) nogil
+cdef void ztrttf(char *transr, char *uplo, int *n, z *a, int *lda, z *arf, int *info) noexcept nogil:
+    
+    _fortran_ztrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrttp "BLAS_FUNC(ztrttp)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *ap, int *info) nogil
+cdef void ztrttp(char *uplo, int *n, z *a, int *lda, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztzrzf "BLAS_FUNC(ztzrzf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void ztzrzf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ztzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunbdb "BLAS_FUNC(zunbdb)"(char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, d *theta, d *phi, npy_complex128 *taup1, npy_complex128 *taup2, npy_complex128 *tauq1, npy_complex128 *tauq2, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zuncsd "BLAS_FUNC(zuncsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, d *theta, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) 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:
+    
+    _fortran_zuncsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, lrwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zung2l "BLAS_FUNC(zung2l)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zung2l(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zung2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zung2r "BLAS_FUNC(zung2r)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zung2r(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zung2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungbr "BLAS_FUNC(zungbr)"(char *vect, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zungbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunghr "BLAS_FUNC(zunghr)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunghr(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungl2 "BLAS_FUNC(zungl2)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zungl2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zungl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunglq "BLAS_FUNC(zunglq)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunglq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungql "BLAS_FUNC(zungql)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungql(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungqr "BLAS_FUNC(zungqr)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungqr(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungr2 "BLAS_FUNC(zungr2)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zungr2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zungr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungrq "BLAS_FUNC(zungrq)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungrq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungtr "BLAS_FUNC(zungtr)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungtr(char *uplo, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunm2l "BLAS_FUNC(zunm2l)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zunm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunm2r "BLAS_FUNC(zunm2r)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zunm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmbr "BLAS_FUNC(zunmbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunmbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmhr "BLAS_FUNC(zunmhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunmhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunml2 "BLAS_FUNC(zunml2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zunml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmlq "BLAS_FUNC(zunmlq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunmlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmql "BLAS_FUNC(zunmql)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunmql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmqr "BLAS_FUNC(zunmqr)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunmqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmr2 "BLAS_FUNC(zunmr2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zunmr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmr3 "BLAS_FUNC(zunmr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zunmr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmrq "BLAS_FUNC(zunmrq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunmrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmrz "BLAS_FUNC(zunmrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunmrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmtr "BLAS_FUNC(zunmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) 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:
+    
+    _fortran_zunmtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zupgtr "BLAS_FUNC(zupgtr)"(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info) nogil
+cdef void zupgtr(char *uplo, int *n, z *ap, z *tau, z *q, int *ldq, z *work, int *info) noexcept nogil:
+    
+    _fortran_zupgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zupmtr "BLAS_FUNC(zupmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) 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:
+    
+    _fortran_zupmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+
+# Python accessible wrappers for testing:
+
+def _test_dlamch(cmach):
+    # This conversion is necessary to handle Python 3 strings.
+    cmach_bytes = bytes(cmach)
+    # Now that it is a bytes representation, a non-temporary variable
+    # must be passed as a part of the function call.
+    cdef char* cmach_char = cmach_bytes
+    return dlamch(cmach_char)
+
+def _test_slamch(cmach):
+    # This conversion is necessary to handle Python 3 strings.
+    cmach_bytes = bytes(cmach)
+    # Now that it is a bytes representation, a non-temporary variable
+    # must be passed as a part of the function call.
+    cdef char* cmach_char = cmach_bytes
+    return slamch(cmach_char)
+
+cpdef double complex _test_zladiv(double complex zx, double complex zy) noexcept nogil:
+    return zladiv(&zx, &zy)
+
+cpdef float complex _test_cladiv(float complex cx, float complex cy) noexcept nogil:
+    return cladiv(&cx, &cy)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d82ab157ce3be763f63e453c9a6fee064557c85
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..92545a5c6af5fe7a4de13f8746b96696d68b5bd2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d5d9a98a04a689fb735f81299e129dc7f307590
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ef58729412ce2c83310b7817a143d14b8f28c19
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3c6cc494db9b35dce8e4007c8c30d823b03881f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..64d0ce8562f06a3837df050f0ea6b8b15a2b359e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..38070863aa515266b0b130dbbdbd3d645da4aa0c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py
@@ -0,0 +1,989 @@
+#  ******************************************************************************
+#   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
+
+Following support functions are deprecated and will be removed in SciPy 1.17.0:
+
+.. autosummary::
+   :toctree: generated/
+
+   seed
+   rand
+
+
+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
+import warnings
+
+__all__ = [
+    'estimate_rank',
+    'estimate_spectral_norm',
+    'estimate_spectral_norm_diff',
+    'id_to_svd',
+    'interp_decomp',
+    'rand',
+    'reconstruct_interp_matrix',
+    'reconstruct_matrix_from_id',
+    'reconstruct_skel_matrix',
+    'seed',
+    '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 seed(seed=None):
+    """
+    This function, historically, used to set the seed of the randomization algorithms
+    used in the `scipy.linalg.interpolative` functions written in Fortran77.
+
+    The library has been ported to Python and now the functions use the native NumPy
+    generators and this function has no content and returns None. Thus this function
+    should not be used and will be removed in SciPy version 1.17.0.
+    """
+    warnings.warn("`scipy.linalg.interpolative.seed` is deprecated and will be "
+                  "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3)
+
+
+def rand(*shape):
+    """
+    This function, historically, used to generate uniformly distributed random number
+    for the randomization algorithms used in the `scipy.linalg.interpolative` functions
+    written in Fortran77.
+
+    The library has been ported to Python and now the functions use the native NumPy
+    generators. Thus this function should not be used and will be removed in the
+    SciPy version 1.17.0.
+
+    If pseudo-random numbers are needed, NumPy pseudo-random generators should be used
+    instead.
+
+    Parameters
+    ----------
+    *shape
+        Shape of output array
+
+    """
+    warnings.warn("`scipy.linalg.interpolative.rand` is deprecated and will be "
+                  "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3)
+    rng = np.random.default_rng()
+    return rng.uniform(low=0., high=1.0, size=shape)
+
+
+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.
+    """
+    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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/lapack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d15cf4d72d19f4b7949cd80bc77aa31553841c1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/lapack.py
@@ -0,0 +1,1061 @@
+"""
+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`.
+
+Finding functions
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   get_lapack_funcs
+
+All functions
+-------------
+
+.. autosummary::
+   :toctree: generated/
+
+   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
+
+   chetrs
+   zhetrs
+
+   chfrk
+   zhfrk
+
+   slamch
+   dlamch
+
+   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
+
+   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
+
+   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
+from scipy.linalg import _flapack
+from re import compile as regex_compile
+try:
+    from scipy.linalg import _clapack
+except ImportError:
+    _clapack = None
+
+try:
+    from scipy.linalg import _flapack_64
+    HAS_ILP64 = True
+except ImportError:
+    HAS_ILP64 = False
+    _flapack_64 = None
+
+
+# Expose all functions (only flapack --- clapack is an implementation detail)
+empty_module = None
+from scipy.linalg._flapack import *  # noqa: E402, F403
+del empty_module
+
+__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,
+                ssyevx, dsyevx, cheevx, zheevx,
+                ssygvd, dsygvd, chegvd, zhegvd]:
+    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=False):
+    """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: False
+
+    Returns
+    -------
+    funcs : list
+        List containing the found function(s).
+
+    Notes
+    -----
+    This routine automatically chooses between Fortran/C
+    interfaces. Fortran code is used whenever possible for arrays with
+    column major order. In all other cases, C code is preferred.
+
+    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'
+
+    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("Invalid value for 'ilp64'")
+
+    if not ilp64:
+        return _get_funcs(names, arrays, dtype,
+                          "LAPACK", _flapack, _clapack,
+                          "flapack", "clapack", _lapack_alias,
+                          ilp64=False)
+    else:
+        if not HAS_ILP64:
+            raise RuntimeError("LAPACK ILP64 routine requested, but Scipy "
+                               "compiled only with 32-bit BLAS")
+        return _get_funcs(names, arrays, dtype,
+                          "LAPACK", _flapack_64, None,
+                          "flapack_64", None, _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("Internal work array size computation failed: "
+                         "%d" % (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
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/matfuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ec8123b3ad8df096d5791c29bb28cce8271d4ad
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/misc.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fad087489c6a24c8e33df54b811b6c37a3a46d4
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/special_matrices.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..a881ce765dfa3a3c4c2853c405f8129aafc615b5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/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', 'kron', '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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..3954d08791cceb3a2b66669fe3c0ec4180089208
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+#cython: language_level=3
+#cython: boundscheck=False
+#cython: wraparound=False
+
+cimport scipy.linalg
+from scipy.linalg.cython_blas cimport 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 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:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..88f23170ac0bbe382d8470bd22a42a92d9473008
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build
@@ -0,0 +1,27 @@
+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.0.8')
+  error('tests requires Cython >= 3.0.8')
+endif
+
+py3.extension_module(
+  'extending',
+  'extending.pyx',
+  install: false,
+  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'],
+  cpp_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this
+)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe51dcc21824ae122a17376940d43e34ec9ac22c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py
@@ -0,0 +1,2059 @@
+import itertools
+
+import numpy as np
+from numpy import (arange, array, dot, zeros, identity, conjugate, transpose,
+                   float32)
+from numpy.random import random
+
+from numpy.testing import (assert_equal, assert_almost_equal, assert_,
+                           assert_array_almost_equal, assert_allclose,
+                           assert_array_equal, suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import (solve, inv, det, lstsq, pinv, pinvh, norm,
+                          solve_banded, solveh_banded, solve_triangular,
+                          solve_circulant, circulant, LinAlgError, block_diag,
+                          matrix_balance, qr, LinAlgWarning)
+
+from scipy.linalg._testutils import assert_no_overwrite
+from scipy._lib._testutils import check_free_memory, IS_MUSL
+from scipy.linalg.blas import HAS_ILP64
+
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+def _eps_cast(dtyp):
+    """Get the epsilon for dtype, possibly downcast to BLAS types."""
+    dt = dtyp
+    if dt == np.longdouble:
+        dt = np.float64
+    elif dt == np.clongdouble:
+        dt = np.complex128
+    return np.finfo(dt).eps
+
+
+class TestSolveBanded:
+
+    def test_real(self):
+        a = array([[1.0, 20, 0, 0],
+                   [-30, 4, 6, 0],
+                   [2, 1, 20, 2],
+                   [0, -1, 7, 14]])
+        ab = array([[0.0, 20, 6, 2],
+                    [1, 4, 20, 14],
+                    [-30, 1, 7, 0],
+                    [2, -1, 0, 0]])
+        l, u = 2, 1
+        b4 = array([10.0, 0.0, 2.0, 14.0])
+        b4by1 = b4.reshape(-1, 1)
+        b4by2 = array([[2, 1],
+                       [-30, 4],
+                       [2, 3],
+                       [1, 3]])
+        b4by4 = array([[1, 0, 0, 0],
+                       [0, 0, 0, 1],
+                       [0, 1, 0, 0],
+                       [0, 1, 0, 0]])
+        for b in [b4, b4by1, b4by2, b4by4]:
+            x = solve_banded((l, u), ab, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_complex(self):
+        a = array([[1.0, 20, 0, 0],
+                   [-30, 4, 6, 0],
+                   [2j, 1, 20, 2j],
+                   [0, -1, 7, 14]])
+        ab = array([[0.0, 20, 6, 2j],
+                    [1, 4, 20, 14],
+                    [-30, 1, 7, 0],
+                    [2j, -1, 0, 0]])
+        l, u = 2, 1
+        b4 = array([10.0, 0.0, 2.0, 14.0j])
+        b4by1 = b4.reshape(-1, 1)
+        b4by2 = array([[2, 1],
+                       [-30, 4],
+                       [2, 3],
+                       [1, 3]])
+        b4by4 = array([[1, 0, 0, 0],
+                       [0, 0, 0, 1j],
+                       [0, 1, 0, 0],
+                       [0, 1, 0, 0]])
+        for b in [b4, b4by1, b4by2, b4by4]:
+            x = solve_banded((l, u), ab, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_tridiag_real(self):
+        ab = array([[0.0, 20, 6, 2],
+                   [1, 4, 20, 14],
+                   [-30, 1, 7, 0]])
+        a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag(
+                                                                ab[2, :-1], -1)
+        b4 = array([10.0, 0.0, 2.0, 14.0])
+        b4by1 = b4.reshape(-1, 1)
+        b4by2 = array([[2, 1],
+                       [-30, 4],
+                       [2, 3],
+                       [1, 3]])
+        b4by4 = array([[1, 0, 0, 0],
+                       [0, 0, 0, 1],
+                       [0, 1, 0, 0],
+                       [0, 1, 0, 0]])
+        for b in [b4, b4by1, b4by2, b4by4]:
+            x = solve_banded((1, 1), ab, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_tridiag_complex(self):
+        ab = array([[0.0, 20, 6, 2j],
+                   [1, 4, 20, 14],
+                   [-30, 1, 7, 0]])
+        a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag(
+                                                               ab[2, :-1], -1)
+        b4 = array([10.0, 0.0, 2.0, 14.0j])
+        b4by1 = b4.reshape(-1, 1)
+        b4by2 = array([[2, 1],
+                       [-30, 4],
+                       [2, 3],
+                       [1, 3]])
+        b4by4 = array([[1, 0, 0, 0],
+                       [0, 0, 0, 1],
+                       [0, 1, 0, 0],
+                       [0, 1, 0, 0]])
+        for b in [b4, b4by1, b4by2, b4by4]:
+            x = solve_banded((1, 1), ab, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_check_finite(self):
+        a = array([[1.0, 20, 0, 0],
+                   [-30, 4, 6, 0],
+                   [2, 1, 20, 2],
+                   [0, -1, 7, 14]])
+        ab = array([[0.0, 20, 6, 2],
+                    [1, 4, 20, 14],
+                    [-30, 1, 7, 0],
+                    [2, -1, 0, 0]])
+        l, u = 2, 1
+        b4 = array([10.0, 0.0, 2.0, 14.0])
+        x = solve_banded((l, u), ab, b4, check_finite=False)
+        assert_array_almost_equal(dot(a, x), b4)
+
+    def test_bad_shape(self):
+        ab = array([[0.0, 20, 6, 2],
+                    [1, 4, 20, 14],
+                    [-30, 1, 7, 0],
+                    [2, -1, 0, 0]])
+        l, u = 2, 1
+        bad = array([1.0, 2.0, 3.0, 4.0]).reshape(-1, 4)
+        assert_raises(ValueError, solve_banded, (l, u), ab, bad)
+        assert_raises(ValueError, solve_banded, (l, u), ab, [1.0, 2.0])
+
+        # Values of (l,u) are not compatible with ab.
+        assert_raises(ValueError, solve_banded, (1, 1), ab, [1.0, 2.0])
+
+    def test_1x1(self):
+        # gh-8906 noted that the case of A@x = b with 1x1 A was handled
+        # incorrectly; check that this is resolved. Typical case:
+        # nupper == nlower == 0
+        # A = [[2]]
+        b = array([[1., 2., 3.]])
+        ref = array([[0.5, 1.0, 1.5]])
+        x = solve_banded((0, 0), [[2]], b)
+        assert_allclose(x, ref, rtol=1e-15)
+
+        # However, the user *can* represent the same system with garbage rows
+        # in `ab`. Test the case with `nupper == 1, nlower == 1`.
+        x = solve_banded((1, 1), [[0], [2], [0]], b)
+        assert_allclose(x, ref, rtol=1e-15)
+        assert_equal(x.dtype, np.dtype('f8'))
+        assert_array_equal(b, [[1.0, 2.0, 3.0]])
+
+    def test_native_list_arguments(self):
+        a = [[1.0, 20, 0, 0],
+             [-30, 4, 6, 0],
+             [2, 1, 20, 2],
+             [0, -1, 7, 14]]
+        ab = [[0.0, 20, 6, 2],
+              [1, 4, 20, 14],
+              [-30, 1, 7, 0],
+              [2, -1, 0, 0]]
+        l, u = 2, 1
+        b = [10.0, 0.0, 2.0, 14.0]
+        x = solve_banded((l, u), ab, b)
+        assert_array_almost_equal(dot(a, x), b)
+
+    @pytest.mark.thread_unsafe  # due to Cython fused types, see cython#6506
+    @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_ab, dt_b):
+        # ab contains one empty row corresponding to the diagonal
+        ab = np.array([[]], dtype=dt_ab)
+        b = np.array([], dtype=dt_b)
+        x = solve_banded((0, 0), ab, b)
+
+        assert x.shape == (0,)
+        assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+        b = np.empty((0, 0), dtype=dt_b)
+        x = solve_banded((0, 0), ab, b)
+
+        assert x.shape == (0, 0)
+        assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+
+class TestSolveHBanded:
+
+    def test_01_upper(self):
+        # Solve
+        # [ 4 1 2 0]     [1]
+        # [ 1 4 1 2] X = [4]
+        # [ 2 1 4 1]     [1]
+        # [ 0 2 1 4]     [2]
+        # with the RHS as a 1D array.
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0, 2.0])
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+    def test_02_upper(self):
+        # Solve
+        # [ 4 1 2 0]     [1 6]
+        # [ 1 4 1 2] X = [4 2]
+        # [ 2 1 4 1]     [1 6]
+        # [ 0 2 1 4]     [2 1]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([[1.0, 6.0],
+                   [4.0, 2.0],
+                   [1.0, 6.0],
+                   [2.0, 1.0]])
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0],
+                          [0.0, 0.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_03_upper(self):
+        # Solve
+        # [ 4 1 2 0]     [1]
+        # [ 1 4 1 2] X = [4]
+        # [ 2 1 4 1]     [1]
+        # [ 0 2 1 4]     [2]
+        # with the RHS as a 2D array with shape (3,1).
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0, 2.0]).reshape(-1, 1)
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, array([0., 1., 0., 0.]).reshape(-1, 1))
+
+    def test_01_lower(self):
+        # Solve
+        # [ 4 1 2 0]     [1]
+        # [ 1 4 1 2] X = [4]
+        # [ 2 1 4 1]     [1]
+        # [ 0 2 1 4]     [2]
+        #
+        ab = array([[4.0, 4.0, 4.0, 4.0],
+                    [1.0, 1.0, 1.0, -99],
+                    [2.0, 2.0, 0.0, 0.0]])
+        b = array([1.0, 4.0, 1.0, 2.0])
+        x = solveh_banded(ab, b, lower=True)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+    def test_02_lower(self):
+        # Solve
+        # [ 4 1 2 0]     [1 6]
+        # [ 1 4 1 2] X = [4 2]
+        # [ 2 1 4 1]     [1 6]
+        # [ 0 2 1 4]     [2 1]
+        #
+        ab = array([[4.0, 4.0, 4.0, 4.0],
+                    [1.0, 1.0, 1.0, -99],
+                    [2.0, 2.0, 0.0, 0.0]])
+        b = array([[1.0, 6.0],
+                   [4.0, 2.0],
+                   [1.0, 6.0],
+                   [2.0, 1.0]])
+        x = solveh_banded(ab, b, lower=True)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0],
+                          [0.0, 0.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_01_float32(self):
+        # Solve
+        # [ 4 1 2 0]     [1]
+        # [ 1 4 1 2] X = [4]
+        # [ 2 1 4 1]     [1]
+        # [ 0 2 1 4]     [2]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]], dtype=float32)
+        b = array([1.0, 4.0, 1.0, 2.0], dtype=float32)
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+    def test_02_float32(self):
+        # Solve
+        # [ 4 1 2 0]     [1 6]
+        # [ 1 4 1 2] X = [4 2]
+        # [ 2 1 4 1]     [1 6]
+        # [ 0 2 1 4]     [2 1]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]], dtype=float32)
+        b = array([[1.0, 6.0],
+                   [4.0, 2.0],
+                   [1.0, 6.0],
+                   [2.0, 1.0]], dtype=float32)
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0],
+                          [0.0, 0.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_01_complex(self):
+        # Solve
+        # [ 4 -j  2  0]     [2-j]
+        # [ j  4 -j  2] X = [4-j]
+        # [ 2  j  4 -j]     [4+j]
+        # [ 0  2  j  4]     [2+j]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, -1.0j, -1.0j, -1.0j],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([2-1.0j, 4.0-1j, 4+1j, 2+1j])
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0])
+
+    def test_02_complex(self):
+        # Solve
+        # [ 4 -j  2  0]     [2-j 2+4j]
+        # [ j  4 -j  2] X = [4-j -1-j]
+        # [ 2  j  4 -j]     [4+j 4+2j]
+        # [ 0  2  j  4]     [2+j j]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, -1.0j, -1.0j, -1.0j],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([[2-1j, 2+4j],
+                   [4.0-1j, -1-1j],
+                   [4.0+1j, 4+2j],
+                   [2+1j, 1j]])
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0j],
+                          [1.0, 0.0],
+                          [1.0, 1.0],
+                          [0.0, 0.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_tridiag_01_upper(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        # with the RHS as a 1D array.
+        ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0])
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+    def test_tridiag_02_upper(self):
+        # Solve
+        # [ 4 1 0]     [1 4]
+        # [ 1 4 1] X = [4 2]
+        # [ 0 1 4]     [1 4]
+        #
+        ab = array([[-99, 1.0, 1.0],
+                    [4.0, 4.0, 4.0]])
+        b = array([[1.0, 4.0],
+                   [4.0, 2.0],
+                   [1.0, 4.0]])
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_tridiag_03_upper(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        # with the RHS as a 2D array with shape (3,1).
+        ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0]).reshape(-1, 1)
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1))
+
+    def test_tridiag_01_lower(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        #
+        ab = array([[4.0, 4.0, 4.0],
+                    [1.0, 1.0, -99]])
+        b = array([1.0, 4.0, 1.0])
+        x = solveh_banded(ab, b, lower=True)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+    def test_tridiag_02_lower(self):
+        # Solve
+        # [ 4 1 0]     [1 4]
+        # [ 1 4 1] X = [4 2]
+        # [ 0 1 4]     [1 4]
+        #
+        ab = array([[4.0, 4.0, 4.0],
+                    [1.0, 1.0, -99]])
+        b = array([[1.0, 4.0],
+                   [4.0, 2.0],
+                   [1.0, 4.0]])
+        x = solveh_banded(ab, b, lower=True)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_tridiag_01_float32(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        #
+        ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
+        b = array([1.0, 4.0, 1.0], dtype=float32)
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+    def test_tridiag_02_float32(self):
+        # Solve
+        # [ 4 1 0]     [1 4]
+        # [ 1 4 1] X = [4 2]
+        # [ 0 1 4]     [1 4]
+        #
+        ab = array([[-99, 1.0, 1.0],
+                    [4.0, 4.0, 4.0]], dtype=float32)
+        b = array([[1.0, 4.0],
+                   [4.0, 2.0],
+                   [1.0, 4.0]], dtype=float32)
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_tridiag_01_complex(self):
+        # Solve
+        # [ 4 -j 0]     [ -j]
+        # [ j 4 -j] X = [4-j]
+        # [ 0 j  4]     [4+j]
+        #
+        ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
+        b = array([-1.0j, 4.0-1j, 4+1j])
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 1.0])
+
+    def test_tridiag_02_complex(self):
+        # Solve
+        # [ 4 -j 0]     [ -j    4j]
+        # [ j 4 -j] X = [4-j  -1-j]
+        # [ 0 j  4]     [4+j   4  ]
+        #
+        ab = array([[-99, -1.0j, -1.0j],
+                    [4.0, 4.0, 4.0]])
+        b = array([[-1j, 4.0j],
+                   [4.0-1j, -1.0-1j],
+                   [4.0+1j, 4.0]])
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0j],
+                          [1.0, 0.0],
+                          [1.0, 1.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_check_finite(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        # with the RHS as a 1D array.
+        ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0])
+        x = solveh_banded(ab, b, check_finite=False)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+    def test_bad_shapes(self):
+        ab = array([[-99, 1.0, 1.0],
+                    [4.0, 4.0, 4.0]])
+        b = array([[1.0, 4.0],
+                   [4.0, 2.0]])
+        assert_raises(ValueError, solveh_banded, ab, b)
+        assert_raises(ValueError, solveh_banded, ab, [1.0, 2.0])
+        assert_raises(ValueError, solveh_banded, ab, [1.0])
+
+    def test_1x1(self):
+        x = solveh_banded([[1]], [[1, 2, 3]])
+        assert_array_equal(x, [[1.0, 2.0, 3.0]])
+        assert_equal(x.dtype, np.dtype('f8'))
+
+    def test_native_list_arguments(self):
+        # Same as test_01_upper, using python's native list.
+        ab = [[0.0, 0.0, 2.0, 2.0],
+              [-99, 1.0, 1.0, 1.0],
+              [4.0, 4.0, 4.0, 4.0]]
+        b = [1.0, 4.0, 1.0, 2.0]
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+    @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_ab, dt_b):
+        # ab contains one empty row corresponding to the diagonal
+        ab = np.array([[]], dtype=dt_ab)
+        b = np.array([], dtype=dt_b)
+        x = solveh_banded(ab, b)
+
+        assert x.shape == (0,)
+        assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+        b = np.empty((0, 0), dtype=dt_b)
+        x = solveh_banded(ab, b)
+
+        assert x.shape == (0, 0)
+        assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+
+class TestSolve:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.thread_unsafe
+    def test_20Feb04_bug(self):
+        a = [[1, 1], [1.0, 0]]  # ok
+        x0 = solve(a, [1, 0j])
+        assert_array_almost_equal(dot(a, x0), [1, 0])
+
+        # gives failure with clapack.zgesv(..,rowmajor=0)
+        a = [[1, 1], [1.2, 0]]
+        b = [1, 0j]
+        x0 = solve(a, b)
+        assert_array_almost_equal(dot(a, x0), [1, 0])
+
+    def test_simple(self):
+        a = [[1, 20], [-30, 4]]
+        for b in ([[1, 0], [0, 1]],
+                  [1, 0],
+                  [[2, 1], [-30, 4]]
+                  ):
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_complex(self):
+        a = array([[5, 2], [2j, 4]], 'D')
+        for b in ([1j, 0],
+                  [[1j, 1j], [0, 2]],
+                  [1, 0j],
+                  array([1, 0], 'D'),
+                  ):
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_pos(self):
+        a = [[2, 3], [3, 5]]
+        for lower in [0, 1]:
+            for b in ([[1, 0], [0, 1]],
+                      [1, 0]
+                      ):
+                x = solve(a, b, assume_a='pos', lower=lower)
+                assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_pos_complexb(self):
+        a = [[5, 2], [2, 4]]
+        for b in ([1j, 0],
+                  [[1j, 1j], [0, 2]],
+                  ):
+            x = solve(a, b, assume_a='pos')
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_sym(self):
+        a = [[2, 3], [3, -5]]
+        for lower in [0, 1]:
+            for b in ([[1, 0], [0, 1]],
+                      [1, 0]
+                      ):
+                x = solve(a, b, assume_a='sym', lower=lower)
+                assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_sym_complexb(self):
+        a = [[5, 2], [2, -4]]
+        for b in ([1j, 0],
+                  [[1j, 1j], [0, 2]]
+                  ):
+            x = solve(a, b, assume_a='sym')
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_sym_complex(self):
+        a = [[5, 2+1j], [2+1j, -4]]
+        for b in ([1j, 0],
+                  [1, 0],
+                  [[1j, 1j], [0, 2]]
+                  ):
+            x = solve(a, b, assume_a='sym')
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_her_actuallysym(self):
+        a = [[2, 3], [3, -5]]
+        for lower in [0, 1]:
+            for b in ([[1, 0], [0, 1]],
+                      [1, 0],
+                      [1j, 0],
+                      ):
+                x = solve(a, b, assume_a='her', lower=lower)
+                assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_her(self):
+        a = [[5, 2+1j], [2-1j, -4]]
+        for b in ([1j, 0],
+                  [1, 0],
+                  [[1j, 1j], [0, 2]]
+                  ):
+            x = solve(a, b, assume_a='her')
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_nils_20Feb04(self):
+        n = 2
+        A = random([n, n])+random([n, n])*1j
+        X = zeros((n, n), 'D')
+        Ainv = inv(A)
+        R = identity(n)+identity(n)*0j
+        for i in arange(0, n):
+            r = R[:, i]
+            X[:, i] = solve(A, r)
+        assert_array_almost_equal(X, Ainv)
+
+    def test_random(self):
+
+        n = 20
+        a = random([n, n])
+        for i in range(n):
+            a[i, i] = 20*(.1+a[i, i])
+        for i in range(4):
+            b = random([n, 3])
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_complex(self):
+        n = 20
+        a = random([n, n]) + 1j * random([n, n])
+        for i in range(n):
+            a[i, i] = 20*(.1+a[i, i])
+        for i in range(2):
+            b = random([n, 3])
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_sym(self):
+        n = 20
+        a = random([n, n])
+        for i in range(n):
+            a[i, i] = abs(20*(.1+a[i, i]))
+            for j in range(i):
+                a[i, j] = a[j, i]
+        for i in range(4):
+            b = random([n])
+            x = solve(a, b, assume_a="pos")
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_sym_complex(self):
+        n = 20
+        a = random([n, n])
+        a = a + 1j*random([n, n])
+        for i in range(n):
+            a[i, i] = abs(20*(.1+a[i, i]))
+            for j in range(i):
+                a[i, j] = conjugate(a[j, i])
+        b = random([n])+2j*random([n])
+        for i in range(2):
+            x = solve(a, b, assume_a="pos")
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_check_finite(self):
+        a = [[1, 20], [-30, 4]]
+        for b in ([[1, 0], [0, 1]], [1, 0],
+                  [[2, 1], [-30, 4]]):
+            x = solve(a, b, check_finite=False)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_scalar_a_and_1D_b(self):
+        a = 1
+        b = [1, 2, 3]
+        x = solve(a, b)
+        assert_array_almost_equal(x.ravel(), b)
+        assert_(x.shape == (3,), 'Scalar_a_1D_b test returned wrong shape')
+
+    def test_simple2(self):
+        a = np.array([[1.80, 2.88, 2.05, -0.89],
+                      [525.00, -295.00, -95.00, -380.00],
+                      [1.58, -2.69, -2.90, -1.04],
+                      [-1.11, -0.66, -0.59, 0.80]])
+
+        b = np.array([[9.52, 18.47],
+                      [2435.00, 225.00],
+                      [0.77, -13.28],
+                      [-6.22, -6.21]])
+
+        x = solve(a, b)
+        assert_array_almost_equal(x, np.array([[1., -1, 3, -5],
+                                               [3, 2, 4, 1]]).T)
+
+    def test_simple_complex2(self):
+        a = np.array([[-1.34+2.55j, 0.28+3.17j, -6.39-2.20j, 0.72-0.92j],
+                      [-1.70-14.10j, 33.10-1.50j, -1.50+13.40j, 12.90+13.80j],
+                      [-3.29-2.39j, -1.91+4.42j, -0.14-1.35j, 1.72+1.35j],
+                      [2.41+0.39j, -0.56+1.47j, -0.83-0.69j, -1.96+0.67j]])
+
+        b = np.array([[26.26+51.78j, 31.32-6.70j],
+                      [64.30-86.80j, 158.60-14.20j],
+                      [-5.75+25.31j, -2.15+30.19j],
+                      [1.16+2.57j, -2.56+7.55j]])
+
+        x = solve(a, b)
+        assert_array_almost_equal(x, np. array([[1+1.j, -1-2.j],
+                                                [2-3.j, 5+1.j],
+                                                [-4-5.j, -3+4.j],
+                                                [6.j, 2-3.j]]))
+
+    def test_hermitian(self):
+        # An upper triangular matrix will be used for hermitian matrix a
+        a = np.array([[-1.84, 0.11-0.11j, -1.78-1.18j, 3.91-1.50j],
+                      [0, -4.63, -1.84+0.03j, 2.21+0.21j],
+                      [0, 0, -8.87, 1.58-0.90j],
+                      [0, 0, 0, -1.36]])
+        b = np.array([[2.98-10.18j, 28.68-39.89j],
+                      [-9.58+3.88j, -24.79-8.40j],
+                      [-0.77-16.05j, 4.23-70.02j],
+                      [7.79+5.48j, -35.39+18.01j]])
+        res = np.array([[2.+1j, -8+6j],
+                        [3.-2j, 7-2j],
+                        [-1+2j, -1+5j],
+                        [1.-1j, 3-4j]])
+        x = solve(a, b, assume_a='her')
+        assert_array_almost_equal(x, res)
+        # Also conjugate a and test for lower triangular data
+        x = solve(a.conj().T, b, assume_a='her', lower=True)
+        assert_array_almost_equal(x, res)
+
+    def test_pos_and_sym(self):
+        A = np.arange(1, 10).reshape(3, 3)
+        x = solve(np.tril(A)/9, np.ones(3), assume_a='pos')
+        assert_array_almost_equal(x, [9., 1.8, 1.])
+        x = solve(np.tril(A)/9, np.ones(3), assume_a='sym')
+        assert_array_almost_equal(x, [9., 1.8, 1.])
+
+    def test_singularity(self):
+        a = np.array([[1, 0, 0, 0, 0, 0, 1, 0, 1],
+                      [1, 1, 1, 0, 0, 0, 1, 0, 1],
+                      [0, 1, 1, 0, 0, 0, 1, 0, 1],
+                      [1, 0, 1, 1, 1, 1, 0, 0, 0],
+                      [1, 0, 1, 1, 1, 1, 0, 0, 0],
+                      [1, 0, 1, 1, 1, 1, 0, 0, 0],
+                      [1, 0, 1, 1, 1, 1, 0, 0, 0],
+                      [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                      [1, 1, 1, 1, 1, 1, 1, 1, 1]])
+        b = np.arange(9)[:, None]
+        assert_raises(LinAlgError, solve, a, b)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize('structure',
+                             ('diagonal', 'tridiagonal', 'lower triangular',
+                              'upper triangular', 'symmetric', 'hermitian',
+                              'positive definite', 'general', None))
+    def test_ill_condition_warning(self, structure):
+        rng = np.random.default_rng(234859349452)
+        n = 10
+        d = np.logspace(0, 50, n)
+        A = np.diag(d)
+        b = rng.random(size=n)
+        message = "Ill-conditioned matrix..."
+        with pytest.warns(LinAlgWarning, match=message):
+            solve(A, b, assume_a=structure)
+
+    def test_multiple_rhs(self):
+        a = np.eye(2)
+        b = np.random.rand(2, 3, 4)
+        x = solve(a, b)
+        assert_array_almost_equal(x, b)
+
+    def test_transposed_keyword(self):
+        A = np.arange(9).reshape(3, 3) + 1
+        x = solve(np.tril(A)/9, np.ones(3), transposed=True)
+        assert_array_almost_equal(x, [1.2, 0.2, 1])
+        x = solve(np.tril(A)/9, np.ones(3), transposed=False)
+        assert_array_almost_equal(x, [9, -5.4, -1.2])
+
+    def test_transposed_notimplemented(self):
+        a = np.eye(3).astype(complex)
+        with assert_raises(NotImplementedError):
+            solve(a, a, transposed=True)
+
+    def test_nonsquare_a(self):
+        assert_raises(ValueError, solve, [1, 2], 1)
+
+    def test_size_mismatch_with_1D_b(self):
+        assert_array_almost_equal(solve(np.eye(3), np.ones(3)), np.ones(3))
+        assert_raises(ValueError, solve, np.eye(3), np.ones(4))
+
+    def test_assume_a_keyword(self):
+        assert_raises(ValueError, solve, 1, 1, assume_a='zxcv')
+
+    @pytest.mark.skip(reason="Failure on OS X (gh-7500), "
+                             "crash on Windows (gh-8064)")
+    def test_all_type_size_routine_combinations(self):
+        sizes = [10, 100]
+        assume_as = ['gen', 'sym', 'pos', 'her']
+        dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+        for size, assume_a, dtype in itertools.product(sizes, assume_as,
+                                                       dtypes):
+            is_complex = dtype in (np.complex64, np.complex128)
+            if assume_a == 'her' and not is_complex:
+                continue
+
+            err_msg = (f"Failed for size: {size}, assume_a: {assume_a},"
+                       f"dtype: {dtype}")
+
+            a = np.random.randn(size, size).astype(dtype)
+            b = np.random.randn(size).astype(dtype)
+            if is_complex:
+                a = a + (1j*np.random.randn(size, size)).astype(dtype)
+
+            if assume_a == 'sym':  # Can still be complex but only symmetric
+                a = a + a.T
+            elif assume_a == 'her':  # Handle hermitian matrices here instead
+                a = a + a.T.conj()
+            elif assume_a == 'pos':
+                a = a.conj().T.dot(a) + 0.1*np.eye(size)
+
+            tol = 1e-12 if dtype in (np.float64, np.complex128) else 1e-6
+
+            if assume_a in ['gen', 'sym', 'her']:
+                # We revert the tolerance from before
+                #   4b4a6e7c34fa4060533db38f9a819b98fa81476c
+                if dtype in (np.float32, np.complex64):
+                    tol *= 10
+
+            x = solve(a, b, assume_a=assume_a)
+            assert_allclose(a.dot(x), b,
+                            atol=tol * size,
+                            rtol=tol * size,
+                            err_msg=err_msg)
+
+            if assume_a == 'sym' and dtype not in (np.complex64,
+                                                   np.complex128):
+                x = solve(a, b, assume_a=assume_a, transposed=True)
+                assert_allclose(a.dot(x), b,
+                                atol=tol * size,
+                                rtol=tol * size,
+                                err_msg=err_msg)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_a, dt_b):
+        a = np.empty((0, 0), dtype=dt_a)
+        b = np.empty(0, dtype=dt_b)
+        x = solve(a, b)
+
+        assert x.size == 0
+        dt_nonempty = solve(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)).dtype
+        assert x.dtype == dt_nonempty
+
+    def test_empty_rhs(self):
+        a = np.eye(2)
+        b = [[], []]
+        x = solve(a, b)
+        assert_(x.size == 0, 'Returned array is not empty')
+        assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
+
+    @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+    # "pos" and "positive definite" need to be added
+    @pytest.mark.parametrize('assume_a', ['diagonal', 'tridiagonal', 'banded',
+                                          'lower triangular', 'upper triangular',
+                                          'symmetric', 'hermitian',
+                                          'general', 'sym', 'her', 'gen'])
+    @pytest.mark.parametrize('nrhs', [(), (5,)])
+    @pytest.mark.parametrize('transposed', [True, False])
+    @pytest.mark.parametrize('overwrite', [True, False])
+    @pytest.mark.parametrize('fortran', [True, False])
+    def test_structure_detection(self, dtype, assume_a, nrhs, transposed,
+                                 overwrite, fortran):
+        rng = np.random.default_rng(982345982439826)
+        n = 5 if not assume_a == 'banded' else 20
+        b = rng.random(size=(n,) + nrhs)
+        A = rng.random(size=(n, n))
+
+        if np.issubdtype(dtype, np.complexfloating):
+            b = b + rng.random(size=(n,) + nrhs) * 1j
+            A = A + rng.random(size=(n, n)) * 1j
+
+        if assume_a == 'diagonal':
+            A = np.diag(np.diag(A))
+        elif assume_a == 'lower triangular':
+            A = np.tril(A)
+        elif assume_a == 'upper triangular':
+            A = np.triu(A)
+        elif assume_a == 'tridiagonal':
+            A = (np.diag(np.diag(A))
+                 + np.diag(np.diag(A, -1), -1)
+                 + np.diag(np.diag(A, 1), 1))
+        elif assume_a == 'banded':
+            A = np.triu(np.tril(A, 2), -1)
+        elif assume_a in {'symmetric', 'sym'}:
+            A = A + A.T
+        elif assume_a in {'hermitian', 'her'}:
+            A = A + A.conj().T
+        elif assume_a in {'positive definite', 'pos'}:
+            A = A + A.T
+            A += np.diag(A.sum(axis=1))
+
+        if fortran:
+            A = np.asfortranarray(A)
+
+        A_copy = A.copy(order='A')
+        b_copy = b.copy()
+
+        if np.issubdtype(dtype, np.complexfloating) and transposed:
+            message = "scipy.linalg.solve can currently..."
+            with pytest.raises(NotImplementedError, match=message):
+                solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite,
+                      transposed=transposed)
+            return
+
+        res = solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite,
+                    transposed=transposed, assume_a=assume_a)
+
+        # Check that solution this solution is *correct*
+        ref = np.linalg.solve(A_copy.T if transposed else A_copy, b_copy)
+        assert_allclose(res, ref)
+
+        # Check that `solve` correctly identifies the structure and returns
+        # *exactly* the same solution whether `assume_a` is specified or not
+        if assume_a != 'banded':  # structure detection removed for banded
+            assert_equal(solve(A_copy, b_copy, transposed=transposed), res)
+
+        # Check that overwrite was respected
+        if not overwrite:
+            assert_equal(A, A_copy)
+            assert_equal(b, b_copy)
+
+
+class TestSolveTriangular:
+
+    def test_simple(self):
+        """
+        solve_triangular on a simple 2x2 matrix.
+        """
+        A = array([[1, 0], [1, 2]])
+        b = [1, 1]
+        sol = solve_triangular(A, b, lower=True)
+        assert_array_almost_equal(sol, [1, 0])
+
+        # check that it works also for non-contiguous matrices
+        sol = solve_triangular(A.T, b, lower=False)
+        assert_array_almost_equal(sol, [.5, .5])
+
+        # and that it gives the same result as trans=1
+        sol = solve_triangular(A, b, lower=True, trans=1)
+        assert_array_almost_equal(sol, [.5, .5])
+
+        b = identity(2)
+        sol = solve_triangular(A, b, lower=True, trans=1)
+        assert_array_almost_equal(sol, [[1., -.5], [0, 0.5]])
+
+    def test_simple_complex(self):
+        """
+        solve_triangular on a simple 2x2 complex matrix
+        """
+        A = array([[1+1j, 0], [1j, 2]])
+        b = identity(2)
+        sol = solve_triangular(A, b, lower=True, trans=1)
+        assert_array_almost_equal(sol, [[.5-.5j, -.25-.25j], [0, 0.5]])
+
+        # check other option combinations with complex rhs
+        b = np.diag([1+1j, 1+2j])
+        sol = solve_triangular(A, b, lower=True, trans=0)
+        assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
+
+        sol = solve_triangular(A, b, lower=True, trans=1)
+        assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
+
+        sol = solve_triangular(A, b, lower=True, trans=2)
+        assert_array_almost_equal(sol, [[1j, -0.75-0.25j], [0, 0.5+1j]])
+
+        sol = solve_triangular(A.T, b, lower=False, trans=0)
+        assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
+
+        sol = solve_triangular(A.T, b, lower=False, trans=1)
+        assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
+
+        sol = solve_triangular(A.T, b, lower=False, trans=2)
+        assert_array_almost_equal(sol, [[1j, 0], [-0.5, 0.5+1j]])
+
+    def test_check_finite(self):
+        """
+        solve_triangular on a simple 2x2 matrix.
+        """
+        A = array([[1, 0], [1, 2]])
+        b = [1, 1]
+        sol = solve_triangular(A, b, lower=True, check_finite=False)
+        assert_array_almost_equal(sol, [1, 0])
+
+    @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_a, dt_b):
+        a = np.empty((0, 0), dtype=dt_a)
+        b = np.empty(0, dtype=dt_b)
+        x = solve_triangular(a, b)
+
+        assert x.size == 0
+        dt_nonempty = solve_triangular(
+            np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)
+        ).dtype
+        assert x.dtype == dt_nonempty
+
+    def test_empty_rhs(self):
+        a = np.eye(2)
+        b = [[], []]
+        x = solve_triangular(a, b)
+        assert_(x.size == 0, 'Returned array is not empty')
+        assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
+
+
+class TestInv:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_simple(self):
+        a = [[1, 2], [3, 4]]
+        a_inv = inv(a)
+        assert_array_almost_equal(dot(a, a_inv), np.eye(2))
+        a = [[1, 2, 3], [4, 5, 6], [7, 8, 10]]
+        a_inv = inv(a)
+        assert_array_almost_equal(dot(a, a_inv), np.eye(3))
+
+    def test_random(self):
+        n = 20
+        for i in range(4):
+            a = random([n, n])
+            for i in range(n):
+                a[i, i] = 20*(.1+a[i, i])
+            a_inv = inv(a)
+            assert_array_almost_equal(dot(a, a_inv),
+                                      identity(n))
+
+    def test_simple_complex(self):
+        a = [[1, 2], [3, 4j]]
+        a_inv = inv(a)
+        assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
+
+    def test_random_complex(self):
+        n = 20
+        for i in range(4):
+            a = random([n, n])+2j*random([n, n])
+            for i in range(n):
+                a[i, i] = 20*(.1+a[i, i])
+            a_inv = inv(a)
+            assert_array_almost_equal(dot(a, a_inv),
+                                      identity(n))
+
+    def test_check_finite(self):
+        a = [[1, 2], [3, 4]]
+        a_inv = inv(a, check_finite=False)
+        assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        a_inv = inv(a)
+        assert a_inv.size == 0
+        assert a_inv.dtype == inv(np.eye(2, dtype=dt)).dtype
+
+
+class TestDet:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1680305949878959)
+
+    def test_1x1_all_singleton_dims(self):
+        a = np.array([[1]])
+        deta = det(a)
+        assert deta.dtype.char == 'd'
+        assert np.isscalar(deta)
+        assert deta == 1.
+        a = np.array([[[[1]]]], dtype='f')
+        deta = det(a)
+        assert deta.dtype.char == 'd'
+        assert deta.shape == (1, 1)
+        assert_equal(deta, [[1.0]])
+        a = np.array([[[1 + 3.j]]], dtype=np.complex64)
+        deta = det(a)
+        assert deta.dtype.char == 'D'
+        assert deta.shape == (1,)
+        assert_equal(deta, [1.+3.j])
+
+    def test_1by1_stacked_input_output(self):
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
+        deta = det(a)
+        assert deta.dtype.char == 'd'
+        assert deta.shape == (4, 5)
+        assert_allclose(deta, np.squeeze(a))
+
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j)
+        deta = det(a)
+        assert deta.dtype.char == 'D'
+        assert deta.shape == (4, 5)
+        assert_allclose(deta, np.squeeze(a))
+
+    @pytest.mark.parametrize('shape', [[2, 2], [20, 20], [3, 2, 20, 20]])
+    def test_simple_det_shapes_real_complex(self, shape):
+        a = self.rng.uniform(-1., 1., size=shape)
+        d1, d2 = det(a), np.linalg.det(a)
+        assert_allclose(d1, d2)
+
+        b = self.rng.uniform(-1., 1., size=shape)*1j
+        b += self.rng.uniform(-0.5, 0.5, size=shape)
+        d3, d4 = det(b), np.linalg.det(b)
+        assert_allclose(d3, d4)
+
+    def test_for_known_det_values(self):
+        # Hadamard8
+        a = np.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]])
+        assert_allclose(det(a), 4096.)
+
+        # consecutive number array always singular
+        assert_allclose(det(np.arange(25).reshape(5, 5)), 0.)
+
+        # simple anti-diagonal block array
+        # Upper right has det (-2+1j) and lower right has (-2-1j)
+        # det(a) = - (-2+1j) (-2-1j) = 5.
+        a = np.array([[0.+0.j, 0.+0.j, 0.-1.j, 1.-1.j],
+                      [0.+0.j, 0.+0.j, 1.+0.j, 0.-1.j],
+                      [0.+1.j, 1.+1.j, 0.+0.j, 0.+0.j],
+                      [1.+0.j, 0.+1.j, 0.+0.j, 0.+0.j]], dtype=np.complex64)
+        assert_allclose(det(a), 5.+0.j)
+
+        # Fiedler companion complexified
+        # >>> a = scipy.linalg.fiedler_companion(np.arange(1, 10))
+        a = np.array([[-2., -3., 1., 0., 0., 0., 0., 0.],
+                      [1., 0., 0., 0., 0., 0., 0., 0.],
+                      [0., -4., 0., -5., 1., 0., 0., 0.],
+                      [0., 1., 0., 0., 0., 0., 0., 0.],
+                      [0., 0., 0., -6., 0., -7., 1., 0.],
+                      [0., 0., 0., 1., 0., 0., 0., 0.],
+                      [0., 0., 0., 0., 0., -8., 0., -9.],
+                      [0., 0., 0., 0., 0., 1., 0., 0.]])*1.j
+        assert_allclose(det(a), 9.)
+
+    # g and G dtypes are handled differently in windows and other platforms
+    @pytest.mark.parametrize('typ', [x for x in np.typecodes['All'][:20]
+                                     if x not in 'gG'])
+    def test_sample_compatible_dtype_input(self, typ):
+        n = 4
+        a = self.rng.random([n, n]).astype(typ)  # value is not important
+        assert isinstance(det(a), (np.float64 | np.complex128))
+
+    def test_incompatible_dtype_input(self):
+        # Double backslashes needed for escaping pytest regex.
+        msg = 'cannot be cast to float\\(32, 64\\)'
+
+        for c, t in zip('SUO', ['bytes8', 'str32', 'object']):
+            with assert_raises(TypeError, match=msg):
+                det(np.array([['a', 'b']]*2, dtype=c))
+        with assert_raises(TypeError, match=msg):
+            det(np.array([[b'a', b'b']]*2, dtype='V'))
+        with assert_raises(TypeError, match=msg):
+            det(np.array([[100, 200]]*2, dtype='datetime64[s]'))
+        with assert_raises(TypeError, match=msg):
+            det(np.array([[100, 200]]*2, dtype='timedelta64[s]'))
+
+    def test_empty_edge_cases(self):
+        assert_allclose(det(np.empty([0, 0])), 1.)
+        assert_allclose(det(np.empty([0, 0, 0])), np.array([]))
+        assert_allclose(det(np.empty([3, 0, 0])), np.array([1., 1., 1.]))
+        with assert_raises(ValueError, match='Last 2 dimensions'):
+            det(np.empty([0, 0, 3]))
+        with assert_raises(ValueError, match='at least two-dimensional'):
+            det(np.array([]))
+        with assert_raises(ValueError, match='Last 2 dimensions'):
+            det(np.array([[]]))
+        with assert_raises(ValueError, match='Last 2 dimensions'):
+            det(np.array([[[]]]))
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty_dtype(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        d = det(a)
+        assert d.shape == ()
+        assert d.dtype == det(np.eye(2, dtype=dt)).dtype
+
+        a = np.empty((3, 0, 0), dtype=dt)
+        d = det(a)
+        assert d.shape == (3,)
+        assert d.dtype == det(np.zeros((3, 1, 1), dtype=dt)).dtype
+
+    def test_overwrite_a(self):
+        # If all conditions are met then input should be overwritten;
+        #   - dtype is one of 'fdFD'
+        #   - C-contiguous
+        #   - writeable
+        a = np.arange(9).reshape(3, 3).astype(np.float32)
+        ac = a.copy()
+        deta = det(ac, overwrite_a=True)
+        assert_allclose(deta, 0.)
+        assert not (a == ac).all()
+
+    def test_readonly_array(self):
+        a = np.array([[2., 0., 1.], [5., 3., -1.], [1., 1., 1.]])
+        a.setflags(write=False)
+        # overwrite_a will be overridden
+        assert_allclose(det(a, overwrite_a=True), 10.)
+
+    def test_simple_check_finite(self):
+        a = [[1, 2], [3, np.inf]]
+        with assert_raises(ValueError, match='array must not contain'):
+            det(a)
+
+
+def direct_lstsq(a, b, cmplx=0):
+    at = transpose(a)
+    if cmplx:
+        at = conjugate(at)
+    a1 = dot(at, a)
+    b1 = dot(at, b)
+    return solve(a1, b1)
+
+
+class TestLstsq:
+    lapack_drivers = ('gelsd', 'gelss', 'gelsy', None)
+
+    def test_simple_exact(self):
+        for dtype in REAL_DTYPES:
+            a = np.array([[1, 20], [-30, 4]], dtype=dtype)
+            for lapack_driver in TestLstsq.lapack_drivers:
+                for overwrite in (True, False):
+                    for bt in (((1, 0), (0, 1)), (1, 0),
+                               ((2, 1), (-30, 4))):
+                        # Store values in case they are overwritten
+                        # later
+                        a1 = a.copy()
+                        b = np.array(bt, dtype=dtype)
+                        b1 = b.copy()
+                        out = lstsq(a1, b1,
+                                    lapack_driver=lapack_driver,
+                                    overwrite_a=overwrite,
+                                    overwrite_b=overwrite)
+                        x = out[0]
+                        r = out[2]
+                        assert_(r == 2,
+                                f'expected efficient rank 2, got {r}')
+                        assert_allclose(dot(a, x), b,
+                                        atol=25 * _eps_cast(a1.dtype),
+                                        rtol=25 * _eps_cast(a1.dtype),
+                                        err_msg=f"driver: {lapack_driver}")
+
+    def test_simple_overdet(self):
+        for dtype in REAL_DTYPES:
+            a = np.array([[1, 2], [4, 5], [3, 4]], dtype=dtype)
+            b = np.array([1, 2, 3], dtype=dtype)
+            for lapack_driver in TestLstsq.lapack_drivers:
+                for overwrite in (True, False):
+                    # Store values in case they are overwritten later
+                    a1 = a.copy()
+                    b1 = b.copy()
+                    out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                                overwrite_a=overwrite,
+                                overwrite_b=overwrite)
+                    x = out[0]
+                    if lapack_driver == 'gelsy':
+                        residuals = np.sum((b - a.dot(x))**2)
+                    else:
+                        residuals = out[1]
+                    r = out[2]
+                    assert_(r == 2, f'expected efficient rank 2, got {r}')
+                    assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0),
+                                    residuals,
+                                    rtol=25 * _eps_cast(a1.dtype),
+                                    atol=25 * _eps_cast(a1.dtype),
+                                    err_msg=f"driver: {lapack_driver}")
+                    assert_allclose(x, (-0.428571428571429, 0.85714285714285),
+                                    rtol=25 * _eps_cast(a1.dtype),
+                                    atol=25 * _eps_cast(a1.dtype),
+                                    err_msg=f"driver: {lapack_driver}")
+
+    def test_simple_overdet_complex(self):
+        for dtype in COMPLEX_DTYPES:
+            a = np.array([[1+2j, 2], [4, 5], [3, 4]], dtype=dtype)
+            b = np.array([1, 2+4j, 3], dtype=dtype)
+            for lapack_driver in TestLstsq.lapack_drivers:
+                for overwrite in (True, False):
+                    # Store values in case they are overwritten later
+                    a1 = a.copy()
+                    b1 = b.copy()
+                    out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                                overwrite_a=overwrite,
+                                overwrite_b=overwrite)
+
+                    x = out[0]
+                    if lapack_driver == 'gelsy':
+                        res = b - a.dot(x)
+                        residuals = np.sum(res * res.conj())
+                    else:
+                        residuals = out[1]
+                    r = out[2]
+                    assert_(r == 2, f'expected efficient rank 2, got {r}')
+                    assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0),
+                                    residuals,
+                                    rtol=25 * _eps_cast(a1.dtype),
+                                    atol=25 * _eps_cast(a1.dtype),
+                                    err_msg=f"driver: {lapack_driver}")
+                    assert_allclose(
+                                x, (-0.4831460674157303 + 0.258426966292135j,
+                                    0.921348314606741 + 0.292134831460674j),
+                                rtol=25 * _eps_cast(a1.dtype),
+                                atol=25 * _eps_cast(a1.dtype),
+                                err_msg=f"driver: {lapack_driver}")
+
+    def test_simple_underdet(self):
+        for dtype in REAL_DTYPES:
+            a = np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype)
+            b = np.array([1, 2], dtype=dtype)
+            for lapack_driver in TestLstsq.lapack_drivers:
+                for overwrite in (True, False):
+                    # Store values in case they are overwritten later
+                    a1 = a.copy()
+                    b1 = b.copy()
+                    out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                                overwrite_a=overwrite,
+                                overwrite_b=overwrite)
+
+                    x = out[0]
+                    r = out[2]
+                    assert_(r == 2, f'expected efficient rank 2, got {r}')
+                    assert_allclose(x, (-0.055555555555555, 0.111111111111111,
+                                        0.277777777777777),
+                                    rtol=25 * _eps_cast(a1.dtype),
+                                    atol=25 * _eps_cast(a1.dtype),
+                                    err_msg=f"driver: {lapack_driver}")
+
+    @pytest.mark.parametrize("dtype", REAL_DTYPES)
+    @pytest.mark.parametrize("n", (20, 200))
+    @pytest.mark.parametrize("lapack_driver", lapack_drivers)
+    @pytest.mark.parametrize("overwrite", (True, False))
+    def test_random_exact(self, dtype, n, lapack_driver, overwrite):
+        rng = np.random.RandomState(1234)
+
+        a = np.asarray(rng.random([n, n]), dtype=dtype)
+        for i in range(n):
+            a[i, i] = 20 * (0.1 + a[i, i])
+        for i in range(4):
+            b = np.asarray(rng.random([n, 3]), dtype=dtype)
+            # Store values in case they are overwritten later
+            a1 = a.copy()
+            b1 = b.copy()
+            out = lstsq(a1, b1,
+                        lapack_driver=lapack_driver,
+                        overwrite_a=overwrite,
+                        overwrite_b=overwrite)
+            x = out[0]
+            r = out[2]
+            assert_(r == n, f'expected efficient rank {n}, '
+                    f'got {r}')
+            if dtype is np.float32:
+                assert_allclose(
+                          dot(a, x), b,
+                          rtol=500 * _eps_cast(a1.dtype),
+                          atol=500 * _eps_cast(a1.dtype),
+                          err_msg=f"driver: {lapack_driver}")
+            else:
+                assert_allclose(
+                          dot(a, x), b,
+                          rtol=1000 * _eps_cast(a1.dtype),
+                          atol=1000 * _eps_cast(a1.dtype),
+                          err_msg=f"driver: {lapack_driver}")
+
+    @pytest.mark.skipif(IS_MUSL, reason="may segfault on Alpine, see gh-17630")
+    @pytest.mark.parametrize("dtype", COMPLEX_DTYPES)
+    @pytest.mark.parametrize("n", (20, 200))
+    @pytest.mark.parametrize("lapack_driver", lapack_drivers)
+    @pytest.mark.parametrize("overwrite", (True, False))
+    def test_random_complex_exact(self, dtype, n, lapack_driver, overwrite):
+        rng = np.random.RandomState(1234)
+
+        a = np.asarray(rng.random([n, n]) + 1j*rng.random([n, n]),
+                       dtype=dtype)
+        for i in range(n):
+            a[i, i] = 20 * (0.1 + a[i, i])
+        for i in range(2):
+            b = np.asarray(rng.random([n, 3]), dtype=dtype)
+            # Store values in case they are overwritten later
+            a1 = a.copy()
+            b1 = b.copy()
+            out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                        overwrite_a=overwrite,
+                        overwrite_b=overwrite)
+            x = out[0]
+            r = out[2]
+            assert_(r == n, f'expected efficient rank {n}, '
+                    f'got {r}')
+            if dtype is np.complex64:
+                assert_allclose(
+                          dot(a, x), b,
+                          rtol=400 * _eps_cast(a1.dtype),
+                          atol=400 * _eps_cast(a1.dtype),
+                          err_msg=f"driver: {lapack_driver}")
+            else:
+                assert_allclose(
+                          dot(a, x), b,
+                          rtol=1000 * _eps_cast(a1.dtype),
+                          atol=1000 * _eps_cast(a1.dtype),
+                          err_msg=f"driver: {lapack_driver}")
+
+    def test_random_overdet(self):
+        rng = np.random.RandomState(1234)
+        for dtype in REAL_DTYPES:
+            for (n, m) in ((20, 15), (200, 2)):
+                for lapack_driver in TestLstsq.lapack_drivers:
+                    for overwrite in (True, False):
+                        a = np.asarray(rng.random([n, m]), dtype=dtype)
+                        for i in range(m):
+                            a[i, i] = 20 * (0.1 + a[i, i])
+                        for i in range(4):
+                            b = np.asarray(rng.random([n, 3]), dtype=dtype)
+                            # Store values in case they are overwritten later
+                            a1 = a.copy()
+                            b1 = b.copy()
+                            out = lstsq(a1, b1,
+                                        lapack_driver=lapack_driver,
+                                        overwrite_a=overwrite,
+                                        overwrite_b=overwrite)
+                            x = out[0]
+                            r = out[2]
+                            assert_(r == m, f'expected efficient rank {m}, '
+                                    f'got {r}')
+                            assert_allclose(
+                                          x, direct_lstsq(a, b, cmplx=0),
+                                          rtol=25 * _eps_cast(a1.dtype),
+                                          atol=25 * _eps_cast(a1.dtype),
+                                          err_msg=f"driver: {lapack_driver}")
+
+    def test_random_complex_overdet(self):
+        rng = np.random.RandomState(1234)
+        for dtype in COMPLEX_DTYPES:
+            for (n, m) in ((20, 15), (200, 2)):
+                for lapack_driver in TestLstsq.lapack_drivers:
+                    for overwrite in (True, False):
+                        a = np.asarray(rng.random([n, m]) + 1j*rng.random([n, m]),
+                                       dtype=dtype)
+                        for i in range(m):
+                            a[i, i] = 20 * (0.1 + a[i, i])
+                        for i in range(2):
+                            b = np.asarray(rng.random([n, 3]), dtype=dtype)
+                            # Store values in case they are overwritten
+                            # later
+                            a1 = a.copy()
+                            b1 = b.copy()
+                            out = lstsq(a1, b1,
+                                        lapack_driver=lapack_driver,
+                                        overwrite_a=overwrite,
+                                        overwrite_b=overwrite)
+                            x = out[0]
+                            r = out[2]
+                            assert_(r == m, f'expected efficient rank {m}, '
+                                    f'got {r}')
+                            assert_allclose(
+                                      x, direct_lstsq(a, b, cmplx=1),
+                                      rtol=25 * _eps_cast(a1.dtype),
+                                      atol=25 * _eps_cast(a1.dtype),
+                                      err_msg=f"driver: {lapack_driver}")
+
+    def test_check_finite(self):
+        with suppress_warnings() as sup:
+            # On (some) OSX this tests triggers a warning (gh-7538)
+            sup.filter(RuntimeWarning,
+                       "internal gelsd driver lwork query error,.*"
+                       "Falling back to 'gelss' driver.")
+
+        at = np.array(((1, 20), (-30, 4)))
+        for dtype, bt, lapack_driver, overwrite, check_finite in \
+            itertools.product(REAL_DTYPES,
+                              (((1, 0), (0, 1)), (1, 0), ((2, 1), (-30, 4))),
+                              TestLstsq.lapack_drivers,
+                              (True, False),
+                              (True, False)):
+
+            a = at.astype(dtype)
+            b = np.array(bt, dtype=dtype)
+            # Store values in case they are overwritten
+            # later
+            a1 = a.copy()
+            b1 = b.copy()
+            out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                        check_finite=check_finite, overwrite_a=overwrite,
+                        overwrite_b=overwrite)
+            x = out[0]
+            r = out[2]
+            assert_(r == 2, f'expected efficient rank 2, got {r}')
+            assert_allclose(dot(a, x), b,
+                            rtol=25 * _eps_cast(a.dtype),
+                            atol=25 * _eps_cast(a.dtype),
+                            err_msg=f"driver: {lapack_driver}")
+
+    def test_empty(self):
+        for a_shape, b_shape in (((0, 2), (0,)),
+                                 ((0, 4), (0, 2)),
+                                 ((4, 0), (4,)),
+                                 ((4, 0), (4, 2))):
+            b = np.ones(b_shape)
+            x, residues, rank, s = lstsq(np.zeros(a_shape), b)
+            assert_equal(x, np.zeros((a_shape[1],) + b_shape[1:]))
+            residues_should_be = (np.empty((0,)) if a_shape[1]
+                                  else np.linalg.norm(b, axis=0)**2)
+            assert_equal(residues, residues_should_be)
+            assert_(rank == 0, 'expected rank 0')
+            assert_equal(s, np.empty((0,)))
+
+    @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty_dtype(self, dt_a, dt_b):
+        a = np.empty((0, 0), dtype=dt_a)
+        b = np.empty(0, dtype=dt_b)
+        x, residues, rank, s = lstsq(a, b)
+
+        assert x.size == 0
+        dt_nonempty = lstsq(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b))[0].dtype
+        assert x.dtype == dt_nonempty
+
+
+class TestPinv:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_simple_real(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+        a_pinv = pinv(a)
+        assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+    def test_simple_complex(self):
+        a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]],
+             dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]],
+                                       dtype=float))
+        a_pinv = pinv(a)
+        assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+    def test_simple_singular(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
+        a_pinv = pinv(a)
+        expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01],
+                          [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02],
+                          [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]])
+        assert_array_almost_equal(a_pinv, expected)
+
+    def test_simple_cols(self):
+        a = array([[1, 2, 3], [4, 5, 6]], dtype=float)
+        a_pinv = pinv(a)
+        expected = array([[-0.94444444, 0.44444444],
+                          [-0.11111111, 0.11111111],
+                          [0.72222222, -0.22222222]])
+        assert_array_almost_equal(a_pinv, expected)
+
+    def test_simple_rows(self):
+        a = array([[1, 2], [3, 4], [5, 6]], dtype=float)
+        a_pinv = pinv(a)
+        expected = array([[-1.33333333, -0.33333333, 0.66666667],
+                          [1.08333333, 0.33333333, -0.41666667]])
+        assert_array_almost_equal(a_pinv, expected)
+
+    def test_check_finite(self):
+        a = array([[1, 2, 3], [4, 5, 6.], [7, 8, 10]])
+        a_pinv = pinv(a, check_finite=False)
+        assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+    def test_native_list_argument(self):
+        a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+        a_pinv = pinv(a)
+        expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01],
+                          [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02],
+                          [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]])
+        assert_array_almost_equal(a_pinv, expected)
+
+    def test_atol_rtol(self):
+        n = 12
+        # get a random ortho matrix for shuffling
+        q, _ = qr(np.random.rand(n, n))
+        a_m = np.arange(35.0).reshape(7, 5)
+        a = a_m.copy()
+        a[0, 0] = 0.001
+        atol = 1e-5
+        rtol = 0.05
+        # svds of a_m is ~ [116.906, 4.234, tiny, tiny, tiny]
+        # svds of a is ~ [116.906, 4.234, 4.62959e-04, tiny, tiny]
+        # Just abs cutoff such that we arrive at a_modified
+        a_p = pinv(a_m, atol=atol, rtol=0.)
+        adiff1 = a @ a_p @ a - a
+        adiff2 = a_m @ a_p @ a_m - a_m
+        # Now adiff1 should be around atol value while adiff2 should be
+        # relatively tiny
+        assert_allclose(np.linalg.norm(adiff1), 5e-4, atol=5.e-4)
+        assert_allclose(np.linalg.norm(adiff2), 5e-14, atol=5.e-14)
+
+        # Now do the same but remove another sv ~4.234 via rtol
+        a_p = pinv(a_m, atol=atol, rtol=rtol)
+        adiff1 = a @ a_p @ a - a
+        adiff2 = a_m @ a_p @ a_m - a_m
+        assert_allclose(np.linalg.norm(adiff1), 4.233, rtol=0.01)
+        assert_allclose(np.linalg.norm(adiff2), 4.233, rtol=0.01)
+
+    @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        a_pinv = pinv(a)
+        assert a_pinv.size == 0
+        assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype
+
+
+class TestPinvSymmetric:
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_simple_real(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+        a = np.dot(a, a.T)
+        a_pinv = pinvh(a)
+        assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+    def test_nonpositive(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
+        a = np.dot(a, a.T)
+        u, s, vt = np.linalg.svd(a)
+        s[0] *= -1
+        a = np.dot(u * s, vt)  # a is now symmetric non-positive and singular
+        a_pinv = pinv(a)
+        a_pinvh = pinvh(a)
+        assert_array_almost_equal(a_pinv, a_pinvh)
+
+    def test_simple_complex(self):
+        a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]],
+             dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]],
+                                       dtype=float))
+        a = np.dot(a, a.conj().T)
+        a_pinv = pinvh(a)
+        assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+    def test_native_list_argument(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+        a = np.dot(a, a.T)
+        a_pinv = pinvh(a.tolist())
+        assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+    def test_zero_eigenvalue(self):
+        # https://github.com/scipy/scipy/issues/12515
+        # the SYEVR eigh driver may give the zero eigenvalue > eps
+        a = np.array([[1, -1, 0], [-1, 2, -1], [0, -1, 1]])
+        p = pinvh(a)
+        assert_allclose(p @ a @ p, p, atol=1e-15)
+        assert_allclose(a @ p @ a, a, atol=1e-15)
+
+    def test_atol_rtol(self):
+        n = 12
+        # get a random ortho matrix for shuffling
+        q, _ = qr(np.random.rand(n, n))
+        a = np.diag([4, 3, 2, 1, 0.99e-4, 0.99e-5] + [0.99e-6]*(n-6))
+        a = q.T @ a @ q
+        a_m = np.diag([4, 3, 2, 1, 0.99e-4, 0.] + [0.]*(n-6))
+        a_m = q.T @ a_m @ q
+        atol = 1e-5
+        rtol = (4.01e-4 - 4e-5)/4
+        # Just abs cutoff such that we arrive at a_modified
+        a_p = pinvh(a, atol=atol, rtol=0.)
+        adiff1 = a @ a_p @ a - a
+        adiff2 = a_m @ a_p @ a_m - a_m
+        # Now adiff1 should dance around atol value since truncation
+        # while adiff2 should be relatively tiny
+        assert_allclose(norm(adiff1), atol, rtol=0.1)
+        assert_allclose(norm(adiff2), 1e-12, atol=1e-11)
+
+        # Now do the same but through rtol cancelling atol value
+        a_p = pinvh(a, atol=atol, rtol=rtol)
+        adiff1 = a @ a_p @ a - a
+        adiff2 = a_m @ a_p @ a_m - a_m
+        # adiff1 and adiff2 should be elevated to ~1e-4 due to mismatch
+        assert_allclose(norm(adiff1), 1e-4, rtol=0.1)
+        assert_allclose(norm(adiff2), 1e-4, rtol=0.1)
+
+    @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        a_pinv = pinvh(a)
+        assert a_pinv.size == 0
+        assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype
+
+
+@pytest.mark.parametrize('scale', (1e-20, 1., 1e20))
+@pytest.mark.parametrize('pinv_', (pinv, pinvh))
+def test_auto_rcond(scale, pinv_):
+    x = np.array([[1, 0], [0, 1e-10]]) * scale
+    expected = np.diag(1. / np.diag(x))
+    x_inv = pinv_(x)
+    assert_allclose(x_inv, expected)
+
+
+class TestVectorNorms:
+
+    def test_types(self):
+        for dtype in np.typecodes['AllFloat']:
+            x = np.array([1, 2, 3], dtype=dtype)
+            tol = max(1e-15, np.finfo(dtype).eps.real * 20)
+            assert_allclose(norm(x), np.sqrt(14), rtol=tol)
+            assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
+
+        for dtype in np.typecodes['Complex']:
+            x = np.array([1j, 2j, 3j], dtype=dtype)
+            tol = max(1e-15, np.finfo(dtype).eps.real * 20)
+            assert_allclose(norm(x), np.sqrt(14), rtol=tol)
+            assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
+
+    def test_overflow(self):
+        # unlike numpy's norm, this one is
+        # safer on overflow
+        a = array([1e20], dtype=float32)
+        assert_almost_equal(norm(a), a)
+
+    def test_stable(self):
+        # more stable than numpy's norm
+        a = array([1e4] + [1]*10000, dtype=float32)
+        try:
+            # snrm in double precision; we obtain the same as for float64
+            # -- large atol needed due to varying blas implementations
+            assert_allclose(norm(a) - 1e4, 0.5, atol=1e-2)
+        except AssertionError:
+            # snrm implemented in single precision, == np.linalg.norm result
+            msg = ": Result should equal either 0.0 or 0.5 (depending on " \
+                  "implementation of snrm2)."
+            assert_almost_equal(norm(a) - 1e4, 0.0, err_msg=msg)
+
+    def test_zero_norm(self):
+        assert_equal(norm([1, 0, 3], 0), 2)
+        assert_equal(norm([1, 2, 3], 0), 3)
+
+    def test_axis_kwd(self):
+        a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+        assert_allclose(norm(a, axis=1), [[3.60555128, 4.12310563]] * 2)
+        assert_allclose(norm(a, 1, axis=1), [[5.] * 2] * 2)
+
+    def test_keepdims_kwd(self):
+        a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+        b = norm(a, axis=1, keepdims=True)
+        assert_allclose(b, [[[3.60555128, 4.12310563]]] * 2)
+        assert_(b.shape == (2, 1, 2))
+        assert_allclose(norm(a, 1, axis=2, keepdims=True), [[[3.], [7.]]] * 2)
+
+    @pytest.mark.skipif(not HAS_ILP64, reason="64-bit BLAS required")
+    def test_large_vector(self):
+        check_free_memory(free_mb=17000)
+        x = np.zeros([2**31], dtype=np.float64)
+        x[-1] = 1
+        res = norm(x)
+        del x
+        assert_allclose(res, 1.0)
+
+
+class TestMatrixNorms:
+
+    def test_matrix_norms(self):
+        # Not all of these are matrix norms in the most technical sense.
+        np.random.seed(1234)
+        for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4):
+            for t in np.float32, np.float64, np.complex64, np.complex128, np.int64:
+                A = 10 * np.random.randn(n, m).astype(t)
+                if np.issubdtype(A.dtype, np.complexfloating):
+                    A = (A + 10j * np.random.randn(n, m)).astype(t)
+                    t_high = np.complex128
+                else:
+                    t_high = np.float64
+                for order in (None, 'fro', 1, -1, 2, -2, np.inf, -np.inf):
+                    actual = norm(A, ord=order)
+                    desired = np.linalg.norm(A, ord=order)
+                    # SciPy may return higher precision matrix norms.
+                    # This is a consequence of using LAPACK.
+                    if not np.allclose(actual, desired):
+                        desired = np.linalg.norm(A.astype(t_high), ord=order)
+                        assert_allclose(actual, desired)
+
+    def test_axis_kwd(self):
+        a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+        b = norm(a, ord=np.inf, axis=(1, 0))
+        c = norm(np.swapaxes(a, 0, 1), ord=np.inf, axis=(0, 1))
+        d = norm(a, ord=1, axis=(0, 1))
+        assert_allclose(b, c)
+        assert_allclose(c, d)
+        assert_allclose(b, d)
+        assert_(b.shape == c.shape == d.shape)
+        b = norm(a, ord=1, axis=(1, 0))
+        c = norm(np.swapaxes(a, 0, 1), ord=1, axis=(0, 1))
+        d = norm(a, ord=np.inf, axis=(0, 1))
+        assert_allclose(b, c)
+        assert_allclose(c, d)
+        assert_allclose(b, d)
+        assert_(b.shape == c.shape == d.shape)
+
+    def test_keepdims_kwd(self):
+        a = np.arange(120, dtype='d').reshape(2, 3, 4, 5)
+        b = norm(a, ord=np.inf, axis=(1, 0), keepdims=True)
+        c = norm(a, ord=1, axis=(0, 1), keepdims=True)
+        assert_allclose(b, c)
+        assert_(b.shape == c.shape)
+
+    def test_empty(self):
+        a = np.empty((0, 0))
+        assert_allclose(norm(a), 0.)
+        assert_allclose(norm(a, axis=0), np.zeros((0,)))
+        assert_allclose(norm(a, keepdims=True), np.zeros((1, 1)))
+
+        a = np.empty((0, 3))
+        assert_allclose(norm(a), 0.)
+        assert_allclose(norm(a, axis=0), np.zeros((3,)))
+        assert_allclose(norm(a, keepdims=True), np.zeros((1, 1)))
+
+
+class TestOverwrite:
+    def test_solve(self):
+        assert_no_overwrite(solve, [(3, 3), (3,)])
+
+    def test_solve_triangular(self):
+        assert_no_overwrite(solve_triangular, [(3, 3), (3,)])
+
+    def test_solve_banded(self):
+        assert_no_overwrite(lambda ab, b: solve_banded((2, 1), ab, b),
+                            [(4, 6), (6,)])
+
+    def test_solveh_banded(self):
+        assert_no_overwrite(solveh_banded, [(2, 6), (6,)])
+
+    def test_inv(self):
+        assert_no_overwrite(inv, [(3, 3)])
+
+    def test_det(self):
+        assert_no_overwrite(det, [(3, 3)])
+
+    def test_lstsq(self):
+        assert_no_overwrite(lstsq, [(3, 2), (3,)])
+
+    def test_pinv(self):
+        assert_no_overwrite(pinv, [(3, 3)])
+
+    def test_pinvh(self):
+        assert_no_overwrite(pinvh, [(3, 3)])
+
+
+class TestSolveCirculant:
+
+    def test_basic1(self):
+        c = np.array([1, 2, 3, 5])
+        b = np.array([1, -1, 1, 0])
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_basic2(self):
+        # b is a 2-d matrix.
+        c = np.array([1, 2, -3, -5])
+        b = np.arange(12).reshape(4, 3)
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_basic3(self):
+        # b is a 3-d matrix.
+        c = np.array([1, 2, -3, -5])
+        b = np.arange(24).reshape(4, 3, 2)
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_complex(self):
+        # Complex b and c
+        c = np.array([1+2j, -3, 4j, 5])
+        b = np.arange(8).reshape(4, 2) + 0.5j
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_random_b_and_c(self):
+        # Random b and c
+        rng = np.random.RandomState(54321)
+        c = rng.randn(50)
+        b = rng.randn(50)
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_singular(self):
+        # c gives a singular circulant matrix.
+        c = np.array([1, 1, 0, 0])
+        b = np.array([1, 2, 3, 4])
+        x = solve_circulant(c, b, singular='lstsq')
+        y, res, rnk, s = lstsq(circulant(c), b)
+        assert_allclose(x, y)
+        assert_raises(LinAlgError, solve_circulant, x, y)
+
+    def test_axis_args(self):
+        # Test use of caxis, baxis and outaxis.
+
+        # c has shape (2, 1, 4)
+        c = np.array([[[-1, 2.5, 3, 3.5]], [[1, 6, 6, 6.5]]])
+
+        # b has shape (3, 4)
+        b = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [1, -1, 0, 0]])
+
+        x = solve_circulant(c, b, baxis=1)
+        assert_equal(x.shape, (4, 2, 3))
+        expected = np.empty_like(x)
+        expected[:, 0, :] = solve(circulant(c[0].ravel()), b.T)
+        expected[:, 1, :] = solve(circulant(c[1].ravel()), b.T)
+        assert_allclose(x, expected)
+
+        x = solve_circulant(c, b, baxis=1, outaxis=-1)
+        assert_equal(x.shape, (2, 3, 4))
+        assert_allclose(np.moveaxis(x, -1, 0), expected)
+
+        # np.swapaxes(c, 1, 2) has shape (2, 4, 1); b.T has shape (4, 3).
+        x = solve_circulant(np.swapaxes(c, 1, 2), b.T, caxis=1)
+        assert_equal(x.shape, (4, 2, 3))
+        assert_allclose(x, expected)
+
+    def test_native_list_arguments(self):
+        # Same as test_basic1 using python's native list.
+        c = [1, 2, 3, 5]
+        b = [1, -1, 1, 0]
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    @pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_c, dt_b):
+        c = np.array([], dtype=dt_c)
+        b = np.array([], dtype=dt_b)
+        x = solve_circulant(c, b)
+        assert x.shape == (0,)
+        assert x.dtype == solve_circulant(np.arange(3, dtype=dt_c),
+                                          np.ones(3, dtype=dt_b)).dtype
+
+        b = np.empty((0, 0), dtype=dt_b)
+        x1 = solve_circulant(c, b)
+        assert x1.shape == (0, 0)
+        assert x1.dtype == x.dtype
+
+
+class TestMatrix_Balance:
+
+    def test_string_arg(self):
+        assert_raises(ValueError, matrix_balance, 'Some string for fail')
+
+    def test_infnan_arg(self):
+        assert_raises(ValueError, matrix_balance,
+                      np.array([[1, 2], [3, np.inf]]))
+        assert_raises(ValueError, matrix_balance,
+                      np.array([[1, 2], [3, np.nan]]))
+
+    def test_scaling(self):
+        _, y = matrix_balance(np.array([[1000, 1], [1000, 0]]))
+        # Pre/post LAPACK 3.5.0 gives the same result up to an offset
+        # since in each case col norm is x1000 greater and
+        # 1000 / 32 ~= 1 * 32 hence balanced with 2 ** 5.
+        assert_allclose(np.diff(np.log2(np.diag(y))), [5])
+
+    def test_scaling_order(self):
+        A = np.array([[1, 0, 1e-4], [1, 1, 1e-2], [1e4, 1e2, 1]])
+        x, y = matrix_balance(A)
+        assert_allclose(solve(y, A).dot(y), x)
+
+    def test_separate(self):
+        _, (y, z) = matrix_balance(np.array([[1000, 1], [1000, 0]]),
+                                   separate=1)
+        assert_equal(np.diff(np.log2(y)), [5])
+        assert_allclose(z, np.arange(2))
+
+    def test_permutation(self):
+        A = block_diag(np.ones((2, 2)), np.tril(np.ones((2, 2))),
+                       np.ones((3, 3)))
+        x, (y, z) = matrix_balance(A, separate=1)
+        assert_allclose(y, np.ones_like(y))
+        assert_allclose(z, np.array([0, 1, 6, 5, 4, 3, 2]))
+
+    def test_perm_and_scaling(self):
+        # Matrix with its diagonal removed
+        cases = (  # Case 0
+                 np.array([[0., 0., 0., 0., 0.000002],
+                           [0., 0., 0., 0., 0.],
+                           [2., 2., 0., 0., 0.],
+                           [2., 2., 0., 0., 0.],
+                           [0., 0., 0.000002, 0., 0.]]),
+                 #  Case 1 user reported GH-7258
+                 np.array([[-0.5, 0., 0., 0.],
+                           [0., -1., 0., 0.],
+                           [1., 0., -0.5, 0.],
+                           [0., 1., 0., -1.]]),
+                 #  Case 2 user reported GH-7258
+                 np.array([[-3., 0., 1., 0.],
+                           [-1., -1., -0., 1.],
+                           [-3., -0., -0., 0.],
+                           [-1., -0., 1., -1.]])
+                 )
+
+        for A in cases:
+            x, y = matrix_balance(A)
+            x, (s, p) = matrix_balance(A, separate=1)
+            ip = np.empty_like(p)
+            ip[p] = np.arange(A.shape[0])
+            assert_allclose(y, np.diag(s)[ip, :])
+            assert_allclose(solve(y, A).dot(y), x)
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        b, t = matrix_balance(a)
+
+        assert b.size == 0
+        assert t.size == 0
+
+        b_n, t_n = matrix_balance(np.eye(2, dtype=dt))
+        assert b.dtype == b_n.dtype
+        assert t.dtype == t_n.dtype
+
+        b, (scale, perm) = matrix_balance(a, separate=True)
+        assert b.size == 0
+        assert scale.size == 0
+        assert perm.size == 0
+
+        b_n, (scale_n, perm_n) = matrix_balance(a, separate=True)
+        assert b.dtype == b_n.dtype
+        assert scale.dtype == scale_n.dtype
+        assert perm.dtype == perm_n.dtype
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6645d0ad5d967ca00a2a5193d51e7ee74b8ad73
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py
@@ -0,0 +1,1127 @@
+#
+# Created by: Pearu Peterson, April 2002
+#
+
+import math
+import pytest
+import numpy as np
+import numpy.random
+from numpy.testing import (assert_equal, assert_almost_equal, assert_,
+                           assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+
+from numpy import float32, float64, complex64, complex128, arange, triu, \
+                  tril, zeros, tril_indices, ones, mod, diag, append, eye, \
+                  nonzero
+
+import scipy
+from scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve
+
+try:
+    from scipy.linalg import _cblas as cblas
+except ImportError:
+    cblas = None
+
+REAL_DTYPES = [float32, float64]
+COMPLEX_DTYPES = [complex64, complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+def test_get_blas_funcs():
+    # check that it returns Fortran code for arrays that are
+    # fortran-ordered
+    f1, f2, f3 = get_blas_funcs(
+        ('axpy', 'axpy', 'axpy'),
+        (np.empty((2, 2), dtype=np.complex64, order='F'),
+         np.empty((2, 2), dtype=np.complex128, order='C'))
+        )
+
+    # get_blas_funcs will choose libraries depending on most generic
+    # array
+    assert_equal(f1.typecode, 'z')
+    assert_equal(f2.typecode, 'z')
+    if cblas is not None:
+        assert_equal(f1.module_name, 'cblas')
+        assert_equal(f2.module_name, 'cblas')
+
+    # check defaults.
+    f1 = get_blas_funcs('rotg')
+    assert_equal(f1.typecode, 'd')
+
+    # check also dtype interface
+    f1 = get_blas_funcs('gemm', dtype=np.complex64)
+    assert_equal(f1.typecode, 'c')
+    f1 = get_blas_funcs('gemm', dtype='F')
+    assert_equal(f1.typecode, 'c')
+
+    # extended precision complex
+    f1 = get_blas_funcs('gemm', dtype=np.clongdouble)
+    assert_equal(f1.typecode, 'z')
+
+    # check safe complex upcasting
+    f1 = get_blas_funcs('axpy',
+                        (np.empty((2, 2), dtype=np.float64),
+                         np.empty((2, 2), dtype=np.complex64))
+                        )
+    assert_equal(f1.typecode, 'z')
+
+
+def test_get_blas_funcs_alias():
+    # check alias for get_blas_funcs
+    f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64)
+    assert f.typecode == 'c'
+    assert g.typecode == 'c'
+
+    f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64)
+    assert f is g
+    assert f is h
+
+
+class TestCBLAS1Simple:
+
+    def test_axpy(self):
+        for p in 'sd':
+            f = getattr(cblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
+                                      [7, 9, 18])
+        for p in 'cz':
+            f = getattr(cblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
+                                      [7, 10j-1, 18])
+
+
+class TestFBLAS1Simple:
+
+    def test_axpy(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
+                                      [7, 9, 18])
+        for p in 'cz':
+            f = getattr(fblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
+                                      [7, 10j-1, 18])
+
+    def test_copy(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'copy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5])
+        for p in 'cz':
+            f = getattr(fblas, p+'copy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j])
+
+    def test_asum(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'asum', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5]), 12)
+        for p in ['sc', 'dz']:
+            f = getattr(fblas, p+'asum', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j]), 14)
+
+    def test_dot(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'dot', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9)
+
+    def test_complex_dotu(self):
+        for p in 'cz':
+            f = getattr(fblas, p+'dotu', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j)
+
+    def test_complex_dotc(self):
+        for p in 'cz':
+            f = getattr(fblas, p+'dotc', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j)
+
+    def test_nrm2(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'nrm2', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5]), math.sqrt(50))
+        for p in ['c', 'z', 'sc', 'dz']:
+            f = getattr(fblas, p+'nrm2', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50))
+
+    def test_scal(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10])
+        for p in 'cz':
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [3j, -4, 3-4j]), [-9, -12j, 12+9j])
+        for p in ['cs', 'zd']:
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j])
+
+    def test_swap(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'swap', None)
+            if f is None:
+                continue
+            x, y = [2, 3, 1], [-2, 3, 7]
+            x1, y1 = f(x, y)
+            assert_array_almost_equal(x1, y)
+            assert_array_almost_equal(y1, x)
+        for p in 'cz':
+            f = getattr(fblas, p+'swap', None)
+            if f is None:
+                continue
+            x, y = [2, 3j, 1], [-2, 3, 7-3j]
+            x1, y1 = f(x, y)
+            assert_array_almost_equal(x1, y)
+            assert_array_almost_equal(y1, x)
+
+    def test_amax(self):
+        for p in 'sd':
+            f = getattr(fblas, 'i'+p+'amax')
+            assert_equal(f([-2, 4, 3]), 1)
+        for p in 'cz':
+            f = getattr(fblas, 'i'+p+'amax')
+            assert_equal(f([-5, 4+3j, 6]), 1)
+    # XXX: need tests for rot,rotm,rotg,rotmg
+
+
+class TestFBLAS2Simple:
+
+    def test_gemv(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'gemv', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [[3]], [-4]), [-36])
+            assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21])
+        for p in 'cz':
+            f = getattr(fblas, p+'gemv', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j])
+            assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]),
+                                      [-48-21j])
+
+    # All of these *ger* functions are segfaulting when called from multiple
+    # threads under free-threaded CPython, see gh-21936.
+    @pytest.mark.thread_unsafe
+    def test_ger(self):
+
+        for p in 'sd':
+            f = getattr(fblas, p+'ger', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]])
+            assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]),
+                                      [[6, 8], [12, 16], [18, 24]])
+
+            assert_array_almost_equal(f(1, [1, 2], [3, 4],
+                                        a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]])
+
+        for p in 'cz':
+            f = getattr(fblas, p+'geru', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
+                                      [[3j, 4j], [6, 8]])
+            assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]),
+                                      [[6, 8], [12, 16], [18, 24]])
+
+        for p in 'cz':
+            for name in ('ger', 'gerc'):
+                f = getattr(fblas, p+name, None)
+                if f is None:
+                    continue
+                assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
+                                          [[3j, 4j], [6, 8]])
+                assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]),
+                                          [[6, 8], [12, 16], [18, 24]])
+
+    def test_syr_her(self):
+        x = np.arange(1, 5, dtype='d')
+        resx = np.triu(x[:, np.newaxis] * x)
+        resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1])
+
+        y = np.linspace(0, 8.5, 17, endpoint=False)
+
+        z = np.arange(1, 9, dtype='d').view('D')
+        resz = np.triu(z[:, np.newaxis] * z)
+        resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1])
+        rehz = np.triu(z[:, np.newaxis] * z.conj())
+        rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj())
+
+        w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
+
+        for p, rtol in zip('sd', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, x), resx, rtol=rtol)
+            assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol)
+            assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, y, incx=-2, offx=2, n=4),
+                            resx_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F')
+            b = f(1.0, x, a=a, overwrite_a=True)
+            assert_allclose(a, resx, rtol=rtol)
+
+            b = f(2.0, x, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*resx, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, incx=0)
+            assert_raises(Exception, f, 1.0, x, offx=5)
+            assert_raises(Exception, f, 1.0, x, offx=-2)
+            assert_raises(Exception, f, 1.0, x, n=-2)
+            assert_raises(Exception, f, 1.0, x, n=5)
+            assert_raises(Exception, f, 1.0, x, lower=2)
+            assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, z), resz, rtol=rtol)
+            assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol)
+            assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
+                            resz_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
+            b = f(1.0, z, a=a, overwrite_a=True)
+            assert_allclose(a, resz, rtol=rtol)
+
+            b = f(2.0, z, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*resz, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, incx=0)
+            assert_raises(Exception, f, 1.0, x, offx=5)
+            assert_raises(Exception, f, 1.0, x, offx=-2)
+            assert_raises(Exception, f, 1.0, x, n=-2)
+            assert_raises(Exception, f, 1.0, x, n=5)
+            assert_raises(Exception, f, 1.0, x, lower=2)
+            assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'her', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, z), rehz, rtol=rtol)
+            assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol)
+            assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
+                            rehz_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
+            b = f(1.0, z, a=a, overwrite_a=True)
+            assert_allclose(a, rehz, rtol=rtol)
+
+            b = f(2.0, z, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*rehz, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, incx=0)
+            assert_raises(Exception, f, 1.0, x, offx=5)
+            assert_raises(Exception, f, 1.0, x, offx=-2)
+            assert_raises(Exception, f, 1.0, x, n=-2)
+            assert_raises(Exception, f, 1.0, x, n=5)
+            assert_raises(Exception, f, 1.0, x, lower=2)
+            assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
+
+    def test_syr2(self):
+        x = np.arange(1, 5, dtype='d')
+        y = np.arange(5, 9, dtype='d')
+        resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x)
+        resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1]
+                                + y[::-1, np.newaxis] * x[::-1])
+
+        q = np.linspace(0, 8.5, 17, endpoint=False)
+
+        for p, rtol in zip('sd', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr2', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
+            assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
+            assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol)
+
+            assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10),
+                            resxy, rtol=rtol)
+            assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3),
+                            resxy[:3, :3], rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10),
+                            resxy_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F')
+            b = f(1.0, x, y, a=a, overwrite_a=True)
+            assert_allclose(a, resxy, rtol=rtol)
+
+            b = f(2.0, x, y, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*resxy, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, y, incx=0)
+            assert_raises(Exception, f, 1.0, x, y, offx=5)
+            assert_raises(Exception, f, 1.0, x, y, offx=-2)
+            assert_raises(Exception, f, 1.0, x, y, incy=0)
+            assert_raises(Exception, f, 1.0, x, y, offy=5)
+            assert_raises(Exception, f, 1.0, x, y, offy=-2)
+            assert_raises(Exception, f, 1.0, x, y, n=-2)
+            assert_raises(Exception, f, 1.0, x, y, n=5)
+            assert_raises(Exception, f, 1.0, x, y, lower=2)
+            assert_raises(Exception, f, 1.0, x, y,
+                          a=np.zeros((2, 2), 'd', 'F'))
+
+    def test_her2(self):
+        x = np.arange(1, 9, dtype='d').view('D')
+        y = np.arange(9, 17, dtype='d').view('D')
+        resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj()
+        resxy = np.triu(resxy)
+
+        resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj()
+        resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj()
+        resxy_reverse = np.triu(resxy_reverse)
+
+        u = np.c_[np.zeros(4), x, np.zeros(4)].ravel()
+        v = np.c_[np.zeros(4), y, np.zeros(4)].ravel()
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'her2', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
+            assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
+            assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(),
+                            rtol=rtol)
+
+            assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1),
+                            resxy, rtol=rtol)
+            assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3),
+                            resxy[:3, :3], rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1),
+                            resxy_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
+            b = f(1.0, x, y, a=a, overwrite_a=True)
+            assert_allclose(a, resxy, rtol=rtol)
+
+            b = f(2.0, x, y, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*resxy, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, y, incx=0)
+            assert_raises(Exception, f, 1.0, x, y, offx=5)
+            assert_raises(Exception, f, 1.0, x, y, offx=-2)
+            assert_raises(Exception, f, 1.0, x, y, incy=0)
+            assert_raises(Exception, f, 1.0, x, y, offy=5)
+            assert_raises(Exception, f, 1.0, x, y, offy=-2)
+            assert_raises(Exception, f, 1.0, x, y, n=-2)
+            assert_raises(Exception, f, 1.0, x, y, n=5)
+            assert_raises(Exception, f, 1.0, x, y, lower=2)
+            assert_raises(Exception, f, 1.0, x, y,
+                          a=np.zeros((2, 2), 'd', 'F'))
+
+    def test_gbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 7
+            m = 5
+            kl = 1
+            ku = 2
+            # fake a banded matrix via toeplitz
+            A = toeplitz(append(rng.random(kl+1), zeros(m-kl-1)),
+                         append(rng.random(ku+1), zeros(n-ku-1)))
+            A = A.astype(dtype)
+            Ab = zeros((kl+ku+1, n), dtype=dtype)
+
+            # Form the banded storage
+            Ab[2, :5] = A[0, 0]  # diag
+            Ab[1, 1:6] = A[0, 1]  # sup1
+            Ab[0, 2:7] = A[0, 2]  # sup2
+            Ab[3, :4] = A[1, 0]  # sub1
+
+            x = rng.random(n).astype(dtype)
+            y = rng.random(m).astype(dtype)
+            alpha, beta = dtype(3), dtype(-5)
+
+            func, = get_blas_funcs(('gbmv',), dtype=dtype)
+            y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
+                      x=x, y=y, beta=beta)
+            y2 = alpha * A.dot(x) + beta * y
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
+                      x=y, y=x, beta=beta, trans=1)
+            y2 = alpha * A.T.dot(y) + beta * x
+            assert_array_almost_equal(y1, y2)
+
+    def test_sbmv_hbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 6
+            k = 2
+            A = zeros((n, n), dtype=dtype)
+            Ab = zeros((k+1, n), dtype=dtype)
+
+            # Form the array and its packed banded storage
+            A[arange(n), arange(n)] = rng.random(n)
+            for ind2 in range(1, k+1):
+                temp = rng.random(n-ind2)
+                A[arange(n-ind2), arange(ind2, n)] = temp
+                Ab[-1-ind2, ind2:] = temp
+            A = A.astype(dtype)
+            A = A + A.T if ind < 2 else A + A.conj().T
+            Ab[-1, :] = diag(A)
+            x = rng.random(n).astype(dtype)
+            y = rng.random(n).astype(dtype)
+            alpha, beta = dtype(1.25), dtype(3)
+
+            if ind > 1:
+                func, = get_blas_funcs(('hbmv',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('sbmv',), dtype=dtype)
+            y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta)
+            y2 = alpha * A.dot(x) + beta * y
+            assert_array_almost_equal(y1, y2)
+
+    def test_spmv_hpmv(self):
+        rng = np.random.default_rng(12345698)
+        for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 4 else A + A.conj().T
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            x = rng.random(n).astype(dtype)
+            y = rng.random(n).astype(dtype)
+            xlong = arange(2*n).astype(dtype)
+            ylong = ones(2*n).astype(dtype)
+            alpha, beta = dtype(1.25), dtype(2)
+
+            if ind > 3:
+                func, = get_blas_funcs(('hpmv',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('spmv',), dtype=dtype)
+            y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta)
+            y2 = alpha * A.dot(x) + beta * y
+            assert_array_almost_equal(y1, y2)
+
+            # Test inc and offsets
+            y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap,
+                      incx=2, incy=2, offx=n, offy=n)
+            y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2]
+            assert_array_almost_equal(y1[3::2], y2)
+            assert_almost_equal(y1[4], ylong[4])
+
+    def test_spr_hpr(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 4 else A + A.conj().T
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            x = rng.random(n).astype(dtype)
+            alpha = (DTYPES+COMPLEX_DTYPES)[mod(ind, 4)](2.5)
+
+            if ind > 3:
+                func, = get_blas_funcs(('hpr',), dtype=dtype)
+                y2 = alpha * x[:, None].dot(x[None, :].conj()) + A
+            else:
+                func, = get_blas_funcs(('spr',), dtype=dtype)
+                y2 = alpha * x[:, None].dot(x[None, :]) + A
+
+            y1 = func(n=n, alpha=alpha, ap=Ap, x=x)
+            y1f = zeros((3, 3), dtype=dtype)
+            y1f[r, c] = y1
+            y1f[c, r] = y1.conj() if ind > 3 else y1
+            assert_array_almost_equal(y1f, y2)
+
+    def test_spr2_hpr2(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 2 else A + A.conj().T
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            x = rng.random(n).astype(dtype)
+            y = rng.random(n).astype(dtype)
+            alpha = dtype(2)
+
+            if ind > 1:
+                func, = get_blas_funcs(('hpr2',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('spr2',), dtype=dtype)
+
+            u = alpha.conj() * x[:, None].dot(y[None, :].conj())
+            y2 = A + u + u.conj().T
+            y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap)
+            y1f = zeros((3, 3), dtype=dtype)
+            y1f[r, c] = y1
+            y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj()
+            assert_array_almost_equal(y1f, y2)
+
+    def test_tbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 10
+            k = 3
+            x = rng.random(n).astype(dtype)
+            A = zeros((n, n), dtype=dtype)
+            # Banded upper triangular array
+            for sup in range(k+1):
+                A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
+
+            # Add complex parts for c,z
+            if ind > 1:
+                A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
+
+            # Form the banded storage
+            Ab = zeros((k+1, n), dtype=dtype)
+            for row in range(k+1):
+                Ab[-row-1, row:] = diag(A, k=row)
+            func, = get_blas_funcs(('tbmv',), dtype=dtype)
+
+            y1 = func(k=k, a=Ab, x=x)
+            y2 = A.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = A.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
+            y2 = A.T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
+            y2 = A.conj().T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_tbsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 6
+            k = 3
+            x = rng.random(n).astype(dtype)
+            A = zeros((n, n), dtype=dtype)
+            # Banded upper triangular array
+            for sup in range(k+1):
+                A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
+
+            # Add complex parts for c,z
+            if ind > 1:
+                A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
+
+            # Form the banded storage
+            Ab = zeros((k+1, n), dtype=dtype)
+            for row in range(k+1):
+                Ab[-row-1, row:] = diag(A, k=row)
+            func, = get_blas_funcs(('tbsv',), dtype=dtype)
+
+            y1 = func(k=k, a=Ab, x=x)
+            y2 = solve(A, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = solve(A, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
+            y2 = solve(A.T, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
+            y2 = solve(A.conj().T, x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_tpmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 10
+            x = rng.random(n).astype(dtype)
+            # Upper triangular array
+            if ind < 2:
+                A = triu(rng.random((n, n)))
+            else:
+                A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
+
+            # Form the packed storage
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            func, = get_blas_funcs(('tpmv',), dtype=dtype)
+
+            y1 = func(n=n, ap=Ap, x=x)
+            y2 = A.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = A.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
+            y2 = A.T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
+            y2 = A.conj().T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_tpsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 10
+            x = rng.random(n).astype(dtype)
+            # Upper triangular array
+            if ind < 2:
+                A = triu(rng.random((n, n)))
+            else:
+                A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
+            A += eye(n)
+            # Form the packed storage
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            func, = get_blas_funcs(('tpsv',), dtype=dtype)
+
+            y1 = func(n=n, ap=Ap, x=x)
+            y2 = solve(A, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = solve(A, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
+            y2 = solve(A.T, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
+            y2 = solve(A.conj().T, x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_trmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 3
+            A = (rng.random((n, n))+eye(n)).astype(dtype)
+            x = rng.random(3).astype(dtype)
+            func, = get_blas_funcs(('trmv',), dtype=dtype)
+
+            y1 = func(a=A, x=x)
+            y2 = triu(A).dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = triu(A).dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1, trans=1)
+            y2 = triu(A).T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1, trans=2)
+            y2 = triu(A).conj().T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_trsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 15
+            A = (rng.random((n, n))+eye(n)).astype(dtype)
+            x = rng.random(n).astype(dtype)
+            func, = get_blas_funcs(('trsv',), dtype=dtype)
+
+            y1 = func(a=A, x=x)
+            y2 = solve(triu(A), x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, lower=1)
+            y2 = solve(tril(A), x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = solve(triu(A), x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1, trans=1)
+            y2 = solve(triu(A).T, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1, trans=2)
+            y2 = solve(triu(A).conj().T, x)
+            assert_array_almost_equal(y1, y2)
+
+
+class TestFBLAS3Simple:
+
+    def test_gemm(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'gemm', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [3], [-4]), [[-36]])
+            assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21])
+        for p in 'cz':
+            f = getattr(fblas, p+'gemm', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]])
+            assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j])
+
+
+def _get_func(func, ps='sdzc'):
+    """Just a helper: return a specified BLAS function w/typecode."""
+    for p in ps:
+        f = getattr(fblas, p+func, None)
+        if f is None:
+            continue
+        yield f
+
+
+class TestBLAS3Symm:
+
+    def setup_method(self):
+        self.a = np.array([[1., 2.],
+                           [0., 1.]])
+        self.b = np.array([[1., 0., 3.],
+                           [0., -1., 2.]])
+        self.c = np.ones((2, 3))
+        self.t = np.array([[2., -1., 8.],
+                           [3., 0., 9.]])
+
+    def test_symm(self):
+        for f in _get_func('symm'):
+            res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
+            assert_array_almost_equal(res, self.t)
+
+            res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
+            assert_array_almost_equal(res, self.t)
+
+            res = f(a=self.a, b=self.b.T, side=1, c=self.c.T,
+                    alpha=1., beta=1.)
+            assert_array_almost_equal(res, self.t.T)
+
+    def test_summ_wrong_side(self):
+        f = getattr(fblas, 'dsymm', None)
+        if f is not None:
+            assert_raises(Exception, f, **{'a': self.a, 'b': self.b,
+                                           'alpha': 1, 'side': 1})
+            # `side=1` means C <- B*A, hence shapes of A and B are to be
+            #  compatible. Otherwise, f2py exception is raised
+
+    def test_symm_wrong_uplo(self):
+        """SYMM only considers the upper/lower part of A. Hence setting
+        wrong value for `lower` (default is lower=0, meaning upper triangle)
+        gives a wrong result.
+        """
+        f = getattr(fblas, 'dsymm', None)
+        if f is not None:
+            res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
+            assert np.allclose(res, self.t)
+
+            res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
+            assert not np.allclose(res, self.t)
+
+
+class TestBLAS3Syrk:
+    def setup_method(self):
+        self.a = np.array([[1., 0.],
+                           [0., -2.],
+                           [2., 3.]])
+        self.t = np.array([[1., 0., 2.],
+                           [0., 4., -6.],
+                           [2., -6., 13.]])
+        self.tt = np.array([[5., 6.],
+                            [6., 13.]])
+
+    def test_syrk(self):
+        for f in _get_func('syrk'):
+            c = f(a=self.a, alpha=1.)
+            assert_array_almost_equal(np.triu(c), np.triu(self.t))
+
+            c = f(a=self.a, alpha=1., lower=1)
+            assert_array_almost_equal(np.tril(c), np.tril(self.t))
+
+            c0 = np.ones(self.t.shape)
+            c = f(a=self.a, alpha=1., beta=1., c=c0)
+            assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
+
+            c = f(a=self.a, alpha=1., trans=1)
+            assert_array_almost_equal(np.triu(c), np.triu(self.tt))
+
+    # prints '0-th dimension must be fixed to 3 but got 5',
+    # FIXME: suppress?
+    # FIXME: how to catch the _fblas.error?
+    def test_syrk_wrong_c(self):
+        f = getattr(fblas, 'dsyrk', None)
+        if f is not None:
+            assert_raises(Exception, f, **{'a': self.a, 'alpha': 1.,
+                                           'c': np.ones((5, 8))})
+        # if C is supplied, it must have compatible dimensions
+
+
+class TestBLAS3Syr2k:
+    def setup_method(self):
+        self.a = np.array([[1., 0.],
+                           [0., -2.],
+                           [2., 3.]])
+        self.b = np.array([[0., 1.],
+                           [1., 0.],
+                           [0, 1.]])
+        self.t = np.array([[0., -1., 3.],
+                           [-1., 0., 0.],
+                           [3., 0., 6.]])
+        self.tt = np.array([[0., 1.],
+                            [1., 6]])
+
+    def test_syr2k(self):
+        for f in _get_func('syr2k'):
+            c = f(a=self.a, b=self.b, alpha=1.)
+            assert_array_almost_equal(np.triu(c), np.triu(self.t))
+
+            c = f(a=self.a, b=self.b, alpha=1., lower=1)
+            assert_array_almost_equal(np.tril(c), np.tril(self.t))
+
+            c0 = np.ones(self.t.shape)
+            c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0)
+            assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
+
+            c = f(a=self.a, b=self.b, alpha=1., trans=1)
+            assert_array_almost_equal(np.triu(c), np.triu(self.tt))
+
+    # prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
+    def test_syr2k_wrong_c(self):
+        f = getattr(fblas, 'dsyr2k', None)
+        if f is not None:
+            assert_raises(Exception, f, **{'a': self.a,
+                                           'b': self.b,
+                                           'alpha': 1.,
+                                           'c': np.zeros((15, 8))})
+        # if C is supplied, it must have compatible dimensions
+
+
+class TestSyHe:
+    """Quick and simple tests for (zc)-symm, syrk, syr2k."""
+
+    def setup_method(self):
+        self.sigma_y = np.array([[0., -1.j],
+                                 [1.j, 0.]])
+
+    def test_symm_zc(self):
+        for f in _get_func('symm', 'zc'):
+            # NB: a is symmetric w/upper diag of ONLY
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([1, -1]))
+
+    def test_hemm_zc(self):
+        for f in _get_func('hemm', 'zc'):
+            # NB: a is hermitian w/upper diag of ONLY
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
+
+    def test_syrk_zr(self):
+        for f in _get_func('syrk', 'zc'):
+            res = f(a=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
+
+    def test_herk_zr(self):
+        for f in _get_func('herk', 'zc'):
+            res = f(a=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
+
+    def test_syr2k_zr(self):
+        for f in _get_func('syr2k', 'zc'):
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
+
+    def test_her2k_zr(self):
+        for f in _get_func('her2k', 'zc'):
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1]))
+
+
+class TestTRMM:
+    """Quick and simple tests for dtrmm."""
+
+    def setup_method(self):
+        self.a = np.array([[1., 2., ],
+                           [-2., 1.]])
+        self.b = np.array([[3., 4., -1.],
+                           [5., 6., -2.]])
+
+        self.a2 = np.array([[1, 1, 2, 3],
+                            [0, 1, 4, 5],
+                            [0, 0, 1, 6],
+                            [0, 0, 0, 1]], order="f")
+        self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]],
+                           order="f")
+
+    @pytest.mark.parametrize("dtype_", DTYPES)
+    def test_side(self, dtype_):
+        trmm = get_blas_funcs("trmm", dtype=dtype_)
+        # Provide large A array that works for side=1 but not 0 (see gh-10841)
+        assert_raises(Exception, trmm, 1.0, self.a2, self.b2)
+        res = trmm(1.0, self.a2.astype(dtype_), self.b2.astype(dtype_),
+                   side=1)
+        k = self.b2.shape[1]
+        assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0.,
+                        atol=100*np.finfo(dtype_).eps)
+
+    def test_ab(self):
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            result = f(1., self.a, self.b)
+            # default a is upper triangular
+            expected = np.array([[13., 16., -5.],
+                                 [5., 6., -2.]])
+            assert_array_almost_equal(result, expected)
+
+    def test_ab_lower(self):
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            result = f(1., self.a, self.b, lower=True)
+            expected = np.array([[3., 4., -1.],
+                                 [-1., -2., 0.]])  # now a is lower triangular
+            assert_array_almost_equal(result, expected)
+
+    def test_b_overwrites(self):
+        # BLAS dtrmm modifies B argument in-place.
+        # Here the default is to copy, but this can be overridden
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            for overwr in [True, False]:
+                bcopy = self.b.copy()
+                result = f(1., self.a, bcopy, overwrite_b=overwr)
+                # C-contiguous arrays are copied
+                assert_(bcopy.flags.f_contiguous is False and
+                        np.may_share_memory(bcopy, result) is False)
+                assert_equal(bcopy, self.b)
+
+            bcopy = np.asfortranarray(self.b.copy())  # or just transpose it
+            result = f(1., self.a, bcopy, overwrite_b=True)
+            assert_(bcopy.flags.f_contiguous is True and
+                    np.may_share_memory(bcopy, result) is True)
+            assert_array_almost_equal(bcopy, result)
+
+
+def test_trsm():
+    rng = np.random.default_rng(1234)
+    for ind, dtype in enumerate(DTYPES):
+        tol = np.finfo(dtype).eps*1000
+        func, = get_blas_funcs(('trsm',), dtype=dtype)
+
+        # Test protection against size mismatches
+        A = rng.random((4, 5)).astype(dtype)
+        B = rng.random((4, 4)).astype(dtype)
+        alpha = dtype(1)
+        assert_raises(Exception, func, alpha, A, B)
+        assert_raises(Exception, func, alpha, A.T, B)
+
+        n = 8
+        m = 7
+        alpha = dtype(-2.5)
+        if ind < 2:
+            A = rng.random((m, m)) + eye(m)
+        else:
+            A = (rng.random((m, m)) + rng.random((m, m))*1j) + eye(m)
+        A = A.astype(dtype)
+        Au = triu(A)
+        Al = tril(A)
+        B1 = rng.random((m, n)).astype(dtype)
+        B2 = rng.random((n, m)).astype(dtype)
+
+        x1 = func(alpha=alpha, a=A, b=B1)
+        assert_equal(B1.shape, x1.shape)
+        x2 = solve(Au, alpha*B1)
+        assert_allclose(x1, x2, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B1, trans_a=1)
+        x2 = solve(Au.T, alpha*B1)
+        assert_allclose(x1, x2, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B1, trans_a=2)
+        x2 = solve(Au.conj().T, alpha*B1)
+        assert_allclose(x1, x2, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B1, diag=1)
+        Au[arange(m), arange(m)] = dtype(1)
+        x2 = solve(Au, alpha*B1)
+        assert_allclose(x1, x2, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1)
+        x2 = solve(Au.conj().T, alpha*B2.conj().T)
+        assert_allclose(x1, x2.conj().T, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1)
+        Al[arange(m), arange(m)] = dtype(1)
+        x2 = solve(Al.conj().T, alpha*B2.conj().T)
+        assert_allclose(x1, x2.conj().T, atol=tol)
+
+
+@pytest.mark.xfail(run=False,
+                   reason="gh-16930")
+def test_gh_169309():
+    x = np.repeat(10, 9)
+    actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1)
+    expected = math.sqrt(500)
+    assert_allclose(actual, expected)
+
+
+def test_dnrm2_neg_incx():
+    # check that dnrm2(..., incx < 0) raises
+    # XXX: remove the test after the lowest supported BLAS implements
+    # negative incx (new in LAPACK 3.10)
+    x = np.repeat(10, 9)
+    incx = -1
+    with assert_raises(fblas.__fblas_error):
+        scipy.linalg.blas.dnrm2(x, 5, 3, incx)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..284e214d38ed331cf0493d1e3bba6e1214939b2c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py
@@ -0,0 +1,118 @@
+import numpy as np
+from numpy.testing import (assert_allclose,
+                           assert_equal)
+import scipy.linalg.cython_blas as blas
+
+class TestDGEMM:
+    
+    def test_transposes(self):
+
+        a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2]
+        b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2]
+        c = np.empty((2, 4))[:2,:2]
+
+        blas._test_dgemm(1., a, b, 0., c)
+        assert_allclose(c, a.dot(b))
+
+        blas._test_dgemm(1., a.T, b, 0., c)
+        assert_allclose(c, a.T.dot(b))
+
+        blas._test_dgemm(1., a, b.T, 0., c)
+        assert_allclose(c, a.dot(b.T))
+
+        blas._test_dgemm(1., a.T, b.T, 0., c)
+        assert_allclose(c, a.T.dot(b.T))
+
+        blas._test_dgemm(1., a, b, 0., c.T)
+        assert_allclose(c, a.dot(b).T)
+
+        blas._test_dgemm(1., a.T, b, 0., c.T)
+        assert_allclose(c, a.T.dot(b).T)
+
+        blas._test_dgemm(1., a, b.T, 0., c.T)
+        assert_allclose(c, a.dot(b.T).T)
+
+        blas._test_dgemm(1., a.T, b.T, 0., c.T)
+        assert_allclose(c, a.T.dot(b.T).T)
+    
+    def test_shapes(self):
+        a = np.arange(6, dtype='d').reshape((3, 2))
+        b = np.arange(-6, 2, dtype='d').reshape((2, 4))
+        c = np.empty((3, 4))
+
+        blas._test_dgemm(1., a, b, 0., c)
+        assert_allclose(c, a.dot(b))
+
+        blas._test_dgemm(1., b.T, a.T, 0., c.T)
+        assert_allclose(c, b.T.dot(a.T).T)
+        
+class TestWfuncPointers:
+    """ Test the function pointers that are expected to fail on
+    Mac OS X without the additional entry statement in their definitions
+    in fblas_l1.pyf.src. """
+
+    def test_complex_args(self):
+
+        cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64)
+        cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64)
+
+        assert_allclose(blas._test_cdotc(cx, cy),
+                        -17.6468753815+21.3718757629j)
+        assert_allclose(blas._test_cdotu(cx, cy),
+                        -6.11562538147+30.3156242371j)
+
+        assert_equal(blas._test_icamax(cx), 3)
+
+        assert_allclose(blas._test_scasum(cx), 18.625)
+        assert_allclose(blas._test_scnrm2(cx), 13.1796483994)
+
+        assert_allclose(blas._test_cdotc(cx[::2], cy[::2]),
+                        -18.1000003815+21.2000007629j)
+        assert_allclose(blas._test_cdotu(cx[::2], cy[::2]),
+                        -6.10000038147+30.7999992371j)
+        assert_allclose(blas._test_scasum(cx[::2]), 18.)
+        assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499)
+    
+    def test_double_args(self):
+
+        x = np.array([5., -3, -.5], np.float64)
+        y = np.array([2, 1, .5], np.float64)
+
+        assert_allclose(blas._test_dasum(x), 8.5)
+        assert_allclose(blas._test_ddot(x, y), 6.75)
+        assert_allclose(blas._test_dnrm2(x), 5.85234975815)
+
+        assert_allclose(blas._test_dasum(x[::2]), 5.5)
+        assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75)
+        assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297)
+
+        assert_equal(blas._test_idamax(x), 1)
+
+    def test_float_args(self):
+
+        x = np.array([5., -3, -.5], np.float32)
+        y = np.array([2, 1, .5], np.float32)
+
+        assert_equal(blas._test_isamax(x), 1)
+
+        assert_allclose(blas._test_sasum(x), 8.5)
+        assert_allclose(blas._test_sdot(x, y), 6.75)
+        assert_allclose(blas._test_snrm2(x), 5.85234975815)
+
+        assert_allclose(blas._test_sasum(x[::2]), 5.5)
+        assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75)
+        assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297)
+
+    def test_double_complex_args(self):
+
+        cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128)
+        cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128)
+
+        assert_equal(blas._test_izamax(cx), 3)
+
+        assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j)
+        assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j)
+
+        assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j)
+        assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j)
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a4e7b34b62042efdb0ce0f8ee61ce0189320995
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py
@@ -0,0 +1,22 @@
+from numpy.testing import assert_allclose
+from scipy.linalg import cython_lapack as cython_lapack
+from scipy.linalg import lapack
+
+
+class TestLamch:
+
+    def test_slamch(self):
+        for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
+            assert_allclose(cython_lapack._test_slamch(c),
+                            lapack.slamch(c))
+
+    def test_dlamch(self):
+        for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
+            assert_allclose(cython_lapack._test_dlamch(c),
+                            lapack.dlamch(c))
+
+    def test_complex_ladiv(self):
+        cx = .5 + 1.j
+        cy = .875 + 2.j
+        assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j)
+        assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d52c93950b6398c010b8bb8e5312153b3102fdf4
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
@@ -0,0 +1,132 @@
+import numpy as np
+from scipy.linalg import bandwidth, issymmetric, ishermitian
+import pytest
+from pytest import raises
+
+
+def test_bandwidth_dtypes():
+    n = 5
+    for t in np.typecodes['All']:
+        A = np.zeros([n, n], dtype=t)
+        if t in 'eUVOMm':
+            raises(TypeError, bandwidth, A)
+        elif t == 'G':  # No-op test. On win these pass on others fail.
+            pass
+        else:
+            _ = bandwidth(A)
+
+
+def test_bandwidth_non2d_input():
+    A = np.array([1, 2, 3])
+    raises(ValueError, bandwidth, A)
+    A = np.array([[[1, 2, 3], [4, 5, 6]]])
+    raises(ValueError, bandwidth, A)
+
+
+@pytest.mark.parametrize('T', [x for x in np.typecodes['All']
+                               if x not in 'eGUVOMm'])
+def test_bandwidth_square_inputs(T):
+    n = 20
+    k = 4
+    R = np.zeros([n, n], dtype=T, order='F')
+    # form a banded matrix inplace
+    R[[x for x in range(n)], [x for x in range(n)]] = 1
+    R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
+    R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
+    R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
+    assert bandwidth(R) == (k, k)
+    A = np.array([
+        [1, 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, 0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0, 1, 1, 1],
+        [0, 0, 0, 0, 0, 1, 0, 0],
+        [0, 0, 0, 0, 0, 1, 0, 0],
+    ])
+    assert bandwidth(A) == (2, 2)
+
+
+@pytest.mark.parametrize('T', [x for x in np.typecodes['All']
+                               if x not in 'eGUVOMm'])
+def test_bandwidth_rect_inputs(T):
+    n, m = 10, 20
+    k = 5
+    R = np.zeros([n, m], dtype=T, order='F')
+    # form a banded matrix inplace
+    R[[x for x in range(n)], [x for x in range(n)]] = 1
+    R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
+    R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
+    R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
+    assert bandwidth(R) == (k, k)
+
+
+def test_issymetric_ishermitian_dtypes():
+    n = 5
+    for t in np.typecodes['All']:
+        A = np.zeros([n, n], dtype=t)
+        if t in 'eUVOMm':
+            raises(TypeError, issymmetric, A)
+            raises(TypeError, ishermitian, A)
+        elif t == 'G':  # No-op test. On win these pass on others fail.
+            pass
+        else:
+            assert issymmetric(A)
+            assert ishermitian(A)
+
+
+def test_issymmetric_ishermitian_invalid_input():
+    A = np.array([1, 2, 3])
+    raises(ValueError, issymmetric, A)
+    raises(ValueError, ishermitian, A)
+    A = np.array([[[1, 2, 3], [4, 5, 6]]])
+    raises(ValueError, issymmetric, A)
+    raises(ValueError, ishermitian, A)
+    A = np.array([[1, 2, 3], [4, 5, 6]])
+    raises(ValueError, issymmetric, A)
+    raises(ValueError, ishermitian, A)
+
+
+def test_issymetric_complex_decimals():
+    A = np.arange(1, 10).astype(complex).reshape(3, 3)
+    A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
+    # make entries decimal
+    A /= np.pi
+    A = A + A.T
+    assert issymmetric(A)
+
+
+def test_ishermitian_complex_decimals():
+    A = np.arange(1, 10).astype(complex).reshape(3, 3)
+    A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
+    # make entries decimal
+    A /= np.pi
+    A = A + A.T.conj()
+    assert ishermitian(A)
+
+
+def test_issymmetric_approximate_results():
+    n = 20
+    rng = np.random.RandomState(123456789)
+    x = rng.uniform(high=5., size=[n, n])
+    y = x @ x.T  # symmetric
+    p = rng.standard_normal([n, n])
+    z = p @ y @ p.T
+    assert issymmetric(z, atol=1e-10)
+    assert issymmetric(z, atol=1e-10, rtol=0.)
+    assert issymmetric(z, atol=0., rtol=1e-12)
+    assert issymmetric(z, atol=1e-13, rtol=1e-12)
+
+
+def test_ishermitian_approximate_results():
+    n = 20
+    rng = np.random.RandomState(987654321)
+    x = rng.uniform(high=5., size=[n, n])
+    y = x @ x.T  # symmetric
+    p = rng.standard_normal([n, n]) + rng.standard_normal([n, n])*1j
+    z = p @ y @ p.conj().T
+    assert ishermitian(z, atol=1e-10)
+    assert ishermitian(z, atol=1e-10, rtol=0.)
+    assert ishermitian(z, atol=0., rtol=1e-12)
+    assert ishermitian(z, atol=1e-13, rtol=1e-12)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..605496721f8eec7a522fbba0a77ed33d6c1fdeaf
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py
@@ -0,0 +1,3152 @@
+import itertools
+import platform
+import sys
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal,
+                           assert_array_almost_equal, assert_array_equal,
+                           assert_, assert_allclose)
+
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import (eig, eigvals, lu, svd, svdvals, cholesky, qr,
+                          schur, rsf2csf, lu_solve, lu_factor, solve, diagsvd,
+                          hessenberg, rq, eig_banded, eigvals_banded, eigh,
+                          eigvalsh, qr_multiply, qz, orth, ordqz,
+                          subspace_angles, hadamard, eigvalsh_tridiagonal,
+                          eigh_tridiagonal, null_space, cdf2rdf, LinAlgError)
+
+from scipy.linalg.lapack import (dgbtrf, dgbtrs, zgbtrf, zgbtrs, dsbev,
+                                 dsbevd, dsbevx, zhbevd, zhbevx)
+
+from scipy.linalg._misc import norm
+from scipy.linalg._decomp_qz import _select_function
+from scipy.stats import ortho_group
+
+from numpy import (array, diag, full, linalg, argsort, zeros, arange,
+                   float32, complex64, ravel, sqrt, iscomplex, shape, sort,
+                   sign, asarray, isfinite, ndarray, eye,)
+
+from scipy.linalg._testutils import assert_no_overwrite
+from scipy.sparse._sputils import matrix
+
+from scipy._lib._testutils import check_free_memory
+from scipy.linalg.blas import HAS_ILP64
+try:
+    from scipy.__config__ import CONFIG
+except ImportError:
+    CONFIG = None
+
+IS_WASM = (sys.platform == "emscripten" or platform.machine() in ["wasm32", "wasm64"])
+
+
+def _random_hermitian_matrix(n, posdef=False, dtype=float):
+    "Generate random sym/hermitian array of the given size n"
+    if dtype in COMPLEX_DTYPES:
+        A = np.random.rand(n, n) + np.random.rand(n, n)*1.0j
+        A = (A + A.conj().T)/2
+    else:
+        A = np.random.rand(n, n)
+        A = (A + A.T)/2
+
+    if posdef:
+        A += sqrt(2*n)*np.eye(n)
+
+    return A.astype(dtype)
+
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+# XXX: This function should not be defined here, but somewhere in
+#      scipy.linalg namespace
+def symrand(dim_or_eigv, rng):
+    """Return a random symmetric (Hermitian) matrix.
+
+    If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues
+        uniformly distributed on (-1,1).
+
+    If 'dim_or_eigv' is  1-D real array 'a', return a matrix whose
+                      eigenvalues are 'a'.
+    """
+    if isinstance(dim_or_eigv, int):
+        dim = dim_or_eigv
+        d = rng.random(dim)*2 - 1
+    elif (isinstance(dim_or_eigv, ndarray) and
+          len(dim_or_eigv.shape) == 1):
+        dim = dim_or_eigv.shape[0]
+        d = dim_or_eigv
+    else:
+        raise TypeError("input type not supported.")
+
+    v = ortho_group.rvs(dim)
+    h = v.T.conj() @ diag(d) @ v
+    # to avoid roundoff errors, symmetrize the matrix (again)
+    h = 0.5*(h.T+h)
+    return h
+
+
+class TestEigVals:
+
+    def test_simple(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        w = eigvals(a)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        assert_array_almost_equal(w, exact_w)
+
+    def test_simple_tr(self):
+        a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]], 'd').T
+        a = a.copy()
+        a = a.T
+        w = eigvals(a)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        assert_array_almost_equal(w, exact_w)
+
+    def test_simple_complex(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]]
+        w = eigvals(a)
+        exact_w = [(9+1j+sqrt(92+6j))/2,
+                   0,
+                   (9+1j-sqrt(92+6j))/2]
+        assert_array_almost_equal(w, exact_w)
+
+    def test_finite(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        w = eigvals(a, check_finite=False)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        assert_array_almost_equal(w, exact_w)
+
+    @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        w = eigvals(a)
+        assert w.shape == (0,)
+        assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype
+
+        w = eigvals(a, homogeneous_eigvals=True)
+        assert w.shape == (2, 0)
+        assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype
+
+
+class TestEig:
+
+    def test_simple(self):
+        a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+        w, v = eig(a)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        v0 = array([1, 1, (1+sqrt(93)/3)/2])
+        v1 = array([3., 0, -1])
+        v2 = array([1, 1, (1-sqrt(93)/3)/2])
+        v0 = v0 / norm(v0)
+        v1 = v1 / norm(v1)
+        v2 = v2 / norm(v2)
+        assert_array_almost_equal(w, exact_w)
+        assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0]))
+        assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1]))
+        assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2]))
+        for i in range(3):
+            assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i])
+        w, v = eig(a, left=1, right=0)
+        for i in range(3):
+            assert_array_almost_equal(a.T @ v[:, i], w[i]*v[:, i])
+
+    def test_simple_complex_eig(self):
+        a = array([[1, 2], [-2, 1]])
+        w, vl, vr = eig(a, left=1, right=1)
+        assert_array_almost_equal(w, array([1+2j, 1-2j]))
+        for i in range(2):
+            assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i])
+        for i in range(2):
+            assert_array_almost_equal(a.conj().T @ vl[:, i],
+                                      w[i].conj()*vl[:, i])
+
+    def test_simple_complex(self):
+        a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]])
+        w, vl, vr = eig(a, left=1, right=1)
+        for i in range(3):
+            assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i])
+        for i in range(3):
+            assert_array_almost_equal(a.conj().T @ vl[:, i],
+                                      w[i].conj()*vl[:, i])
+
+    def test_gh_3054(self):
+        a = [[1]]
+        b = [[0]]
+        w, vr = eig(a, b, homogeneous_eigvals=True)
+        assert_allclose(w[1, 0], 0)
+        assert_(w[0, 0] != 0)
+        assert_allclose(vr, 1)
+
+        w, vr = eig(a, b)
+        assert_equal(w, np.inf)
+        assert_allclose(vr, 1)
+
+    def _check_gen_eig(self, A, B, atol_homog=1e-13, rtol_homog=1e-13,
+                                   atol=1e-13, rtol=1e-13):
+        if B is not None:
+            A, B = asarray(A), asarray(B)
+            B0 = B
+        else:
+            A = asarray(A)
+            B0 = B
+            B = np.eye(*A.shape)
+        msg = f"\n{A!r}\n{B!r}"
+
+        # Eigenvalues in homogeneous coordinates
+        w, vr = eig(A, B0, homogeneous_eigvals=True)
+        wt = eigvals(A, B0, homogeneous_eigvals=True)
+        val1 = A @ vr * w[1, :]
+        val2 = B @ vr * w[0, :]
+        for i in range(val1.shape[1]):
+            assert_allclose(val1[:, i], val2[:, i],
+                            rtol=rtol_homog, atol=atol_homog, err_msg=msg)
+
+        if B0 is None:
+            assert_allclose(w[1, :], 1)
+            assert_allclose(wt[1, :], 1)
+
+        perm = np.lexsort(w)
+        permt = np.lexsort(wt)
+        assert_allclose(w[:, perm], wt[:, permt], atol=1e-7, rtol=1e-7,
+                        err_msg=msg)
+
+        length = np.empty(len(vr))
+
+        for i in range(len(vr)):
+            length[i] = norm(vr[:, i])
+
+        assert_allclose(length, np.ones(length.size), err_msg=msg,
+                        atol=1e-7, rtol=1e-7)
+
+        # Convert homogeneous coordinates
+        beta_nonzero = (w[1, :] != 0)
+        wh = w[0, beta_nonzero] / w[1, beta_nonzero]
+
+        # Eigenvalues in standard coordinates
+        w, vr = eig(A, B0)
+        wt = eigvals(A, B0)
+        val1 = A @ vr
+        val2 = B @ vr * w
+        res = val1 - val2
+        for i in range(res.shape[1]):
+            if np.all(isfinite(res[:, i])):
+                assert_allclose(res[:, i], 0,
+                                rtol=rtol, atol=atol, err_msg=msg)
+
+        # try to consistently order eigenvalues, including complex conjugate pairs
+        w_fin = w[isfinite(w)]
+        wt_fin = wt[isfinite(wt)]
+
+        # prune noise in the real parts
+        w_fin = -1j * np.real_if_close(1j*w_fin, tol=1e-10)
+        wt_fin = -1j * np.real_if_close(1j*wt_fin, tol=1e-10)
+
+        perm = argsort(abs(w_fin) + w_fin.imag)
+        permt = argsort(abs(wt_fin) + wt_fin.imag)
+
+        assert_allclose(w_fin[perm], wt_fin[permt],
+                        atol=1e-7, rtol=1e-7, err_msg=msg)
+
+        length = np.empty(len(vr))
+        for i in range(len(vr)):
+            length[i] = norm(vr[:, i])
+        assert_allclose(length, np.ones(length.size), err_msg=msg)
+
+        # Compare homogeneous and nonhomogeneous versions
+        assert_allclose(sort(wh), sort(w[np.isfinite(w)]))
+
+    def test_singular(self):
+        # Example taken from
+        # https://web.archive.org/web/20040903121217/http://www.cs.umu.se/research/nla/singular_pairs/guptri/matlab.html
+        A = array([[22, 34, 31, 31, 17],
+                   [45, 45, 42, 19, 29],
+                   [39, 47, 49, 26, 34],
+                   [27, 31, 26, 21, 15],
+                   [38, 44, 44, 24, 30]])
+        B = array([[13, 26, 25, 17, 24],
+                   [31, 46, 40, 26, 37],
+                   [26, 40, 19, 25, 25],
+                   [16, 25, 27, 14, 23],
+                   [24, 35, 18, 21, 22]])
+
+        with np.errstate(all='ignore'):
+            self._check_gen_eig(A, B, atol_homog=5e-13, atol=5e-13)
+
+    def test_falker(self):
+        # Test matrices giving some Nan generalized eigenvalues.
+        M = diag(array([1, 0, 3]))
+        K = array(([2, -1, -1], [-1, 2, -1], [-1, -1, 2]))
+        D = array(([1, -1, 0], [-1, 1, 0], [0, 0, 0]))
+        Z = zeros((3, 3))
+        I3 = eye(3)
+        A = np.block([[I3, Z], [Z, -K]])
+        B = np.block([[Z, I3], [M, D]])
+
+        with np.errstate(all='ignore'):
+            self._check_gen_eig(A, B)
+
+    def test_bad_geneig(self):
+        # Ticket #709 (strange return values from DGGEV)
+
+        def matrices(omega):
+            c1 = -9 + omega**2
+            c2 = 2*omega
+            A = [[1, 0, 0, 0],
+                 [0, 1, 0, 0],
+                 [0, 0, c1, 0],
+                 [0, 0, 0, c1]]
+            B = [[0, 0, 1, 0],
+                 [0, 0, 0, 1],
+                 [1, 0, 0, -c2],
+                 [0, 1, c2, 0]]
+            return A, B
+
+        # With a buggy LAPACK, this can fail for different omega on different
+        # machines -- so we need to test several values
+        with np.errstate(all='ignore'):
+            for k in range(100):
+                A, B = matrices(omega=k*5./100)
+                self._check_gen_eig(A, B)
+
+    def test_make_eigvals(self):
+        # Step through all paths in _make_eigvals
+        # Real eigenvalues
+        rng = np.random.RandomState(1234)
+        A = symrand(3, rng)
+        self._check_gen_eig(A, None)
+        B = symrand(3, rng)
+        self._check_gen_eig(A, B)
+        # Complex eigenvalues
+        A = rng.random((3, 3)) + 1j*rng.random((3, 3))
+        self._check_gen_eig(A, None)
+        B = rng.random((3, 3)) + 1j*rng.random((3, 3))
+        self._check_gen_eig(A, B)
+
+    def test_check_finite(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        w, v = eig(a, check_finite=False)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        v0 = array([1, 1, (1+sqrt(93)/3)/2])
+        v1 = array([3., 0, -1])
+        v2 = array([1, 1, (1-sqrt(93)/3)/2])
+        v0 = v0 / norm(v0)
+        v1 = v1 / norm(v1)
+        v2 = v2 / norm(v2)
+        assert_array_almost_equal(w, exact_w)
+        assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0]))
+        assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1]))
+        assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2]))
+        for i in range(3):
+            assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i])
+
+    def test_not_square_error(self):
+        """Check that passing a non-square array raises a ValueError."""
+        A = np.arange(6).reshape(3, 2)
+        assert_raises(ValueError, eig, A)
+
+    def test_shape_mismatch(self):
+        """Check that passing arrays of with different shapes
+        raises a ValueError."""
+        A = eye(2)
+        B = np.arange(9.0).reshape(3, 3)
+        assert_raises(ValueError, eig, A, B)
+        assert_raises(ValueError, eig, B, A)
+
+    def test_gh_11577(self):
+        # https://github.com/scipy/scipy/issues/11577
+        # `A - lambda B` should have 4 and 8 among the eigenvalues, and this
+        # was apparently broken on some platforms
+        A = np.array([[12.0, 28.0, 76.0, 220.0],
+                      [16.0, 32.0, 80.0, 224.0],
+                      [24.0, 40.0, 88.0, 232.0],
+                      [40.0, 56.0, 104.0, 248.0]], dtype='float64')
+        B = np.array([[2.0, 4.0, 10.0, 28.0],
+                      [3.0, 5.0, 11.0, 29.0],
+                      [5.0, 7.0, 13.0, 31.0],
+                      [9.0, 11.0, 17.0, 35.0]], dtype='float64')
+
+        D, V = eig(A, B)
+
+        # The problem is ill-conditioned, and two other eigenvalues
+        # depend on ATLAS/OpenBLAS version, compiler version etc
+        # see gh-11577 for discussion
+        #
+        # NB: it is tempting to use `assert_allclose(D[:2], [4, 8])` instead but
+        # the ordering of eigenvalues also comes out different on different
+        # systems depending on who knows what.
+        with np.testing.suppress_warnings() as sup:
+            # isclose chokes on inf/nan values
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            assert np.isclose(D, 4.0, atol=1e-14).any()
+            assert np.isclose(D, 8.0, atol=1e-14).any()
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        w, vr = eig(a)
+
+        w_n, vr_n = eig(np.eye(2, dtype=dt))
+
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype  #eigvals(np.eye(2, dtype=dt)).dtype
+
+        assert_allclose(vr, np.empty((0, 0)))
+        assert vr.shape == (0, 0)
+        assert vr.dtype == vr_n.dtype
+
+        w, vr = eig(a, homogeneous_eigvals=True)
+        assert w.shape == (2, 0)
+        assert w.dtype == w_n.dtype
+
+        assert vr.shape == (0, 0)
+        assert vr.dtype == vr_n.dtype
+
+
+
+class TestEigBanded:
+    def setup_method(self):
+        self.create_bandmat()
+
+    def create_bandmat(self):
+        """Create the full matrix `self.fullmat` and
+           the corresponding band matrix `self.bandmat`."""
+        N = 10
+        self.KL = 2   # number of subdiagonals (below the diagonal)
+        self.KU = 2   # number of superdiagonals (above the diagonal)
+
+        # symmetric band matrix
+        self.sym_mat = (diag(full(N, 1.0))
+                        + diag(full(N-1, -1.0), -1) + diag(full(N-1, -1.0), 1)
+                        + diag(full(N-2, -2.0), -2) + diag(full(N-2, -2.0), 2))
+
+        # hermitian band matrix
+        self.herm_mat = (diag(full(N, -1.0))
+                         + 1j*diag(full(N-1, 1.0), -1)
+                         - 1j*diag(full(N-1, 1.0), 1)
+                         + diag(full(N-2, -2.0), -2)
+                         + diag(full(N-2, -2.0), 2))
+
+        # general real band matrix
+        self.real_mat = (diag(full(N, 1.0))
+                         + diag(full(N-1, -1.0), -1) + diag(full(N-1, -3.0), 1)
+                         + diag(full(N-2, 2.0), -2) + diag(full(N-2, -2.0), 2))
+
+        # general complex band matrix
+        self.comp_mat = (1j*diag(full(N, 1.0))
+                         + diag(full(N-1, -1.0), -1)
+                         + 1j*diag(full(N-1, -3.0), 1)
+                         + diag(full(N-2, 2.0), -2)
+                         + diag(full(N-2, -2.0), 2))
+
+        # Eigenvalues and -vectors from linalg.eig
+        ew, ev = linalg.eig(self.sym_mat)
+        ew = ew.real
+        args = argsort(ew)
+        self.w_sym_lin = ew[args]
+        self.evec_sym_lin = ev[:, args]
+
+        ew, ev = linalg.eig(self.herm_mat)
+        ew = ew.real
+        args = argsort(ew)
+        self.w_herm_lin = ew[args]
+        self.evec_herm_lin = ev[:, args]
+
+        # Extract upper bands from symmetric and hermitian band matrices
+        # (for use in dsbevd, dsbevx, zhbevd, zhbevx
+        #  and their single precision versions)
+        LDAB = self.KU + 1
+        self.bandmat_sym = zeros((LDAB, N), dtype=float)
+        self.bandmat_herm = zeros((LDAB, N), dtype=complex)
+        for i in range(LDAB):
+            self.bandmat_sym[LDAB-i-1, i:N] = diag(self.sym_mat, i)
+            self.bandmat_herm[LDAB-i-1, i:N] = diag(self.herm_mat, i)
+
+        # Extract bands from general real and complex band matrix
+        # (for use in dgbtrf, dgbtrs and their single precision versions)
+        LDAB = 2*self.KL + self.KU + 1
+        self.bandmat_real = zeros((LDAB, N), dtype=float)
+        self.bandmat_real[2*self.KL, :] = diag(self.real_mat)  # diagonal
+        for i in range(self.KL):
+            # superdiagonals
+            self.bandmat_real[2*self.KL-1-i, i+1:N] = diag(self.real_mat, i+1)
+            # subdiagonals
+            self.bandmat_real[2*self.KL+1+i, 0:N-1-i] = diag(self.real_mat,
+                                                             -i-1)
+
+        self.bandmat_comp = zeros((LDAB, N), dtype=complex)
+        self.bandmat_comp[2*self.KL, :] = diag(self.comp_mat)  # diagonal
+        for i in range(self.KL):
+            # superdiagonals
+            self.bandmat_comp[2*self.KL-1-i, i+1:N] = diag(self.comp_mat, i+1)
+            # subdiagonals
+            self.bandmat_comp[2*self.KL+1+i, 0:N-1-i] = diag(self.comp_mat,
+                                                             -i-1)
+
+        # absolute value for linear equation system A*x = b
+        self.b = 1.0*arange(N)
+        self.bc = self.b * (1 + 1j)
+
+    #####################################################################
+
+    def test_dsbev(self):
+        """Compare dsbev eigenvalues and eigenvectors with
+           the result of linalg.eig."""
+        w, evec, info = dsbev(self.bandmat_sym, compute_v=1)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+    def test_dsbevd(self):
+        """Compare dsbevd eigenvalues and eigenvectors with
+           the result of linalg.eig."""
+        w, evec, info = dsbevd(self.bandmat_sym, compute_v=1)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+    def test_dsbevx(self):
+        """Compare dsbevx eigenvalues and eigenvectors
+           with the result of linalg.eig."""
+        N, N = shape(self.sym_mat)
+        # Achtung: Argumente 0.0,0.0,range?
+        w, evec, num, ifail, info = dsbevx(self.bandmat_sym, 0.0, 0.0, 1, N,
+                                           compute_v=1, range=2)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+    def test_zhbevd(self):
+        """Compare zhbevd eigenvalues and eigenvectors
+           with the result of linalg.eig."""
+        w, evec, info = zhbevd(self.bandmat_herm, compute_v=1)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_herm_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin))
+
+    def test_zhbevx(self):
+        """Compare zhbevx eigenvalues and eigenvectors
+           with the result of linalg.eig."""
+        N, N = shape(self.herm_mat)
+        # Achtung: Argumente 0.0,0.0,range?
+        w, evec, num, ifail, info = zhbevx(self.bandmat_herm, 0.0, 0.0, 1, N,
+                                           compute_v=1, range=2)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_herm_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin))
+
+    def test_eigvals_banded(self):
+        """Compare eigenvalues of eigvals_banded with those of linalg.eig."""
+        w_sym = eigvals_banded(self.bandmat_sym)
+        w_sym = w_sym.real
+        assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+
+        w_herm = eigvals_banded(self.bandmat_herm)
+        w_herm = w_herm.real
+        assert_array_almost_equal(sort(w_herm), self.w_herm_lin)
+
+        # extracting eigenvalues with respect to an index range
+        ind1 = 2
+        ind2 = np.longlong(6)
+        w_sym_ind = eigvals_banded(self.bandmat_sym,
+                                   select='i', select_range=(ind1, ind2))
+        assert_array_almost_equal(sort(w_sym_ind),
+                                  self.w_sym_lin[ind1:ind2+1])
+        w_herm_ind = eigvals_banded(self.bandmat_herm,
+                                    select='i', select_range=(ind1, ind2))
+        assert_array_almost_equal(sort(w_herm_ind),
+                                  self.w_herm_lin[ind1:ind2+1])
+
+        # extracting eigenvalues with respect to a value range
+        v_lower = self.w_sym_lin[ind1] - 1.0e-5
+        v_upper = self.w_sym_lin[ind2] + 1.0e-5
+        w_sym_val = eigvals_banded(self.bandmat_sym,
+                                   select='v', select_range=(v_lower, v_upper))
+        assert_array_almost_equal(sort(w_sym_val),
+                                  self.w_sym_lin[ind1:ind2+1])
+
+        v_lower = self.w_herm_lin[ind1] - 1.0e-5
+        v_upper = self.w_herm_lin[ind2] + 1.0e-5
+        w_herm_val = eigvals_banded(self.bandmat_herm,
+                                    select='v',
+                                    select_range=(v_lower, v_upper))
+        assert_array_almost_equal(sort(w_herm_val),
+                                  self.w_herm_lin[ind1:ind2+1])
+
+        w_sym = eigvals_banded(self.bandmat_sym, check_finite=False)
+        w_sym = w_sym.real
+        assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+
+    def test_eig_banded(self):
+        """Compare eigenvalues and eigenvectors of eig_banded
+           with those of linalg.eig. """
+        w_sym, evec_sym = eig_banded(self.bandmat_sym)
+        evec_sym_ = evec_sym[:, argsort(w_sym.real)]
+        assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin))
+
+        w_herm, evec_herm = eig_banded(self.bandmat_herm)
+        evec_herm_ = evec_herm[:, argsort(w_herm.real)]
+        assert_array_almost_equal(sort(w_herm), self.w_herm_lin)
+        assert_array_almost_equal(abs(evec_herm_), abs(self.evec_herm_lin))
+
+        # extracting eigenvalues with respect to an index range
+        ind1 = 2
+        ind2 = 6
+        w_sym_ind, evec_sym_ind = eig_banded(self.bandmat_sym,
+                                             select='i',
+                                             select_range=(ind1, ind2))
+        assert_array_almost_equal(sort(w_sym_ind),
+                                  self.w_sym_lin[ind1:ind2+1])
+        assert_array_almost_equal(abs(evec_sym_ind),
+                                  abs(self.evec_sym_lin[:, ind1:ind2+1]))
+
+        w_herm_ind, evec_herm_ind = eig_banded(self.bandmat_herm,
+                                               select='i',
+                                               select_range=(ind1, ind2))
+        assert_array_almost_equal(sort(w_herm_ind),
+                                  self.w_herm_lin[ind1:ind2+1])
+        assert_array_almost_equal(abs(evec_herm_ind),
+                                  abs(self.evec_herm_lin[:, ind1:ind2+1]))
+
+        # extracting eigenvalues with respect to a value range
+        v_lower = self.w_sym_lin[ind1] - 1.0e-5
+        v_upper = self.w_sym_lin[ind2] + 1.0e-5
+        w_sym_val, evec_sym_val = eig_banded(self.bandmat_sym,
+                                             select='v',
+                                             select_range=(v_lower, v_upper))
+        assert_array_almost_equal(sort(w_sym_val),
+                                  self.w_sym_lin[ind1:ind2+1])
+        assert_array_almost_equal(abs(evec_sym_val),
+                                  abs(self.evec_sym_lin[:, ind1:ind2+1]))
+
+        v_lower = self.w_herm_lin[ind1] - 1.0e-5
+        v_upper = self.w_herm_lin[ind2] + 1.0e-5
+        w_herm_val, evec_herm_val = eig_banded(self.bandmat_herm,
+                                               select='v',
+                                               select_range=(v_lower, v_upper))
+        assert_array_almost_equal(sort(w_herm_val),
+                                  self.w_herm_lin[ind1:ind2+1])
+        assert_array_almost_equal(abs(evec_herm_val),
+                                  abs(self.evec_herm_lin[:, ind1:ind2+1]))
+
+        w_sym, evec_sym = eig_banded(self.bandmat_sym, check_finite=False)
+        evec_sym_ = evec_sym[:, argsort(w_sym.real)]
+        assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin))
+
+    def test_dgbtrf(self):
+        """Compare dgbtrf  LU factorisation with the LU factorisation result
+           of linalg.lu."""
+        M, N = shape(self.real_mat)
+        lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU)
+
+        # extract matrix u from lu_symm_band
+        u = diag(lu_symm_band[2*self.KL, :])
+        for i in range(self.KL + self.KU):
+            u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1)
+
+        p_lin, l_lin, u_lin = lu(self.real_mat, permute_l=0)
+        assert_array_almost_equal(u, u_lin)
+
+    def test_zgbtrf(self):
+        """Compare zgbtrf  LU factorisation with the LU factorisation result
+           of linalg.lu."""
+        M, N = shape(self.comp_mat)
+        lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU)
+
+        # extract matrix u from lu_symm_band
+        u = diag(lu_symm_band[2*self.KL, :])
+        for i in range(self.KL + self.KU):
+            u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1)
+
+        p_lin, l_lin, u_lin = lu(self.comp_mat, permute_l=0)
+        assert_array_almost_equal(u, u_lin)
+
+    def test_dgbtrs(self):
+        """Compare dgbtrs  solutions for linear equation system  A*x = b
+           with solutions of linalg.solve."""
+
+        lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU)
+        y, info = dgbtrs(lu_symm_band, self.KL, self.KU, self.b, ipiv)
+
+        y_lin = linalg.solve(self.real_mat, self.b)
+        assert_array_almost_equal(y, y_lin)
+
+    def test_zgbtrs(self):
+        """Compare zgbtrs  solutions for linear equation system  A*x = b
+           with solutions of linalg.solve."""
+
+        lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU)
+        y, info = zgbtrs(lu_symm_band, self.KL, self.KU, self.bc, ipiv)
+
+        y_lin = linalg.solve(self.comp_mat, self.bc)
+        assert_array_almost_equal(y, y_lin)
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a_band = np.empty((0, 0), dtype=dt)
+        w, v = eig_banded(a_band)
+
+        w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=dt))
+
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype
+
+        assert v.shape == (0, 0)
+        assert v.dtype == v_n.dtype
+
+        w = eig_banded(a_band, eigvals_only=True)
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype
+
+class TestEigTridiagonal:
+    def setup_method(self):
+        self.create_trimat()
+
+    def create_trimat(self):
+        """Create the full matrix `self.fullmat`, `self.d`, and `self.e`."""
+        N = 10
+
+        # symmetric band matrix
+        self.d = full(N, 1.0)
+        self.e = full(N-1, -1.0)
+        self.full_mat = (diag(self.d) + diag(self.e, -1) + diag(self.e, 1))
+
+        ew, ev = linalg.eig(self.full_mat)
+        ew = ew.real
+        args = argsort(ew)
+        self.w = ew[args]
+        self.evec = ev[:, args]
+
+    def test_degenerate(self):
+        """Test error conditions."""
+        # Wrong sizes
+        assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e[:-1])
+        # Must be real
+        assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e * 1j)
+        # Bad driver
+        assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e,
+                      lapack_driver=1.)
+        assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+                      lapack_driver='foo')
+        # Bad bounds
+        assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+                      select='i', select_range=(0, -1))
+
+    def test_eigvalsh_tridiagonal(self):
+        """Compare eigenvalues of eigvalsh_tridiagonal with those of eig."""
+        # can't use ?STERF with subselection
+        for driver in ('sterf', 'stev', 'stebz', 'stemr', 'auto'):
+            w = eigvalsh_tridiagonal(self.d, self.e, lapack_driver=driver)
+            assert_array_almost_equal(sort(w), self.w)
+
+        for driver in ('sterf', 'stev'):
+            assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+                          lapack_driver=driver, select='i',
+                          select_range=(0, 1))
+        for driver in ('stebz', 'stemr', 'auto'):
+            # extracting eigenvalues with respect to the full index range
+            w_ind = eigvalsh_tridiagonal(
+                self.d, self.e, select='i', select_range=(0, len(self.d)-1),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w_ind), self.w)
+
+            # extracting eigenvalues with respect to an index range
+            ind1 = 2
+            ind2 = 6
+            w_ind = eigvalsh_tridiagonal(
+                self.d, self.e, select='i', select_range=(ind1, ind2),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w_ind), self.w[ind1:ind2+1])
+
+            # extracting eigenvalues with respect to a value range
+            v_lower = self.w[ind1] - 1.0e-5
+            v_upper = self.w[ind2] + 1.0e-5
+            w_val = eigvalsh_tridiagonal(
+                self.d, self.e, select='v', select_range=(v_lower, v_upper),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w_val), self.w[ind1:ind2+1])
+
+    def test_eigh_tridiagonal(self):
+        """Compare eigenvalues and eigenvectors of eigh_tridiagonal
+           with those of eig. """
+        # can't use ?STERF when eigenvectors are requested
+        assert_raises(ValueError, eigh_tridiagonal, self.d, self.e,
+                      lapack_driver='sterf')
+        for driver in ('stebz', 'stev', 'stemr', 'auto'):
+            w, evec = eigh_tridiagonal(self.d, self.e, lapack_driver=driver)
+            evec_ = evec[:, argsort(w)]
+            assert_array_almost_equal(sort(w), self.w)
+            assert_array_almost_equal(abs(evec_), abs(self.evec))
+
+        assert_raises(ValueError, eigh_tridiagonal, self.d, self.e,
+                      lapack_driver='stev', select='i', select_range=(0, 1))
+        for driver in ('stebz', 'stemr', 'auto'):
+            # extracting eigenvalues with respect to an index range
+            ind1 = 0
+            ind2 = len(self.d)-1
+            w, evec = eigh_tridiagonal(
+                self.d, self.e, select='i', select_range=(ind1, ind2),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w), self.w)
+            assert_array_almost_equal(abs(evec), abs(self.evec))
+            ind1 = 2
+            ind2 = 6
+            w, evec = eigh_tridiagonal(
+                self.d, self.e, select='i', select_range=(ind1, ind2),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w), self.w[ind1:ind2+1])
+            assert_array_almost_equal(abs(evec),
+                                      abs(self.evec[:, ind1:ind2+1]))
+
+            # extracting eigenvalues with respect to a value range
+            v_lower = self.w[ind1] - 1.0e-5
+            v_upper = self.w[ind2] + 1.0e-5
+            w, evec = eigh_tridiagonal(
+                self.d, self.e, select='v', select_range=(v_lower, v_upper),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w), self.w[ind1:ind2+1])
+            assert_array_almost_equal(abs(evec),
+                                      abs(self.evec[:, ind1:ind2+1]))
+
+    def test_eigh_tridiagonal_1x1(self):
+        """See gh-20075"""
+        a = np.array([-2.0])
+        b = np.array([])
+        x = eigh_tridiagonal(a, b, eigvals_only=True)
+        assert x.ndim == 1
+        assert_allclose(x, a)
+        x, V = eigh_tridiagonal(a, b, select="i", select_range=(0, 0))
+        assert x.ndim == 1
+        assert V.ndim == 2
+        assert_allclose(x, a)
+        assert_allclose(V, array([[1.]]))
+
+        x, V = eigh_tridiagonal(a, b, select="v", select_range=(-2, 0))
+        assert x.size == 0
+        assert x.shape == (0,)
+        assert V.shape == (1, 0)
+
+
+class TestEigh:
+    def setup_class(self):
+        np.random.seed(1234)
+
+    def test_wrong_inputs(self):
+        # Nonsquare a
+        assert_raises(ValueError, eigh, np.ones([1, 2]))
+        # Nonsquare b
+        assert_raises(ValueError, eigh, np.ones([2, 2]), np.ones([2, 1]))
+        # Incompatible a, b sizes
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([2, 2]))
+        # Wrong type parameter for generalized problem
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      type=4)
+        # Both value and index subsets requested
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_value=[1, 2], subset_by_index=[2, 4])
+        # Invalid upper index spec
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_index=[0, 4])
+        # Invalid lower index
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_index=[-2, 2])
+        # Invalid index spec #2
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_index=[2, 0])
+        # Invalid value spec
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_value=[2, 0])
+        # Invalid driver name
+        assert_raises(ValueError, eigh, np.ones([2, 2]), driver='wrong')
+        # Generalized driver selection without b
+        assert_raises(ValueError, eigh, np.ones([3, 3]), None, driver='gvx')
+        # Standard driver with b
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      driver='evr')
+        # Subset request from invalid driver
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      driver='gvd', subset_by_index=[1, 2])
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      driver='gvd', subset_by_index=[1, 2])
+
+    def test_nonpositive_b(self):
+        assert_raises(LinAlgError, eigh, np.ones([3, 3]), np.ones([3, 3]))
+
+    # index based subsets are done in the legacy test_eigh()
+    def test_value_subsets(self):
+        for ind, dt in enumerate(DTYPES):
+
+            a = _random_hermitian_matrix(20, dtype=dt)
+            w, v = eigh(a, subset_by_value=[-2, 2])
+            assert_equal(v.shape[1], len(w))
+            assert all((w > -2) & (w < 2))
+
+            b = _random_hermitian_matrix(20, posdef=True, dtype=dt)
+            w, v = eigh(a, b, subset_by_value=[-2, 2])
+            assert_equal(v.shape[1], len(w))
+            assert all((w > -2) & (w < 2))
+
+    def test_eigh_integer(self):
+        a = array([[1, 2], [2, 7]])
+        b = array([[3, 1], [1, 5]])
+        w, z = eigh(a)
+        w, z = eigh(a, b)
+
+    def test_eigh_of_sparse(self):
+        # This tests the rejection of inputs that eigh cannot currently handle.
+        import scipy.sparse
+        a = scipy.sparse.identity(2).tocsc()
+        b = np.atleast_2d(a)
+        assert_raises(ValueError, eigh, a)
+        assert_raises(ValueError, eigh, b)
+
+    @pytest.mark.parametrize('dtype_', DTYPES)
+    @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx"))
+    def test_various_drivers_standard(self, driver, dtype_):
+        a = _random_hermitian_matrix(n=20, dtype=dtype_)
+        w, v = eigh(a, driver=driver)
+        assert_allclose(a @ v - (v * w), 0.,
+                        atol=1000*np.finfo(dtype_).eps,
+                        rtol=0.)
+
+    @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx"))
+    def test_1x1_lwork(self, driver):
+        w, v = eigh([[1]], driver=driver)
+        assert_allclose(w, array([1.]), atol=1e-15)
+        assert_allclose(v, array([[1.]]), atol=1e-15)
+
+        # complex case now
+        w, v = eigh([[1j]], driver=driver)
+        assert_allclose(w, array([0]), atol=1e-15)
+        assert_allclose(v, array([[1.]]), atol=1e-15)
+
+    @pytest.mark.parametrize('type', (1, 2, 3))
+    @pytest.mark.parametrize('driver', ("gv", "gvd", "gvx"))
+    def test_various_drivers_generalized(self, driver, type):
+        atol = np.spacing(5000.)
+        a = _random_hermitian_matrix(20)
+        b = _random_hermitian_matrix(20, posdef=True)
+        w, v = eigh(a=a, b=b, driver=driver, type=type)
+        if type == 1:
+            assert_allclose(a @ v - w*(b @ v), 0., atol=atol, rtol=0.)
+        elif type == 2:
+            assert_allclose(a @ b @ v - v * w, 0., atol=atol, rtol=0.)
+        else:
+            assert_allclose(b @ a @ v - v * w, 0., atol=atol, rtol=0.)
+
+    def test_eigvalsh_new_args(self):
+        a = _random_hermitian_matrix(5)
+        w = eigvalsh(a, subset_by_index=[1, 2])
+        assert_equal(len(w), 2)
+
+        w2 = eigvalsh(a, subset_by_index=[1, 2])
+        assert_equal(len(w2), 2)
+        assert_allclose(w, w2)
+
+        b = np.diag([1, 1.2, 1.3, 1.5, 2])
+        w3 = eigvalsh(b, subset_by_value=[1, 1.4])
+        assert_equal(len(w3), 2)
+        assert_allclose(w3, np.array([1.2, 1.3]))
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        w, v = eigh(a)
+
+        w_n, v_n = eigh(np.eye(2, dtype=dt))
+
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype
+
+        assert v.shape == (0, 0)
+        assert v.dtype == v_n.dtype
+
+        w = eigh(a, eigvals_only=True)
+        assert_allclose(w, np.empty((0,)))
+
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype
+
+class TestSVD_GESDD:
+    lapack_driver = 'gesdd'
+
+    def test_degenerate(self):
+        assert_raises(TypeError, svd, [[1.]], lapack_driver=1.)
+        assert_raises(ValueError, svd, [[1.]], lapack_driver='foo')
+
+    def test_simple(self):
+        a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.T @ u, eye(3))
+            assert_array_almost_equal(vh.T @ vh, eye(3))
+            sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_simple_singular(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.T @ u, eye(3))
+            assert_array_almost_equal(vh.T @ vh, eye(3))
+            sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_simple_underdet(self):
+        a = [[1, 2, 3], [4, 5, 6]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.T @ u, eye(u.shape[0]))
+            sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_simple_overdet(self):
+        a = [[1, 2], [4, 5], [3, 4]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.T @ u, eye(u.shape[1]))
+            assert_array_almost_equal(vh.T @ vh, eye(2))
+            sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_random(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        m = 15
+        for i in range(3):
+            for a in [rng.random([n, m]), rng.random([m, n])]:
+                for full_matrices in (True, False):
+                    u, s, vh = svd(a, full_matrices=full_matrices,
+                                   lapack_driver=self.lapack_driver)
+                    assert_array_almost_equal(u.T @ u, eye(u.shape[1]))
+                    assert_array_almost_equal(vh @ vh.T, eye(vh.shape[0]))
+                    sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+                    for i in range(len(s)):
+                        sigma[i, i] = s[i]
+                    assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_simple_complex(self):
+        a = [[1, 2, 3], [1, 2j, 3], [2, 5, 6]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.conj().T @ u, eye(u.shape[1]))
+            assert_array_almost_equal(vh.conj().T @ vh, eye(vh.shape[0]))
+            sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_random_complex(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        m = 15
+        for i in range(3):
+            for full_matrices in (True, False):
+                for a in [rng.random([n, m]), rng.random([m, n])]:
+                    a = a + 1j*rng.random(list(a.shape))
+                    u, s, vh = svd(a, full_matrices=full_matrices,
+                                   lapack_driver=self.lapack_driver)
+                    assert_array_almost_equal(u.conj().T @ u,
+                                              eye(u.shape[1]))
+                    # This fails when [m,n]
+                    # assert_array_almost_equal(vh.conj().T @ vh,
+                    #                        eye(len(vh),dtype=vh.dtype.char))
+                    sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+                    for i in range(len(s)):
+                        sigma[i, i] = s[i]
+                    assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_crash_1580(self):
+        rng = np.random.RandomState(1234)
+        sizes = [(13, 23), (30, 50), (60, 100)]
+        for sz in sizes:
+            for dt in [np.float32, np.float64, np.complex64, np.complex128]:
+                a = rng.rand(*sz).astype(dt)
+                # should not crash
+                svd(a, lapack_driver=self.lapack_driver)
+
+    def test_check_finite(self):
+        a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]]
+        u, s, vh = svd(a, check_finite=False, lapack_driver=self.lapack_driver)
+        assert_array_almost_equal(u.T @ u, eye(3))
+        assert_array_almost_equal(vh.T @ vh, eye(3))
+        sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+        for i in range(len(s)):
+            sigma[i, i] = s[i]
+        assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_gh_5039(self):
+        # This is a smoke test for https://github.com/scipy/scipy/issues/5039
+        #
+        # The following is reported to raise "ValueError: On entry to DGESDD
+        # parameter number 12 had an illegal value".
+        # `interp1d([1,2,3,4], [1,2,3,4], kind='cubic')`
+        # This is reported to only show up on LAPACK 3.0.3.
+        #
+        # The matrix below is taken from the call to
+        # `B = _fitpack._bsplmat(order, xk)` in interpolate._find_smoothest
+        b = np.array(
+            [[0.16666667, 0.66666667, 0.16666667, 0., 0., 0.],
+             [0., 0.16666667, 0.66666667, 0.16666667, 0., 0.],
+             [0., 0., 0.16666667, 0.66666667, 0.16666667, 0.],
+             [0., 0., 0., 0.16666667, 0.66666667, 0.16666667]])
+        svd(b, lapack_driver=self.lapack_driver)
+
+    @pytest.mark.skipif(not HAS_ILP64, reason="64-bit LAPACK required")
+    @pytest.mark.slow
+    def test_large_matrix(self):
+        check_free_memory(free_mb=17000)
+        A = np.zeros([1, 2**31], dtype=np.float32)
+        A[0, -1] = 1
+        u, s, vh = svd(A, full_matrices=False)
+        assert_allclose(s[0], 1.0)
+        assert_allclose(u[0, 0] * vh[0, -1], 1.0)
+
+    @pytest.mark.parametrize("m", [0, 1, 2])
+    @pytest.mark.parametrize("n", [0, 1, 2])
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_shape_dtype(self, m, n, dtype):
+        a = np.zeros((m, n), dtype=dtype)
+        k = min(m, n)
+        dchar = a.dtype.char
+        real_dchar = dchar.lower() if dchar in 'FD' else dchar
+
+        u, s, v = svd(a)
+        assert_equal(u.shape, (m, m))
+        assert_equal(u.dtype, dtype)
+        assert_equal(s.shape, (k,))
+        assert_equal(s.dtype, np.dtype(real_dchar))
+        assert_equal(v.shape, (n, n))
+        assert_equal(v.dtype, dtype)
+
+        u, s, v = svd(a, full_matrices=False)
+        assert_equal(u.shape, (m, k))
+        assert_equal(u.dtype, dtype)
+        assert_equal(s.shape, (k,))
+        assert_equal(s.dtype, np.dtype(real_dchar))
+        assert_equal(v.shape, (k, n))
+        assert_equal(v.dtype, dtype)
+
+        s = svd(a, compute_uv=False)
+        assert_equal(s.shape, (k,))
+        assert_equal(s.dtype, np.dtype(real_dchar))
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+    def test_empty(self, dt, m, n):
+        a0 = np.eye(3, dtype=dt)
+        u0, s0, v0 = svd(a0)
+
+        a = np.empty((m, n), dtype=dt)
+        u, s, v = svd(a)
+        assert_allclose(u, np.identity(m))
+        assert_allclose(s, np.empty((0,)))
+        assert_allclose(v, np.identity(n))
+
+        assert u.dtype == u0.dtype
+        assert v.dtype == v0.dtype
+        assert s.dtype == s0.dtype
+
+        u, s, v = svd(a, full_matrices=False)
+        assert_allclose(u, np.empty((m, 0)))
+        assert_allclose(s, np.empty((0,)))
+        assert_allclose(v, np.empty((0, n)))
+
+        assert u.dtype == u0.dtype
+        assert v.dtype == v0.dtype
+        assert s.dtype == s0.dtype
+
+        s = svd(a, compute_uv=False)
+        assert_allclose(s, np.empty((0,)))
+
+        assert s.dtype == s0.dtype
+
+class TestSVD_GESVD(TestSVD_GESDD):
+    lapack_driver = 'gesvd'
+
+
+# Allocating an array of such a size leads to _ArrayMemoryError(s)
+# since the maximum memory that can be in 32-bit (WASM) is 4GB
+@pytest.mark.skipif(IS_WASM, reason="out of memory in WASM")
+@pytest.mark.fail_slow(10)
+def test_svd_gesdd_nofegfault():
+    # svd(a) with {U,VT}.size > INT_MAX does not segfault
+    # cf https://github.com/scipy/scipy/issues/14001
+    df=np.ones((4799, 53130), dtype=np.float64)
+    with assert_raises(ValueError):
+        svd(df)
+
+
+class TestSVDVals:
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        for a in [[]], np.empty((2, 0)), np.ones((0, 3)):
+            a = np.array(a, dtype=dt)
+            s = svdvals(a)
+            assert_equal(s, np.empty(0))
+
+            s0 = svdvals(np.eye(2, dtype=dt))
+            assert s.dtype == s0.dtype
+
+    def test_simple(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        s = svdvals(a)
+        assert_(len(s) == 3)
+        assert_(s[0] >= s[1] >= s[2])
+
+    def test_simple_underdet(self):
+        a = [[1, 2, 3], [4, 5, 6]]
+        s = svdvals(a)
+        assert_(len(s) == 2)
+        assert_(s[0] >= s[1])
+
+    def test_simple_overdet(self):
+        a = [[1, 2], [4, 5], [3, 4]]
+        s = svdvals(a)
+        assert_(len(s) == 2)
+        assert_(s[0] >= s[1])
+
+    def test_simple_complex(self):
+        a = [[1, 2, 3], [1, 20, 3j], [2, 5, 6]]
+        s = svdvals(a)
+        assert_(len(s) == 3)
+        assert_(s[0] >= s[1] >= s[2])
+
+    def test_simple_underdet_complex(self):
+        a = [[1, 2, 3], [4, 5j, 6]]
+        s = svdvals(a)
+        assert_(len(s) == 2)
+        assert_(s[0] >= s[1])
+
+    def test_simple_overdet_complex(self):
+        a = [[1, 2], [4, 5], [3j, 4]]
+        s = svdvals(a)
+        assert_(len(s) == 2)
+        assert_(s[0] >= s[1])
+
+    def test_check_finite(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        s = svdvals(a, check_finite=False)
+        assert_(len(s) == 3)
+        assert_(s[0] >= s[1] >= s[2])
+
+    @pytest.mark.slow
+    def test_crash_2609(self):
+        np.random.seed(1234)
+        a = np.random.rand(1500, 2800)
+        # Shouldn't crash:
+        svdvals(a)
+
+
+class TestDiagSVD:
+
+    def test_simple(self):
+        assert_array_almost_equal(diagsvd([1, 0, 0], 3, 3),
+                                  [[1, 0, 0], [0, 0, 0], [0, 0, 0]])
+
+
+class TestQR:
+    def test_simple(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_simple_left(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r = qr(a)
+        c = [1, 2, 3]
+        qc, r2 = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        assert_array_almost_equal(r, r2)
+        qc, r2 = qr_multiply(a, eye(3), "left")
+        assert_array_almost_equal(q, qc)
+
+    def test_simple_right(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r = qr(a)
+        c = [1, 2, 3]
+        qc, r2 = qr_multiply(a, c)
+        assert_array_almost_equal(c @ q, qc)
+        assert_array_almost_equal(r, r2)
+        qc, r = qr_multiply(a, eye(3))
+        assert_array_almost_equal(q, qc)
+
+    def test_simple_pivoting(self):
+        a = np.asarray([[8, 2, 3], [2, 9, 3], [5, 3, 6]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_left_pivoting(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r, jpvt = qr(a, pivoting=True)
+        c = [1, 2, 3]
+        qc, r, jpvt = qr_multiply(a, c, "left", True)
+        assert_array_almost_equal(q @ c, qc)
+
+    def test_simple_right_pivoting(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r, jpvt = qr(a, pivoting=True)
+        c = [1, 2, 3]
+        qc, r, jpvt = qr_multiply(a, c, pivoting=True)
+        assert_array_almost_equal(c @ q, qc)
+
+    def test_simple_trap(self):
+        a = [[8, 2, 3], [2, 9, 3]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_simple_trap_pivoting(self):
+        a = np.asarray([[8, 2, 3], [2, 9, 3]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_tall(self):
+        # full version
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_simple_tall_pivoting(self):
+        # full version pivoting
+        a = np.asarray([[8, 2], [2, 9], [5, 3]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_tall_e(self):
+        # economy version
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r = qr(a, mode='economic')
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a)
+        assert_equal(q.shape, (3, 2))
+        assert_equal(r.shape, (2, 2))
+
+    def test_simple_tall_e_pivoting(self):
+        # economy version pivoting
+        a = np.asarray([[8, 2], [2, 9], [5, 3]])
+        q, r, p = qr(a, pivoting=True, mode='economic')
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p], mode='economic')
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_tall_left(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2]
+        qc, r2 = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        assert_array_almost_equal(r, r2)
+        c = array([1, 2, 0])
+        qc, r2 = qr_multiply(a, c, "left", overwrite_c=True)
+        assert_array_almost_equal(q @ c[:2], qc)
+        qc, r = qr_multiply(a, eye(2), "left")
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_tall_left_pivoting(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r, jpvt = qr(a, mode="economic", pivoting=True)
+        c = [1, 2]
+        qc, r, kpvt = qr_multiply(a, c, "left", True)
+        assert_array_equal(jpvt, kpvt)
+        assert_array_almost_equal(q @ c, qc)
+        qc, r, jpvt = qr_multiply(a, eye(2), "left", True)
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_tall_right(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2, 3]
+        cq, r2 = qr_multiply(a, c)
+        assert_array_almost_equal(c @ q, cq)
+        assert_array_almost_equal(r, r2)
+        cq, r = qr_multiply(a, eye(3))
+        assert_array_almost_equal(cq, q)
+
+    def test_simple_tall_right_pivoting(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r, jpvt = qr(a, pivoting=True, mode="economic")
+        c = [1, 2, 3]
+        cq, r, jpvt = qr_multiply(a, c, pivoting=True)
+        assert_array_almost_equal(c @ q, cq)
+        cq, r, jpvt = qr_multiply(a, eye(3), pivoting=True)
+        assert_array_almost_equal(cq, q)
+
+    def test_simple_fat(self):
+        # full version
+        a = [[8, 2, 5], [2, 9, 3]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a)
+        assert_equal(q.shape, (2, 2))
+        assert_equal(r.shape, (2, 3))
+
+    def test_simple_fat_pivoting(self):
+        # full version pivoting
+        a = np.asarray([[8, 2, 5], [2, 9, 3]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a[:, p])
+        assert_equal(q.shape, (2, 2))
+        assert_equal(r.shape, (2, 3))
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_fat_e(self):
+        # economy version
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r = qr(a, mode='economic')
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a)
+        assert_equal(q.shape, (2, 2))
+        assert_equal(r.shape, (2, 3))
+
+    def test_simple_fat_e_pivoting(self):
+        # economy version pivoting
+        a = np.asarray([[8, 2, 3], [2, 9, 5]])
+        q, r, p = qr(a, pivoting=True, mode='economic')
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a[:, p])
+        assert_equal(q.shape, (2, 2))
+        assert_equal(r.shape, (2, 3))
+        q2, r2 = qr(a[:, p], mode='economic')
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_fat_left(self):
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2]
+        qc, r2 = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        assert_array_almost_equal(r, r2)
+        qc, r = qr_multiply(a, eye(2), "left")
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_fat_left_pivoting(self):
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r, jpvt = qr(a, mode="economic", pivoting=True)
+        c = [1, 2]
+        qc, r, jpvt = qr_multiply(a, c, "left", True)
+        assert_array_almost_equal(q @ c, qc)
+        qc, r, jpvt = qr_multiply(a, eye(2), "left", True)
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_fat_right(self):
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2]
+        cq, r2 = qr_multiply(a, c)
+        assert_array_almost_equal(c @ q, cq)
+        assert_array_almost_equal(r, r2)
+        cq, r = qr_multiply(a, eye(2))
+        assert_array_almost_equal(cq, q)
+
+    def test_simple_fat_right_pivoting(self):
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r, jpvt = qr(a, pivoting=True, mode="economic")
+        c = [1, 2]
+        cq, r, jpvt = qr_multiply(a, c, pivoting=True)
+        assert_array_almost_equal(c @ q, cq)
+        cq, r, jpvt = qr_multiply(a, eye(2), pivoting=True)
+        assert_array_almost_equal(cq, q)
+
+    def test_simple_complex(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.conj().T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_simple_complex_left(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        c = [1, 2, 3+4j]
+        qc, r = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        qc, r = qr_multiply(a, eye(3), "left")
+        assert_array_almost_equal(q, qc)
+
+    def test_simple_complex_right(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        c = [1, 2, 3+4j]
+        qc, r = qr_multiply(a, c)
+        assert_array_almost_equal(c @ q, qc)
+        qc, r = qr_multiply(a, eye(3))
+        assert_array_almost_equal(q, qc)
+
+    def test_simple_tall_complex_left(self):
+        a = [[8, 2+3j], [2, 9], [5+7j, 3]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2+2j]
+        qc, r2 = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        assert_array_almost_equal(r, r2)
+        c = array([1, 2, 0])
+        qc, r2 = qr_multiply(a, c, "left", overwrite_c=True)
+        assert_array_almost_equal(q @ c[:2], qc)
+        qc, r = qr_multiply(a, eye(2), "left")
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_complex_left_conjugate(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        c = [1, 2, 3+4j]
+        qc, r = qr_multiply(a, c, "left", conjugate=True)
+        assert_array_almost_equal(q.conj() @ c, qc)
+
+    def test_simple_complex_tall_left_conjugate(self):
+        a = [[3, 3+4j], [5, 2+2j], [3, 2]]
+        q, r = qr(a, mode='economic')
+        c = [1, 3+4j]
+        qc, r = qr_multiply(a, c, "left", conjugate=True)
+        assert_array_almost_equal(q.conj() @ c, qc)
+
+    def test_simple_complex_right_conjugate(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        c = np.array([1, 2, 3+4j])
+        qc, r = qr_multiply(a, c, conjugate=True)
+        assert_array_almost_equal(c @ q.conj(), qc)
+
+    def test_simple_complex_pivoting(self):
+        a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.conj().T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_complex_left_pivoting(self):
+        a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+        q, r, jpvt = qr(a, pivoting=True)
+        c = [1, 2, 3+4j]
+        qc, r, jpvt = qr_multiply(a, c, "left", True)
+        assert_array_almost_equal(q @ c, qc)
+
+    def test_simple_complex_right_pivoting(self):
+        a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+        q, r, jpvt = qr(a, pivoting=True)
+        c = [1, 2, 3+4j]
+        qc, r, jpvt = qr_multiply(a, c, pivoting=True)
+        assert_array_almost_equal(c @ q, qc)
+
+    def test_random(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            q, r = qr(a)
+            assert_array_almost_equal(q.T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a)
+
+    def test_random_left(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            q, r = qr(a)
+            c = rng.random([n])
+            qc, r = qr_multiply(a, c, "left")
+            assert_array_almost_equal(q @ c, qc)
+            qc, r = qr_multiply(a, eye(n), "left")
+            assert_array_almost_equal(q, qc)
+
+    def test_random_right(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            q, r = qr(a)
+            c = rng.random([n])
+            cq, r = qr_multiply(a, c)
+            assert_array_almost_equal(c @ q, cq)
+            cq, r = qr_multiply(a, eye(n))
+            assert_array_almost_equal(q, cq)
+
+    def test_random_pivoting(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            q, r, p = qr(a, pivoting=True)
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a[:, p])
+            q2, r2 = qr(a[:, p])
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_random_tall(self):
+        rng = np.random.RandomState(1234)
+        # full version
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a)
+            assert_array_almost_equal(q.T @ q, eye(m))
+            assert_array_almost_equal(q @ r, a)
+
+    def test_random_tall_left(self):
+        rng = np.random.RandomState(1234)
+        # full version
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a, mode="economic")
+            c = rng.random([n])
+            qc, r = qr_multiply(a, c, "left")
+            assert_array_almost_equal(q @ c, qc)
+            qc, r = qr_multiply(a, eye(n), "left")
+            assert_array_almost_equal(qc, q)
+
+    def test_random_tall_right(self):
+        rng = np.random.RandomState(1234)
+        # full version
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a, mode="economic")
+            c = rng.random([m])
+            cq, r = qr_multiply(a, c)
+            assert_array_almost_equal(c @ q, cq)
+            cq, r = qr_multiply(a, eye(m))
+            assert_array_almost_equal(cq, q)
+
+    def test_random_tall_pivoting(self):
+        rng = np.random.RandomState(1234)
+        # full version pivoting
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r, p = qr(a, pivoting=True)
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.T @ q, eye(m))
+            assert_array_almost_equal(q @ r, a[:, p])
+            q2, r2 = qr(a[:, p])
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_random_tall_e(self):
+        rng = np.random.RandomState(1234)
+        # economy version
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a, mode='economic')
+            assert_array_almost_equal(q.T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a)
+            assert_equal(q.shape, (m, n))
+            assert_equal(r.shape, (n, n))
+
+    def test_random_tall_e_pivoting(self):
+        rng = np.random.RandomState(1234)
+        # economy version pivoting
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r, p = qr(a, pivoting=True, mode='economic')
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a[:, p])
+            assert_equal(q.shape, (m, n))
+            assert_equal(r.shape, (n, n))
+            q2, r2 = qr(a[:, p], mode='economic')
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_random_trap(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a)
+            assert_array_almost_equal(q.T @ q, eye(m))
+            assert_array_almost_equal(q @ r, a)
+
+    def test_random_trap_pivoting(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r, p = qr(a, pivoting=True)
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.T @ q, eye(m))
+            assert_array_almost_equal(q @ r, a[:, p])
+            q2, r2 = qr(a[:, p])
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_random_complex(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            q, r = qr(a)
+            assert_array_almost_equal(q.conj().T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a)
+
+    def test_random_complex_left(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            q, r = qr(a)
+            c = rng.random([n]) + 1j*rng.random([n])
+            qc, r = qr_multiply(a, c, "left")
+            assert_array_almost_equal(q @ c, qc)
+            qc, r = qr_multiply(a, eye(n), "left")
+            assert_array_almost_equal(q, qc)
+
+    def test_random_complex_right(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            q, r = qr(a)
+            c = rng.random([n]) + 1j*rng.random([n])
+            cq, r = qr_multiply(a, c)
+            assert_array_almost_equal(c @ q, cq)
+            cq, r = qr_multiply(a, eye(n))
+            assert_array_almost_equal(q, cq)
+
+    def test_random_complex_pivoting(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            q, r, p = qr(a, pivoting=True)
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.conj().T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a[:, p])
+            q2, r2 = qr(a[:, p])
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_check_finite(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r = qr(a, check_finite=False)
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_lwork(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        # Get comparison values
+        q, r = qr(a, lwork=None)
+
+        # Test against minimum valid lwork
+        q2, r2 = qr(a, lwork=3)
+        assert_array_almost_equal(q2, q)
+        assert_array_almost_equal(r2, r)
+
+        # Test against larger lwork
+        q3, r3 = qr(a, lwork=10)
+        assert_array_almost_equal(q3, q)
+        assert_array_almost_equal(r3, r)
+
+        # Test against explicit lwork=-1
+        q4, r4 = qr(a, lwork=-1)
+        assert_array_almost_equal(q4, q)
+        assert_array_almost_equal(r4, r)
+
+        # Test against invalid lwork
+        assert_raises(Exception, qr, (a,), {'lwork': 0})
+        assert_raises(Exception, qr, (a,), {'lwork': 2})
+
+    @pytest.mark.parametrize("m", [0, 1, 2])
+    @pytest.mark.parametrize("n", [0, 1, 2])
+    @pytest.mark.parametrize("pivoting", [False, True])
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_shape_dtype(self, m, n, pivoting, dtype):
+        k = min(m, n)
+
+        a = np.zeros((m, n), dtype=dtype)
+        q, r, *other = qr(a, pivoting=pivoting)
+        assert_equal(q.shape, (m, m))
+        assert_equal(q.dtype, dtype)
+        assert_equal(r.shape, (m, n))
+        assert_equal(r.dtype, dtype)
+        assert len(other) == (1 if pivoting else 0)
+        if pivoting:
+            p, = other
+            assert_equal(p.shape, (n,))
+            assert_equal(p.dtype, np.int32)
+
+        r, *other = qr(a, mode='r', pivoting=pivoting)
+        assert_equal(r.shape, (m, n))
+        assert_equal(r.dtype, dtype)
+        assert len(other) == (1 if pivoting else 0)
+        if pivoting:
+            p, = other
+            assert_equal(p.shape, (n,))
+            assert_equal(p.dtype, np.int32)
+
+        q, r, *other = qr(a, mode='economic', pivoting=pivoting)
+        assert_equal(q.shape, (m, k))
+        assert_equal(q.dtype, dtype)
+        assert_equal(r.shape, (k, n))
+        assert_equal(r.dtype, dtype)
+        assert len(other) == (1 if pivoting else 0)
+        if pivoting:
+            p, = other
+            assert_equal(p.shape, (n,))
+            assert_equal(p.dtype, np.int32)
+
+        (raw, tau), r, *other = qr(a, mode='raw', pivoting=pivoting)
+        assert_equal(raw.shape, (m, n))
+        assert_equal(raw.dtype, dtype)
+        assert_equal(tau.shape, (k,))
+        assert_equal(tau.dtype, dtype)
+        assert_equal(r.shape, (k, n))
+        assert_equal(r.dtype, dtype)
+        assert len(other) == (1 if pivoting else 0)
+        if pivoting:
+            p, = other
+            assert_equal(p.shape, (n,))
+            assert_equal(p.dtype, np.int32)
+
+    @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+    def test_empty(self, m, n):
+        k = min(m, n)
+
+        a = np.empty((m, n))
+        q, r = qr(a)
+        assert_allclose(q, np.identity(m))
+        assert_allclose(r, np.empty((m, n)))
+
+        q, r, p = qr(a, pivoting=True)
+        assert_allclose(q, np.identity(m))
+        assert_allclose(r, np.empty((m, n)))
+        assert_allclose(p, np.arange(n))
+
+        r, = qr(a, mode='r')
+        assert_allclose(r, np.empty((m, n)))
+
+        q, r = qr(a, mode='economic')
+        assert_allclose(q, np.empty((m, k)))
+        assert_allclose(r, np.empty((k, n)))
+
+        (raw, tau), r = qr(a, mode='raw')
+        assert_allclose(raw, np.empty((m, n)))
+        assert_allclose(tau, np.empty((k,)))
+        assert_allclose(r, np.empty((k, n)))
+
+    def test_multiply_empty(self):
+        a = np.empty((0, 0))
+        c = np.empty((0, 0))
+        cq, r = qr_multiply(a, c)
+        assert_allclose(cq, np.empty((0, 0)))
+
+        a = np.empty((0, 2))
+        c = np.empty((2, 0))
+        cq, r = qr_multiply(a, c)
+        assert_allclose(cq, np.empty((2, 0)))
+
+        a = np.empty((2, 0))
+        c = np.empty((0, 2))
+        cq, r = qr_multiply(a, c)
+        assert_allclose(cq, np.empty((0, 2)))
+
+
+class TestRQ:
+    def test_simple(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        r, q = rq(a)
+        assert_array_almost_equal(q @ q.T, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_r(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        r, q = rq(a)
+        r2 = rq(a, mode='r')
+        assert_array_almost_equal(r, r2)
+
+    def test_random(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            r, q = rq(a)
+            assert_array_almost_equal(q @ q.T, eye(n))
+            assert_array_almost_equal(r @ q, a)
+
+    def test_simple_trap(self):
+        a = [[8, 2, 3], [2, 9, 3]]
+        r, q = rq(a)
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_simple_tall(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        r, q = rq(a)
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_simple_fat(self):
+        a = [[8, 2, 5], [2, 9, 3]]
+        r, q = rq(a)
+        assert_array_almost_equal(q @ q.T, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_simple_complex(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        r, q = rq(a)
+        assert_array_almost_equal(q @ q.conj().T, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_random_tall(self):
+        rng = np.random.RandomState(1234)
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            r, q = rq(a)
+            assert_array_almost_equal(q @ q.T, eye(n))
+            assert_array_almost_equal(r @ q, a)
+
+    def test_random_trap(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n])
+            r, q = rq(a)
+            assert_array_almost_equal(q @ q.T, eye(n))
+            assert_array_almost_equal(r @ q, a)
+
+    def test_random_trap_economic(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n])
+            r, q = rq(a, mode='economic')
+            assert_array_almost_equal(q @ q.T, eye(m))
+            assert_array_almost_equal(r @ q, a)
+            assert_equal(q.shape, (m, n))
+            assert_equal(r.shape, (m, m))
+
+    def test_random_complex(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            r, q = rq(a)
+            assert_array_almost_equal(q @ q.conj().T, eye(n))
+            assert_array_almost_equal(r @ q, a)
+
+    def test_random_complex_economic(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n]) + 1j*rng.random([m, n])
+            r, q = rq(a, mode='economic')
+            assert_array_almost_equal(q @ q.conj().T, eye(m))
+            assert_array_almost_equal(r @ q, a)
+            assert_equal(q.shape, (m, n))
+            assert_equal(r.shape, (m, m))
+
+    def test_check_finite(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        r, q = rq(a, check_finite=False)
+        assert_array_almost_equal(q @ q.T, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    @pytest.mark.parametrize("m", [0, 1, 2])
+    @pytest.mark.parametrize("n", [0, 1, 2])
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_shape_dtype(self, m, n, dtype):
+        k = min(m, n)
+
+        a = np.zeros((m, n), dtype=dtype)
+        r, q = rq(a)
+        assert_equal(q.shape, (n, n))
+        assert_equal(r.shape, (m, n))
+        assert_equal(r.dtype, dtype)
+        assert_equal(q.dtype, dtype)
+
+        r = rq(a, mode='r')
+        assert_equal(r.shape, (m, n))
+        assert_equal(r.dtype, dtype)
+
+        r, q = rq(a, mode='economic')
+        assert_equal(r.shape, (m, k))
+        assert_equal(r.dtype, dtype)
+        assert_equal(q.shape, (k, n))
+        assert_equal(q.dtype, dtype)
+
+    @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+    def test_empty(self, m, n):
+        k = min(m, n)
+
+        a = np.empty((m, n))
+        r, q = rq(a)
+        assert_allclose(r, np.empty((m, n)))
+        assert_allclose(q, np.identity(n))
+
+        r = rq(a, mode='r')
+        assert_allclose(r, np.empty((m, n)))
+
+        r, q = rq(a, mode='economic')
+        assert_allclose(r, np.empty((m, k)))
+        assert_allclose(q, np.empty((k, n)))
+
+
+class TestSchur:
+
+    def check_schur(self, a, t, u, rtol, atol):
+        # Check that the Schur decomposition is correct.
+        assert_allclose(u @ t @ u.conj().T, a, rtol=rtol, atol=atol,
+                        err_msg="Schur decomposition does not match 'a'")
+        # The expected value of u @ u.H - I is all zeros, so test
+        # with absolute tolerance only.
+        assert_allclose(u @ u.conj().T - np.eye(len(u)), 0, rtol=0, atol=atol,
+                        err_msg="u is not unitary")
+
+    def test_simple(self):
+        a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]]
+        t, z = schur(a)
+        self.check_schur(a, t, z, rtol=1e-14, atol=5e-15)
+        tc, zc = schur(a, 'complex')
+        assert_(np.any(ravel(iscomplex(zc))) and np.any(ravel(iscomplex(tc))))
+        self.check_schur(a, tc, zc, rtol=1e-14, atol=5e-15)
+        tc2, zc2 = rsf2csf(tc, zc)
+        self.check_schur(a, tc2, zc2, rtol=1e-14, atol=5e-15)
+
+    @pytest.mark.parametrize(
+        'sort, expected_diag',
+        [('lhp', [-np.sqrt(2), -0.5, np.sqrt(2), 0.5]),
+         ('rhp', [np.sqrt(2), 0.5, -np.sqrt(2), -0.5]),
+         ('iuc', [-0.5, 0.5, np.sqrt(2), -np.sqrt(2)]),
+         ('ouc', [np.sqrt(2), -np.sqrt(2), -0.5, 0.5]),
+         (lambda x: x >= 0.0, [np.sqrt(2), 0.5, -np.sqrt(2), -0.5])]
+    )
+    def test_sort(self, sort, expected_diag):
+        # The exact eigenvalues of this matrix are
+        #   -sqrt(2), sqrt(2), -1/2, 1/2.
+        a = [[4., 3., 1., -1.],
+             [-4.5, -3.5, -1., 1.],
+             [9., 6., -4., 4.5],
+             [6., 4., -3., 3.5]]
+        t, u, sdim = schur(a, sort=sort)
+        self.check_schur(a, t, u, rtol=1e-14, atol=5e-15)
+        assert_allclose(np.diag(t), expected_diag, rtol=1e-12)
+        assert_equal(2, sdim)
+
+    def test_sort_errors(self):
+        a = [[4., 3., 1., -1.],
+             [-4.5, -3.5, -1., 1.],
+             [9., 6., -4., 4.5],
+             [6., 4., -3., 3.5]]
+        assert_raises(ValueError, schur, a, sort='unsupported')
+        assert_raises(ValueError, schur, a, sort=1)
+
+    def test_check_finite(self):
+        a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]]
+        t, z = schur(a, check_finite=False)
+        assert_array_almost_equal(z @ t @ z.conj().T, a)
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        t, z = schur(a)
+        t0, z0 = schur(np.eye(2, dtype=dt))
+        assert_allclose(t, np.empty((0, 0)))
+        assert_allclose(z, np.empty((0, 0)))
+        assert t.dtype == t0.dtype
+        assert z.dtype == z0.dtype
+
+        t, z, sdim = schur(a, sort='lhp')
+        assert_allclose(t, np.empty((0, 0)))
+        assert_allclose(z, np.empty((0, 0)))
+        assert_equal(sdim, 0)
+        assert t.dtype == t0.dtype
+        assert z.dtype == z0.dtype
+
+    @pytest.mark.parametrize('sort', ['iuc', 'ouc'])
+    @pytest.mark.parametrize('output', ['real', 'complex'])
+    @pytest.mark.parametrize('dtype', [np.float32, np.float64,
+                                       np.complex64, np.complex128])
+    def test_gh_13137_sort_str(self, sort, output, dtype):
+        # gh-13137 reported that sort values 'iuc' and 'ouc' were not
+        # correct because the callables assumed that the eigenvalues would
+        # always be expressed as a single complex number.
+        # In fact, when `output='real'` and the dtype is real, the
+        # eigenvalues are passed as separate real and imaginary components
+        # (yet no error is raised if the callable accepts only one argument).
+        #
+        # This tests these sort values by counting the number of eigenvalues
+        # `schur` reports as being inside/outside the unit circle.
+
+        # Real matrix with eigenvalues 0.1 +- 2j
+        A = np.asarray([[0.1, -2], [2, 0.1]])
+
+        # Previously, this would fail for `output='real'` with real dtypes
+        sdim = schur(A.astype(dtype), sort=sort, output=output)[-1]
+        assert sdim == 0 if sort == 'iuc' else sdim == 2
+
+    @pytest.mark.parametrize('output', ['real', 'complex'])
+    @pytest.mark.parametrize('dtype', [np.float32, np.float64,
+                                       np.complex64, np.complex128])
+    def test_gh_13137_sort_custom(self, output, dtype):
+        # This simply tests our understanding of how eigenvalues are
+        # passed to a sort callable. If `output='real'` and the dtype is real,
+        # real and imaginary parts are passed as separate real arguments;
+        # otherwise, they are passed a single complex argument.
+        # Also, if `output='real'` and the dtype is real, when either
+        # eigenvalue in a complex conjugate pair satisfies the sort condition,
+        # `sdim` is incremented by TWO.
+
+        # Real matrix with eigenvalues 0.1 +- 2j
+        A = np.asarray([[0.1, -2], [2, 0.1]])
+
+        all_real = output=='real' and dtype in {np.float32, np.float64}
+
+        def sort(x, y=None):
+            if all_real:
+                assert not np.iscomplexobj(x)
+                assert y is not None and np.isreal(y)
+                z = x + y*1j
+            else:
+                assert np.iscomplexobj(x)
+                assert y is None
+                z = x
+            return z.imag > 1e-15
+
+        # Only one complex eigenvalue satisfies the condition, but when
+        # `all_real` applies, both eigenvalues in the complex conjugate pair
+        # are counted.
+        sdim = schur(A.astype(dtype), sort=sort, output=output)[-1]
+        assert sdim == 2 if all_real else sdim == 1
+
+
+class TestHessenberg:
+
+    def test_simple(self):
+        a = [[-149, -50, -154],
+             [537, 180, 546],
+             [-27, -9, -25]]
+        h1 = [[-149.0000, 42.2037, -156.3165],
+              [-537.6783, 152.5511, -554.9272],
+              [0, 0.0728, 2.4489]]
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q.T @ a @ q, h)
+        assert_array_almost_equal(h, h1, decimal=4)
+
+    def test_simple_complex(self):
+        a = [[-149, -50, -154],
+             [537, 180j, 546],
+             [-27j, -9, -25]]
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q.conj().T @ a @ q, h)
+
+    def test_simple2(self):
+        a = [[1, 2, 3, 4, 5, 6, 7],
+             [0, 2, 3, 4, 6, 7, 2],
+             [0, 2, 2, 3, 0, 3, 2],
+             [0, 0, 2, 8, 0, 0, 2],
+             [0, 3, 1, 2, 0, 1, 2],
+             [0, 1, 2, 3, 0, 1, 0],
+             [0, 0, 0, 0, 0, 1, 2]]
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q.T @ a @ q, h)
+
+    def test_simple3(self):
+        a = np.eye(3)
+        a[-1, 0] = 2
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q.T @ a @ q, h)
+
+    def test_random(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            h, q = hessenberg(a, calc_q=1)
+            assert_array_almost_equal(q.T @ a @ q, h)
+
+    def test_random_complex(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            h, q = hessenberg(a, calc_q=1)
+            assert_array_almost_equal(q.conj().T @ a @ q, h)
+
+    def test_check_finite(self):
+        a = [[-149, -50, -154],
+             [537, 180, 546],
+             [-27, -9, -25]]
+        h1 = [[-149.0000, 42.2037, -156.3165],
+              [-537.6783, 152.5511, -554.9272],
+              [0, 0.0728, 2.4489]]
+        h, q = hessenberg(a, calc_q=1, check_finite=False)
+        assert_array_almost_equal(q.T @ a @ q, h)
+        assert_array_almost_equal(h, h1, decimal=4)
+
+    def test_2x2(self):
+        a = [[2, 1], [7, 12]]
+
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q, np.eye(2))
+        assert_array_almost_equal(h, a)
+
+        b = [[2-7j, 1+2j], [7+3j, 12-2j]]
+        h2, q2 = hessenberg(b, calc_q=1)
+        assert_array_almost_equal(q2, np.eye(2))
+        assert_array_almost_equal(h2, b)
+
+    @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        h = hessenberg(a)
+        assert h.shape == (0, 0)
+        assert h.dtype == hessenberg(np.eye(3, dtype=dt)).dtype
+
+        h, q = hessenberg(a, calc_q=True)
+        h3, q3 = hessenberg(a, calc_q=True)
+        assert h.shape == (0, 0)
+        assert h.dtype == h3.dtype
+
+        assert q.shape == (0, 0)
+        assert q.dtype == q3.dtype
+
+
+blas_provider = blas_version = None
+if CONFIG is not None:
+    blas_provider = CONFIG['Build Dependencies']['blas']['name']
+    blas_version = CONFIG['Build Dependencies']['blas']['version']
+
+
+class TestQZ:
+    def test_qz_single(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n]).astype(float32)
+        B = rng.random([n, n]).astype(float32)
+        AA, BB, Q, Z = qz(A, B)
+        assert_array_almost_equal(Q @ AA @ Z.T, A, decimal=5)
+        assert_array_almost_equal(Q @ BB @ Z.T, B, decimal=5)
+        assert_array_almost_equal(Q @ Q.T, eye(n), decimal=5)
+        assert_array_almost_equal(Z @ Z.T, eye(n), decimal=5)
+        assert_(np.all(diag(BB) >= 0))
+
+    def test_qz_double(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n])
+        B = rng.random([n, n])
+        AA, BB, Q, Z = qz(A, B)
+        assert_array_almost_equal(Q @ AA @ Z.T, A)
+        assert_array_almost_equal(Q @ BB @ Z.T, B)
+        assert_array_almost_equal(Q @ Q.T, eye(n))
+        assert_array_almost_equal(Z @ Z.T, eye(n))
+        assert_(np.all(diag(BB) >= 0))
+
+    def test_qz_complex(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n]) + 1j*rng.random([n, n])
+        B = rng.random([n, n]) + 1j*rng.random([n, n])
+        AA, BB, Q, Z = qz(A, B)
+        assert_array_almost_equal(Q @ AA @ Z.conj().T, A)
+        assert_array_almost_equal(Q @ BB @ Z.conj().T, B)
+        assert_array_almost_equal(Q @ Q.conj().T, eye(n))
+        assert_array_almost_equal(Z @ Z.conj().T, eye(n))
+        assert_(np.all(diag(BB) >= 0))
+        assert_(np.all(diag(BB).imag == 0))
+
+    def test_qz_complex64(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64)
+        B = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64)
+        AA, BB, Q, Z = qz(A, B)
+        assert_array_almost_equal(Q @ AA @ Z.conj().T, A, decimal=5)
+        assert_array_almost_equal(Q @ BB @ Z.conj().T, B, decimal=5)
+        assert_array_almost_equal(Q @ Q.conj().T, eye(n), decimal=5)
+        assert_array_almost_equal(Z @ Z.conj().T, eye(n), decimal=5)
+        assert_(np.all(diag(BB) >= 0))
+        assert_(np.all(diag(BB).imag == 0))
+
+    def test_qz_double_complex(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n])
+        B = rng.random([n, n])
+        AA, BB, Q, Z = qz(A, B, output='complex')
+        aa = Q @ AA @ Z.conj().T
+        assert_array_almost_equal(aa.real, A)
+        assert_array_almost_equal(aa.imag, 0)
+        bb = Q @ BB @ Z.conj().T
+        assert_array_almost_equal(bb.real, B)
+        assert_array_almost_equal(bb.imag, 0)
+        assert_array_almost_equal(Q @ Q.conj().T, eye(n))
+        assert_array_almost_equal(Z @ Z.conj().T, eye(n))
+        assert_(np.all(diag(BB) >= 0))
+
+    def test_qz_double_sort(self):
+        # from https://www.nag.com/lapack-ex/node119.html
+        # NOTE: These matrices may be ill-conditioned and lead to a
+        # seg fault on certain python versions when compiled with
+        # sse2 or sse3 older ATLAS/LAPACK binaries for windows
+        # A =   np.array([[3.9,  12.5, -34.5,  -0.5],
+        #                [ 4.3,  21.5, -47.5,   7.5],
+        #                [ 4.3,  21.5, -43.5,   3.5],
+        #                [ 4.4,  26.0, -46.0,   6.0 ]])
+
+        # B = np.array([[ 1.0,   2.0,  -3.0,   1.0],
+        #              [1.0,   3.0,  -5.0,   4.0],
+        #              [1.0,   3.0,  -4.0,   3.0],
+        #              [1.0,   3.0,  -4.0,   4.0]])
+        A = np.array([[3.9, 12.5, -34.5, 2.5],
+                      [4.3, 21.5, -47.5, 7.5],
+                      [4.3, 1.5, -43.5, 3.5],
+                      [4.4, 6.0, -46.0, 6.0]])
+
+        B = np.array([[1.0, 1.0, -3.0, 1.0],
+                      [1.0, 3.0, -5.0, 4.4],
+                      [1.0, 2.0, -4.0, 1.0],
+                      [1.2, 3.0, -4.0, 4.0]])
+
+        assert_raises(ValueError, qz, A, B, sort=lambda ar, ai, beta: ai == 0)
+        if False:
+            AA, BB, Q, Z, sdim = qz(A, B, sort=lambda ar, ai, beta: ai == 0)
+            # assert_(sdim == 2)
+            assert_(sdim == 4)
+            assert_array_almost_equal(Q @ AA @ Z.T, A)
+            assert_array_almost_equal(Q @ BB @ Z.T, B)
+
+            # test absolute values bc the sign is ambiguous and
+            # might be platform dependent
+            assert_array_almost_equal(np.abs(AA), np.abs(np.array(
+                            [[35.7864, -80.9061, -12.0629, -9.498],
+                             [0., 2.7638, -2.3505, 7.3256],
+                             [0., 0., 0.6258, -0.0398],
+                             [0., 0., 0., -12.8217]])), 4)
+            assert_array_almost_equal(np.abs(BB), np.abs(np.array(
+                            [[4.5324, -8.7878, 3.2357, -3.5526],
+                             [0., 1.4314, -2.1894, 0.9709],
+                             [0., 0., 1.3126, -0.3468],
+                             [0., 0., 0., 0.559]])), 4)
+            assert_array_almost_equal(np.abs(Q), np.abs(np.array(
+                            [[-0.4193, -0.605, -0.1894, -0.6498],
+                             [-0.5495, 0.6987, 0.2654, -0.3734],
+                             [-0.4973, -0.3682, 0.6194, 0.4832],
+                             [-0.5243, 0.1008, -0.7142, 0.4526]])), 4)
+            assert_array_almost_equal(np.abs(Z), np.abs(np.array(
+                            [[-0.9471, -0.2971, -0.1217, 0.0055],
+                             [-0.0367, 0.1209, 0.0358, 0.9913],
+                             [0.3171, -0.9041, -0.2547, 0.1312],
+                             [0.0346, 0.2824, -0.9587, 0.0014]])), 4)
+
+        # test absolute values bc the sign is ambiguous and might be platform
+        # dependent
+        # assert_array_almost_equal(abs(AA), abs(np.array([
+        #                [3.8009, -69.4505, 50.3135, -43.2884],
+        #                [0.0000, 9.2033, -0.2001, 5.9881],
+        #                [0.0000, 0.0000, 1.4279, 4.4453],
+        #                [0.0000, 0.0000, 0.9019, -1.1962]])), 4)
+        # assert_array_almost_equal(abs(BB), abs(np.array([
+        #                [1.9005, -10.2285, 0.8658, -5.2134],
+        #                [0.0000,   2.3008, 0.7915,  0.4262],
+        #                [0.0000,   0.0000, 0.8101,  0.0000],
+        #                [0.0000,   0.0000, 0.0000, -0.2823]])), 4)
+        # assert_array_almost_equal(abs(Q), abs(np.array([
+        #                [0.4642,  0.7886,  0.2915, -0.2786],
+        #                [0.5002, -0.5986,  0.5638, -0.2713],
+        #                [0.5002,  0.0154, -0.0107,  0.8657],
+        #                [0.5331, -0.1395, -0.7727, -0.3151]])), 4)
+        # assert_array_almost_equal(dot(Q,Q.T), eye(4))
+        # assert_array_almost_equal(abs(Z), abs(np.array([
+        #                [0.9961, -0.0014,  0.0887, -0.0026],
+        #                [0.0057, -0.0404, -0.0938, -0.9948],
+        #                [0.0626,  0.7194, -0.6908,  0.0363],
+        #                [0.0626, -0.6934, -0.7114,  0.0956]])), 4)
+        # assert_array_almost_equal(dot(Z,Z.T), eye(4))
+
+    # def test_qz_complex_sort(self):
+    #    cA = np.array([
+    #   [-21.10+22.50*1j, 53.50+-50.50*1j, -34.50+127.50*1j, 7.50+  0.50*1j],
+    #   [-0.46+ -7.78*1j, -3.50+-37.50*1j, -15.50+ 58.50*1j,-10.50+ -1.50*1j],
+    #   [ 4.30+ -5.50*1j, 39.70+-17.10*1j, -68.50+ 12.50*1j, -7.50+ -3.50*1j],
+    #   [ 5.50+  4.40*1j, 14.40+ 43.30*1j, -32.50+-46.00*1j,-19.00+-32.50*1j]])
+
+    #    cB =  np.array([
+    #   [1.00+ -5.00*1j, 1.60+  1.20*1j,-3.00+  0.00*1j, 0.00+ -1.00*1j],
+    #   [0.80+ -0.60*1j, 3.00+ -5.00*1j,-4.00+  3.00*1j,-2.40+ -3.20*1j],
+    #   [1.00+  0.00*1j, 2.40+  1.80*1j,-4.00+ -5.00*1j, 0.00+ -3.00*1j],
+    #   [0.00+  1.00*1j,-1.80+  2.40*1j, 0.00+ -4.00*1j, 4.00+ -5.00*1j]])
+
+    #    AAS,BBS,QS,ZS,sdim = qz(cA,cB,sort='lhp')
+
+    #    eigenvalues = diag(AAS)/diag(BBS)
+    #    assert_(np.all(np.real(eigenvalues[:sdim] < 0)))
+    #    assert_(np.all(np.real(eigenvalues[sdim:] > 0)))
+
+    def test_check_finite(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n])
+        B = rng.random([n, n])
+        AA, BB, Q, Z = qz(A, B, check_finite=False)
+        assert_array_almost_equal(Q @ AA @ Z.T, A)
+        assert_array_almost_equal(Q @ BB @ Z.T, B)
+        assert_array_almost_equal(Q @ Q.T, eye(n))
+        assert_array_almost_equal(Z @ Z.T, eye(n))
+        assert_(np.all(diag(BB) >= 0))
+
+
+class TestOrdQZ:
+    @classmethod
+    def setup_class(cls):
+        # https://www.nag.com/lapack-ex/node119.html
+        A1 = np.array([[-21.10 - 22.50j, 53.5 - 50.5j, -34.5 + 127.5j,
+                        7.5 + 0.5j],
+                       [-0.46 - 7.78j, -3.5 - 37.5j, -15.5 + 58.5j,
+                        -10.5 - 1.5j],
+                       [4.30 - 5.50j, 39.7 - 17.1j, -68.5 + 12.5j,
+                        -7.5 - 3.5j],
+                       [5.50 + 4.40j, 14.4 + 43.3j, -32.5 - 46.0j,
+                        -19.0 - 32.5j]])
+
+        B1 = np.array([[1.0 - 5.0j, 1.6 + 1.2j, -3 + 0j, 0.0 - 1.0j],
+                       [0.8 - 0.6j, .0 - 5.0j, -4 + 3j, -2.4 - 3.2j],
+                       [1.0 + 0.0j, 2.4 + 1.8j, -4 - 5j, 0.0 - 3.0j],
+                       [0.0 + 1.0j, -1.8 + 2.4j, 0 - 4j, 4.0 - 5.0j]])
+
+        # https://www.nag.com/numeric/fl/nagdoc_fl23/xhtml/F08/f08yuf.xml
+        A2 = np.array([[3.9, 12.5, -34.5, -0.5],
+                       [4.3, 21.5, -47.5, 7.5],
+                       [4.3, 21.5, -43.5, 3.5],
+                       [4.4, 26.0, -46.0, 6.0]])
+
+        B2 = np.array([[1, 2, -3, 1],
+                       [1, 3, -5, 4],
+                       [1, 3, -4, 3],
+                       [1, 3, -4, 4]])
+
+        # example with the eigenvalues
+        # -0.33891648, 1.61217396+0.74013521j, 1.61217396-0.74013521j,
+        # 0.61244091
+        # thus featuring:
+        #  * one complex conjugate eigenvalue pair,
+        #  * one eigenvalue in the lhp
+        #  * 2 eigenvalues in the unit circle
+        #  * 2 non-real eigenvalues
+        A3 = np.array([[5., 1., 3., 3.],
+                       [4., 4., 2., 7.],
+                       [7., 4., 1., 3.],
+                       [0., 4., 8., 7.]])
+        B3 = np.array([[8., 10., 6., 10.],
+                       [7., 7., 2., 9.],
+                       [9., 1., 6., 6.],
+                       [5., 1., 4., 7.]])
+
+        # example with infinite eigenvalues
+        A4 = np.eye(2)
+        B4 = np.diag([0, 1])
+
+        # example with (alpha, beta) = (0, 0)
+        A5 = np.diag([1, 0])
+
+        cls.A = [A1, A2, A3, A4, A5]
+        cls.B = [B1, B2, B3, B4, A5]
+
+    def qz_decomp(self, sort):
+        with np.errstate(all='raise'):
+            ret = [ordqz(Ai, Bi, sort=sort) for Ai, Bi in zip(self.A, self.B)]
+        return tuple(ret)
+
+    def check(self, A, B, sort, AA, BB, alpha, beta, Q, Z):
+        Id = np.eye(*A.shape)
+        # make sure Q and Z are orthogonal
+        assert_array_almost_equal(Q @ Q.T.conj(), Id)
+        assert_array_almost_equal(Z @ Z.T.conj(), Id)
+        # check factorization
+        assert_array_almost_equal(Q @ AA, A @ Z)
+        assert_array_almost_equal(Q @ BB, B @ Z)
+        # check shape of AA and BB
+        assert_array_equal(np.tril(AA, -2), np.zeros(AA.shape))
+        assert_array_equal(np.tril(BB, -1), np.zeros(BB.shape))
+        # check eigenvalues
+        for i in range(A.shape[0]):
+            # does the current diagonal element belong to a 2-by-2 block
+            # that was already checked?
+            if i > 0 and A[i, i - 1] != 0:
+                continue
+            # take care of 2-by-2 blocks
+            if i < AA.shape[0] - 1 and AA[i + 1, i] != 0:
+                evals, _ = eig(AA[i:i + 2, i:i + 2], BB[i:i + 2, i:i + 2])
+                # make sure the pair of complex conjugate eigenvalues
+                # is ordered consistently (positive imaginary part first)
+                if evals[0].imag < 0:
+                    evals = evals[[1, 0]]
+                tmp = alpha[i:i + 2]/beta[i:i + 2]
+                if tmp[0].imag < 0:
+                    tmp = tmp[[1, 0]]
+                assert_array_almost_equal(evals, tmp)
+            else:
+                if alpha[i] == 0 and beta[i] == 0:
+                    assert_equal(AA[i, i], 0)
+                    assert_equal(BB[i, i], 0)
+                elif beta[i] == 0:
+                    assert_equal(BB[i, i], 0)
+                else:
+                    assert_almost_equal(AA[i, i]/BB[i, i], alpha[i]/beta[i])
+        sortfun = _select_function(sort)
+        lastsort = True
+        for i in range(A.shape[0]):
+            cursort = sortfun(np.array([alpha[i]]), np.array([beta[i]]))
+            # once the sorting criterion was not matched all subsequent
+            # eigenvalues also shouldn't match
+            if not lastsort:
+                assert not cursort
+            lastsort = cursort
+
+    def check_all(self, sort):
+        ret = self.qz_decomp(sort)
+
+        for reti, Ai, Bi in zip(ret, self.A, self.B):
+            self.check(Ai, Bi, sort, *reti)
+
+    def test_lhp(self):
+        self.check_all('lhp')
+
+    def test_rhp(self):
+        self.check_all('rhp')
+
+    def test_iuc(self):
+        self.check_all('iuc')
+
+    def test_ouc(self):
+        self.check_all('ouc')
+
+    def test_ref(self):
+        # real eigenvalues first (top-left corner)
+        def sort(x, y):
+            out = np.empty_like(x, dtype=bool)
+            nonzero = (y != 0)
+            out[~nonzero] = False
+            out[nonzero] = (x[nonzero]/y[nonzero]).imag == 0
+            return out
+
+        self.check_all(sort)
+
+    def test_cef(self):
+        # complex eigenvalues first (top-left corner)
+        def sort(x, y):
+            out = np.empty_like(x, dtype=bool)
+            nonzero = (y != 0)
+            out[~nonzero] = False
+            out[nonzero] = (x[nonzero]/y[nonzero]).imag != 0
+            return out
+
+        self.check_all(sort)
+
+    def test_diff_input_types(self):
+        ret = ordqz(self.A[1], self.B[2], sort='lhp')
+        self.check(self.A[1], self.B[2], 'lhp', *ret)
+
+        ret = ordqz(self.B[2], self.A[1], sort='lhp')
+        self.check(self.B[2], self.A[1], 'lhp', *ret)
+
+    def test_sort_explicit(self):
+        # Test order of the eigenvalues in the 2 x 2 case where we can
+        # explicitly compute the solution
+        A1 = np.eye(2)
+        B1 = np.diag([-2, 0.5])
+        expected1 = [('lhp', [-0.5, 2]),
+                     ('rhp', [2, -0.5]),
+                     ('iuc', [-0.5, 2]),
+                     ('ouc', [2, -0.5])]
+        A2 = np.eye(2)
+        B2 = np.diag([-2 + 1j, 0.5 + 0.5j])
+        expected2 = [('lhp', [1/(-2 + 1j), 1/(0.5 + 0.5j)]),
+                     ('rhp', [1/(0.5 + 0.5j), 1/(-2 + 1j)]),
+                     ('iuc', [1/(-2 + 1j), 1/(0.5 + 0.5j)]),
+                     ('ouc', [1/(0.5 + 0.5j), 1/(-2 + 1j)])]
+        # 'lhp' is ambiguous so don't test it
+        A3 = np.eye(2)
+        B3 = np.diag([2, 0])
+        expected3 = [('rhp', [0.5, np.inf]),
+                     ('iuc', [0.5, np.inf]),
+                     ('ouc', [np.inf, 0.5])]
+        # 'rhp' is ambiguous so don't test it
+        A4 = np.eye(2)
+        B4 = np.diag([-2, 0])
+        expected4 = [('lhp', [-0.5, np.inf]),
+                     ('iuc', [-0.5, np.inf]),
+                     ('ouc', [np.inf, -0.5])]
+        A5 = np.diag([0, 1])
+        B5 = np.diag([0, 0.5])
+        # 'lhp' and 'iuc' are ambiguous so don't test them
+        expected5 = [('rhp', [2, np.nan]),
+                     ('ouc', [2, np.nan])]
+
+        A = [A1, A2, A3, A4, A5]
+        B = [B1, B2, B3, B4, B5]
+        expected = [expected1, expected2, expected3, expected4, expected5]
+        for Ai, Bi, expectedi in zip(A, B, expected):
+            for sortstr, expected_eigvals in expectedi:
+                _, _, alpha, beta, _, _ = ordqz(Ai, Bi, sort=sortstr)
+                azero = (alpha == 0)
+                bzero = (beta == 0)
+                x = np.empty_like(alpha)
+                x[azero & bzero] = np.nan
+                x[~azero & bzero] = np.inf
+                x[~bzero] = alpha[~bzero]/beta[~bzero]
+                assert_allclose(expected_eigvals, x)
+
+
+class TestOrdQZWorkspaceSize:
+    @pytest.mark.fail_slow(5)
+    def test_decompose(self):
+        rng = np.random.RandomState(12345)
+        N = 202
+        # raises error if lwork parameter to dtrsen is too small
+        for ddtype in [np.float32, np.float64]:
+            A = rng.random((N, N)).astype(ddtype)
+            B = rng.random((N, N)).astype(ddtype)
+            # sort = lambda ar, ai, b: ar**2 + ai**2 < b**2
+            _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta,
+                      output='real')
+
+        for ddtype in [np.complex128, np.complex64]:
+            A = rng.random((N, N)).astype(ddtype)
+            B = rng.random((N, N)).astype(ddtype)
+            _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta,
+                      output='complex')
+
+    @pytest.mark.slow
+    def test_decompose_ouc(self):
+        rng = np.random.RandomState(12345)
+        N = 202
+        # segfaults if lwork parameter to dtrsen is too small
+        for ddtype in [np.float32, np.float64, np.complex128, np.complex64]:
+            A = rng.random((N, N)).astype(ddtype)
+            B = rng.random((N, N)).astype(ddtype)
+            S, T, alpha, beta, U, V = ordqz(A, B, sort='ouc')
+
+
+class TestDatacopied:
+
+    def test_datacopied(self):
+        from scipy.linalg._decomp import _datacopied
+
+        M = matrix([[0, 1], [2, 3]])
+        A = asarray(M)
+        L = M.tolist()
+        M2 = M.copy()
+
+        class Fake1:
+            def __array__(self, dtype=None, copy=None):
+                return A
+
+        class Fake2:
+            __array_interface__ = A.__array_interface__
+
+        F1 = Fake1()
+        F2 = Fake2()
+
+        for item, status in [(M, False), (A, False), (L, True),
+                             (M2, False), (F1, False), (F2, False)]:
+            arr = asarray(item)
+            assert_equal(_datacopied(arr, item), status,
+                         err_msg=repr(item))
+
+
+def test_aligned_mem_float():
+    """Check linalg works with non-aligned memory (float32)"""
+    # Allocate 402 bytes of memory (allocated on boundary)
+    a = arange(402, dtype=np.uint8)
+
+    # Create an array with boundary offset 4
+    z = np.frombuffer(a.data, offset=2, count=100, dtype=float32)
+    z.shape = 10, 10
+
+    eig(z, overwrite_a=True)
+    eig(z.T, overwrite_a=True)
+
+
+@pytest.mark.skipif(platform.machine() == 'ppc64le',
+                    reason="crashes on ppc64le")
+def test_aligned_mem():
+    """Check linalg works with non-aligned memory (float64)"""
+    # Allocate 804 bytes of memory (allocated on boundary)
+    a = arange(804, dtype=np.uint8)
+
+    # Create an array with boundary offset 4
+    z = np.frombuffer(a.data, offset=4, count=100, dtype=float)
+    z.shape = 10, 10
+
+    eig(z, overwrite_a=True)
+    eig(z.T, overwrite_a=True)
+
+
+def test_aligned_mem_complex():
+    """Check that complex objects don't need to be completely aligned"""
+    # Allocate 1608 bytes of memory (allocated on boundary)
+    a = zeros(1608, dtype=np.uint8)
+
+    # Create an array with boundary offset 8
+    z = np.frombuffer(a.data, offset=8, count=100, dtype=complex)
+    z.shape = 10, 10
+
+    eig(z, overwrite_a=True)
+    # This does not need special handling
+    eig(z.T, overwrite_a=True)
+
+
+def check_lapack_misaligned(func, args, kwargs):
+    args = list(args)
+    for i in range(len(args)):
+        a = args[:]
+        if isinstance(a[i], np.ndarray):
+            # Try misaligning a[i]
+            aa = np.zeros(a[i].size*a[i].dtype.itemsize+8, dtype=np.uint8)
+            aa = np.frombuffer(aa.data, offset=4, count=a[i].size,
+                               dtype=a[i].dtype)
+            aa.shape = a[i].shape
+            aa[...] = a[i]
+            a[i] = aa
+            func(*a, **kwargs)
+            if len(a[i].shape) > 1:
+                a[i] = a[i].T
+                func(*a, **kwargs)
+
+
+@pytest.mark.xfail(run=False,
+                   reason="Ticket #1152, triggers a segfault in rare cases.")
+def test_lapack_misaligned():
+    M = np.eye(10, dtype=float)
+    R = np.arange(100)
+    R.shape = 10, 10
+    S = np.arange(20000, dtype=np.uint8)
+    S = np.frombuffer(S.data, offset=4, count=100, dtype=float)
+    S.shape = 10, 10
+    b = np.ones(10)
+    LU, piv = lu_factor(S)
+    for (func, args, kwargs) in [
+            (eig, (S,), dict(overwrite_a=True)),  # crash
+            (eigvals, (S,), dict(overwrite_a=True)),  # no crash
+            (lu, (S,), dict(overwrite_a=True)),  # no crash
+            (lu_factor, (S,), dict(overwrite_a=True)),  # no crash
+            (lu_solve, ((LU, piv), b), dict(overwrite_b=True)),
+            (solve, (S, b), dict(overwrite_a=True, overwrite_b=True)),
+            (svd, (M,), dict(overwrite_a=True)),  # no crash
+            (svd, (R,), dict(overwrite_a=True)),  # no crash
+            (svd, (S,), dict(overwrite_a=True)),  # crash
+            (svdvals, (S,), dict()),  # no crash
+            (svdvals, (S,), dict(overwrite_a=True)),  # crash
+            (cholesky, (M,), dict(overwrite_a=True)),  # no crash
+            (qr, (S,), dict(overwrite_a=True)),  # crash
+            (rq, (S,), dict(overwrite_a=True)),  # crash
+            (hessenberg, (S,), dict(overwrite_a=True)),  # crash
+            (schur, (S,), dict(overwrite_a=True)),  # crash
+            ]:
+        check_lapack_misaligned(func, args, kwargs)
+# not properly tested
+# cholesky, rsf2csf, lu_solve, solve, eig_banded, eigvals_banded, eigh, diagsvd
+
+
+class TestOverwrite:
+    def test_eig(self):
+        assert_no_overwrite(eig, [(3, 3)])
+        assert_no_overwrite(eig, [(3, 3), (3, 3)])
+
+    def test_eigh(self):
+        assert_no_overwrite(eigh, [(3, 3)])
+        assert_no_overwrite(eigh, [(3, 3), (3, 3)])
+
+    def test_eig_banded(self):
+        assert_no_overwrite(eig_banded, [(3, 2)])
+
+    def test_eigvals(self):
+        assert_no_overwrite(eigvals, [(3, 3)])
+
+    def test_eigvalsh(self):
+        assert_no_overwrite(eigvalsh, [(3, 3)])
+
+    def test_eigvals_banded(self):
+        assert_no_overwrite(eigvals_banded, [(3, 2)])
+
+    def test_hessenberg(self):
+        assert_no_overwrite(hessenberg, [(3, 3)])
+
+    def test_lu_factor(self):
+        assert_no_overwrite(lu_factor, [(3, 3)])
+
+    def test_lu_solve(self):
+        x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 8]])
+        xlu = lu_factor(x)
+        assert_no_overwrite(lambda b: lu_solve(xlu, b), [(3,)])
+
+    def test_lu(self):
+        assert_no_overwrite(lu, [(3, 3)])
+
+    def test_qr(self):
+        assert_no_overwrite(qr, [(3, 3)])
+
+    def test_rq(self):
+        assert_no_overwrite(rq, [(3, 3)])
+
+    def test_schur(self):
+        assert_no_overwrite(schur, [(3, 3)])
+
+    def test_schur_complex(self):
+        assert_no_overwrite(lambda a: schur(a, 'complex'), [(3, 3)],
+                            dtypes=[np.float32, np.float64])
+
+    def test_svd(self):
+        assert_no_overwrite(svd, [(3, 3)])
+        assert_no_overwrite(lambda a: svd(a, lapack_driver='gesvd'), [(3, 3)])
+
+    def test_svdvals(self):
+        assert_no_overwrite(svdvals, [(3, 3)])
+
+
+def _check_orth(n, dtype, skip_big=False):
+    X = np.ones((n, 2), dtype=float).astype(dtype)
+
+    eps = np.finfo(dtype).eps
+    tol = 1000 * eps
+
+    Y = orth(X)
+    assert_equal(Y.shape, (n, 1))
+    assert_allclose(Y, Y.mean(), atol=tol)
+
+    Y = orth(X.T)
+    assert_equal(Y.shape, (2, 1))
+    assert_allclose(Y, Y.mean(), atol=tol)
+
+    if n > 5 and not skip_big:
+        rng = np.random.RandomState(1)
+        X = rng.rand(n, 5) @ rng.rand(5, n)
+        X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n)
+        X = X.astype(dtype)
+
+        Y = orth(X, rcond=1e-3)
+        assert_equal(Y.shape, (n, 5))
+
+        Y = orth(X, rcond=1e-6)
+        assert_equal(Y.shape, (n, 5 + 1))
+
+
+@pytest.mark.slow
+@pytest.mark.skipif(np.dtype(np.intp).itemsize < 8,
+                    reason="test only on 64-bit, else too slow")
+def test_orth_memory_efficiency():
+    # Pick n so that 16*n bytes is reasonable but 8*n*n bytes is unreasonable.
+    # Keep in mind that @pytest.mark.slow tests are likely to be running
+    # under configurations that support 4Gb+ memory for tests related to
+    # 32 bit overflow.
+    n = 10*1000*1000
+    try:
+        _check_orth(n, np.float64, skip_big=True)
+    except MemoryError as e:
+        raise AssertionError(
+            'memory error perhaps caused by orth regression'
+        ) from e
+
+
+def test_orth():
+    dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+    sizes = [1, 2, 3, 10, 100]
+    for dt, n in itertools.product(dtypes, sizes):
+        _check_orth(n, dt)
+
+@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+def test_orth_empty(dt):
+    a = np.empty((0, 0), dtype=dt)
+    a0 = np.eye(2, dtype=dt)
+
+    oa = orth(a)
+    assert oa.dtype == orth(a0).dtype
+    assert oa.shape == (0, 0)
+
+
+class TestNullSpace:
+    def test_null_space(self):
+        rng = np.random.RandomState(1)
+
+        dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+        sizes = [1, 2, 3, 10, 100]
+
+        for dt, n in itertools.product(dtypes, sizes):
+            X = np.ones((2, n), dtype=dt)
+
+            eps = np.finfo(dt).eps
+            tol = 1000 * eps
+
+            Y = null_space(X)
+            assert_equal(Y.shape, (n, n-1))
+            assert_allclose(X @ Y, 0, atol=tol)
+
+            Y = null_space(X.T)
+            assert_equal(Y.shape, (2, 1))
+            assert_allclose(X.T @ Y, 0, atol=tol)
+
+            X = rng.randn(1 + n//2, n)
+            Y = null_space(X)
+            assert_equal(Y.shape, (n, n - 1 - n//2))
+            assert_allclose(X @ Y, 0, atol=tol)
+
+            if n > 5:
+                rng = np.random.RandomState(1)
+                X = rng.rand(n, 5) @ rng.rand(5, n)
+                X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n)
+                X = X.astype(dt)
+
+                Y = null_space(X, rcond=1e-3)
+                assert_equal(Y.shape, (n, n - 5))
+
+                Y = null_space(X, rcond=1e-6)
+                assert_equal(Y.shape, (n, n - 6))
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_null_space_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        a0 = np.eye(2, dtype=dt)
+        nsa = null_space(a)
+
+        assert nsa.shape == (0, 0)
+        assert nsa.dtype == null_space(a0).dtype
+
+    @pytest.mark.parametrize("overwrite_a", [True, False])
+    @pytest.mark.parametrize("check_finite", [True, False])
+    @pytest.mark.parametrize("lapack_driver", ["gesdd", "gesvd"])
+    def test_null_space_options(self, overwrite_a, check_finite, lapack_driver):
+        rng = np.random.default_rng(42887289350573064398746)
+        n = 10
+        X = rng.standard_normal((1 + n//2, n))
+        Y = null_space(X.copy(), overwrite_a=overwrite_a, check_finite=check_finite,
+                       lapack_driver=lapack_driver)
+        assert_allclose(X @ Y, 0, atol=np.finfo(X.dtype).eps*100)
+
+
+def test_subspace_angles():
+    H = hadamard(8, float)
+    A = H[:, :3]
+    B = H[:, 3:]
+    assert_allclose(subspace_angles(A, B), [np.pi / 2.] * 3, atol=1e-14)
+    assert_allclose(subspace_angles(B, A), [np.pi / 2.] * 3, atol=1e-14)
+    for x in (A, B):
+        assert_allclose(subspace_angles(x, x), np.zeros(x.shape[1]),
+                        atol=1e-14)
+    # From MATLAB function "subspace", which effectively only returns the
+    # last value that we calculate
+    x = np.array(
+        [[0.537667139546100, 0.318765239858981, 3.578396939725760, 0.725404224946106],  # noqa: E501
+         [1.833885014595086, -1.307688296305273, 2.769437029884877, -0.063054873189656],  # noqa: E501
+         [-2.258846861003648, -0.433592022305684, -1.349886940156521, 0.714742903826096],  # noqa: E501
+         [0.862173320368121, 0.342624466538650, 3.034923466331855, -0.204966058299775]])  # noqa: E501
+    expected = 1.481454682101605
+    assert_allclose(subspace_angles(x[:, :2], x[:, 2:])[0], expected,
+                    rtol=1e-12)
+    assert_allclose(subspace_angles(x[:, 2:], x[:, :2])[0], expected,
+                    rtol=1e-12)
+    expected = 0.746361174247302
+    assert_allclose(subspace_angles(x[:, :2], x[:, [2]]), expected, rtol=1e-12)
+    assert_allclose(subspace_angles(x[:, [2]], x[:, :2]), expected, rtol=1e-12)
+    expected = 0.487163718534313
+    assert_allclose(subspace_angles(x[:, :3], x[:, [3]]), expected, rtol=1e-12)
+    assert_allclose(subspace_angles(x[:, [3]], x[:, :3]), expected, rtol=1e-12)
+    expected = 0.328950515907756
+    assert_allclose(subspace_angles(x[:, :2], x[:, 1:]), [expected, 0],
+                    atol=1e-12)
+    # Degenerate conditions
+    assert_raises(ValueError, subspace_angles, x[0], x)
+    assert_raises(ValueError, subspace_angles, x, x[0])
+    assert_raises(ValueError, subspace_angles, x[:-1], x)
+
+    # Test branch if mask.any is True:
+    A = np.array([[1, 0, 0],
+                  [0, 1, 0],
+                  [0, 0, 1],
+                  [0, 0, 0],
+                  [0, 0, 0]])
+    B = np.array([[1, 0, 0],
+                  [0, 1, 0],
+                  [0, 0, 0],
+                  [0, 0, 0],
+                  [0, 0, 1]])
+    expected = np.array([np.pi/2, 0, 0])
+    assert_allclose(subspace_angles(A, B), expected, rtol=1e-12)
+
+    # Complex
+    # second column in "b" does not affect result, just there so that
+    # b can have more cols than a, and vice-versa (both conditional code paths)
+    a = [[1 + 1j], [0]]
+    b = [[1 - 1j, 0], [0, 1]]
+    assert_allclose(subspace_angles(a, b), 0., atol=1e-14)
+    assert_allclose(subspace_angles(b, a), 0., atol=1e-14)
+
+    # Empty
+    a = np.empty((0, 0))
+    b = np.empty((0, 0))
+    assert_allclose(subspace_angles(a, b), np.empty((0,)))
+    a = np.empty((2, 0))
+    b = np.empty((2, 0))
+    assert_allclose(subspace_angles(a, b), np.empty((0,)))
+    a = np.empty((0, 2))
+    b = np.empty((0, 3))
+    assert_allclose(subspace_angles(a, b), np.empty((0,)))
+
+
+class TestCDF2RDF:
+
+    def matmul(self, a, b):
+        return np.einsum('...ij,...jk->...ik', a, b)
+
+    def assert_eig_valid(self, w, v, x):
+        assert_array_almost_equal(
+            self.matmul(v, w),
+            self.matmul(x, v)
+        )
+
+    def test_single_array0x0real(self):
+        # eig doesn't support 0x0 in old versions of numpy
+        X = np.empty((0, 0))
+        w, v = np.empty(0), np.empty((0, 0))
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_single_array2x2_real(self):
+        X = np.array([[1, 2], [3, -1]])
+        w, v = np.linalg.eig(X)
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_single_array2x2_complex(self):
+        X = np.array([[1, 2], [-2, 1]])
+        w, v = np.linalg.eig(X)
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_single_array3x3_real(self):
+        X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+        w, v = np.linalg.eig(X)
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_single_array3x3_complex(self):
+        X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+        w, v = np.linalg.eig(X)
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_random_1d_stacked_arrays(self):
+        # cannot test M == 0 due to bug in old numpy
+        for M in range(1, 7):
+            np.random.seed(999999999)
+            X = np.random.rand(100, M, M)
+            w, v = np.linalg.eig(X)
+            wr, vr = cdf2rdf(w, v)
+            self.assert_eig_valid(wr, vr, X)
+
+    def test_random_2d_stacked_arrays(self):
+        # cannot test M == 0 due to bug in old numpy
+        for M in range(1, 7):
+            X = np.random.rand(10, 10, M, M)
+            w, v = np.linalg.eig(X)
+            wr, vr = cdf2rdf(w, v)
+            self.assert_eig_valid(wr, vr, X)
+
+    def test_low_dimensionality_error(self):
+        w, v = np.empty(()), np.array((2,))
+        assert_raises(ValueError, cdf2rdf, w, v)
+
+    def test_not_square_error(self):
+        # Check that passing a non-square array raises a ValueError.
+        w, v = np.arange(3), np.arange(6).reshape(3, 2)
+        assert_raises(ValueError, cdf2rdf, w, v)
+
+    def test_swapped_v_w_error(self):
+        # Check that exchanging places of w and v raises ValueError.
+        X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+        w, v = np.linalg.eig(X)
+        assert_raises(ValueError, cdf2rdf, v, w)
+
+    def test_non_associated_error(self):
+        # Check that passing non-associated eigenvectors raises a ValueError.
+        w, v = np.arange(3), np.arange(16).reshape(4, 4)
+        assert_raises(ValueError, cdf2rdf, w, v)
+
+    def test_not_conjugate_pairs(self):
+        # Check that passing non-conjugate pairs raises a ValueError.
+        X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]])
+        w, v = np.linalg.eig(X)
+        assert_raises(ValueError, cdf2rdf, w, v)
+
+        # different arrays in the stack, so not conjugate
+        X = np.array([
+            [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]],
+            [[1, 2, 3], [1, 2, 3], [2, 5, 6-1j]],
+        ])
+        w, v = np.linalg.eig(X)
+        assert_raises(ValueError, cdf2rdf, w, v)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..61bbc7e544f10fc834034fbadd7141f6deb1d423
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
@@ -0,0 +1,268 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_array_almost_equal
+from pytest import raises as assert_raises
+
+from numpy import array, transpose, dot, conjugate, zeros_like, empty
+from numpy.random import random
+from scipy.linalg import (cholesky, cholesky_banded, cho_solve_banded,
+     cho_factor, cho_solve)
+
+from scipy.linalg._testutils import assert_no_overwrite
+
+
+class TestCholesky:
+
+    def test_simple(self):
+        a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
+        c = cholesky(a)
+        assert_array_almost_equal(dot(transpose(c), c), a)
+        c = transpose(c)
+        a = dot(c, transpose(c))
+        assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_check_finite(self):
+        a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
+        c = cholesky(a, check_finite=False)
+        assert_array_almost_equal(dot(transpose(c), c), a)
+        c = transpose(c)
+        a = dot(c, transpose(c))
+        assert_array_almost_equal(cholesky(a, lower=1, check_finite=False), c)
+
+    def test_simple_complex(self):
+        m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]])
+        a = dot(transpose(conjugate(m)), m)
+        c = cholesky(a)
+        a1 = dot(transpose(conjugate(c)), c)
+        assert_array_almost_equal(a, a1)
+        c = transpose(c)
+        a = dot(c, transpose(conjugate(c)))
+        assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_random(self):
+        n = 20
+        for k in range(2):
+            m = random([n, n])
+            for i in range(n):
+                m[i, i] = 20*(.1+m[i, i])
+            a = dot(transpose(m), m)
+            c = cholesky(a)
+            a1 = dot(transpose(c), c)
+            assert_array_almost_equal(a, a1)
+            c = transpose(c)
+            a = dot(c, transpose(c))
+            assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_random_complex(self):
+        n = 20
+        for k in range(2):
+            m = random([n, n])+1j*random([n, n])
+            for i in range(n):
+                m[i, i] = 20*(.1+abs(m[i, i]))
+            a = dot(transpose(conjugate(m)), m)
+            c = cholesky(a)
+            a1 = dot(transpose(conjugate(c)), c)
+            assert_array_almost_equal(a, a1)
+            c = transpose(c)
+            a = dot(c, transpose(conjugate(c)))
+            assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    @pytest.mark.xslow
+    def test_int_overflow(self):
+       # regression test for
+       # https://github.com/scipy/scipy/issues/17436
+       # the problem was an int overflow in zeroing out
+       # the unused triangular part
+       n = 47_000
+       x = np.eye(n, dtype=np.float64, order='F')
+       x[:4, :4] = np.array([[4, -2, 3, -1],
+                             [-2, 4, -3, 1],
+                             [3, -3, 5, 0],
+                             [-1, 1, 0, 5]])
+
+       cholesky(x, check_finite=False, overwrite_a=True)  # should not segfault
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt, dt_b):
+        a = empty((0, 0), dtype=dt)
+
+        c = cholesky(a)
+        assert c.shape == (0, 0)
+        assert c.dtype == cholesky(np.eye(2, dtype=dt)).dtype
+
+        c_and_lower = (c, True)
+        b = np.asarray([], dtype=dt_b)
+        x = cho_solve(c_and_lower, b)
+        assert x.shape == (0,)
+        assert x.dtype == cho_solve((np.eye(2, dtype=dt), True),
+                                     np.ones(2, dtype=dt_b)).dtype
+
+        b = empty((0, 0), dtype=dt_b)
+        x = cho_solve(c_and_lower, b)
+        assert x.shape == (0, 0)
+        assert x.dtype == cho_solve((np.eye(2, dtype=dt), True),
+                                     np.ones(2, dtype=dt_b)).dtype
+
+        a1 = array([])
+        a2 = array([[]])
+        a3 = []
+        a4 = [[]]
+        for x in ([a1, a2, a3, a4]):
+            assert_raises(ValueError, cholesky, x)
+
+
+class TestCholeskyBanded:
+    """Tests for cholesky_banded() and cho_solve_banded."""
+
+    def test_check_finite(self):
+        # Symmetric positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, 0.2],
+                   [0.0, 0.0, 0.2, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[-1.0, 1.0, 0.5, 0.2],
+                    [4.0, 4.0, 4.0, 4.0]])
+        c = cholesky_banded(ab, lower=False, check_finite=False)
+        ufac = zeros_like(a)
+        ufac[list(range(4)), list(range(4))] = c[-1]
+        ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+        assert_array_almost_equal(a, dot(ufac.T, ufac))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, False), b, check_finite=False)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    def test_upper_real(self):
+        # Symmetric positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, 0.2],
+                   [0.0, 0.0, 0.2, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[-1.0, 1.0, 0.5, 0.2],
+                    [4.0, 4.0, 4.0, 4.0]])
+        c = cholesky_banded(ab, lower=False)
+        ufac = zeros_like(a)
+        ufac[list(range(4)), list(range(4))] = c[-1]
+        ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+        assert_array_almost_equal(a, dot(ufac.T, ufac))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, False), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    def test_upper_complex(self):
+        # Hermitian positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, -0.2j],
+                   [0.0, 0.0, 0.2j, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[-1.0, 1.0, 0.5, -0.2j],
+                    [4.0, 4.0, 4.0, 4.0]])
+        c = cholesky_banded(ab, lower=False)
+        ufac = zeros_like(a)
+        ufac[list(range(4)), list(range(4))] = c[-1]
+        ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+        assert_array_almost_equal(a, dot(ufac.conj().T, ufac))
+
+        b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0])
+        x = cho_solve_banded((c, False), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    def test_lower_real(self):
+        # Symmetric positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, 0.2],
+                   [0.0, 0.0, 0.2, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[4.0, 4.0, 4.0, 4.0],
+                    [1.0, 0.5, 0.2, -1.0]])
+        c = cholesky_banded(ab, lower=True)
+        lfac = zeros_like(a)
+        lfac[list(range(4)), list(range(4))] = c[0]
+        lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
+        assert_array_almost_equal(a, dot(lfac, lfac.T))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, True), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    def test_lower_complex(self):
+        # Hermitian positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, -0.2j],
+                   [0.0, 0.0, 0.2j, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[4.0, 4.0, 4.0, 4.0],
+                    [1.0, 0.5, 0.2j, -1.0]])
+        c = cholesky_banded(ab, lower=True)
+        lfac = zeros_like(a)
+        lfac[list(range(4)), list(range(4))] = c[0]
+        lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
+        assert_array_almost_equal(a, dot(lfac, lfac.conj().T))
+
+        b = array([0.0, 0.5j, 3.8j, 3.8])
+        x = cho_solve_banded((c, True), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0j, 1.0])
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt, dt_b):
+        ab = empty((0, 0), dtype=dt)
+
+        cb = cholesky_banded(ab)
+        assert cb.shape == (0, 0)
+
+        m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=dt))
+        assert cb.dtype == m.dtype
+
+        cb_and_lower = (cb, True)
+        b = np.asarray([], dtype=dt_b)
+        x = cho_solve_banded(cb_and_lower, b)
+        assert x.shape == (0,)
+
+        dtype_nonempty = cho_solve_banded((m, True), np.ones(2, dtype=dt_b)).dtype
+        assert x.dtype == dtype_nonempty
+
+        b = empty((0, 0), dtype=dt_b)
+        x = cho_solve_banded(cb_and_lower, b)
+        assert x.shape == (0, 0)
+        assert x.dtype == dtype_nonempty
+
+
+class TestOverwrite:
+    def test_cholesky(self):
+        assert_no_overwrite(cholesky, [(3, 3)])
+
+    def test_cho_factor(self):
+        assert_no_overwrite(cho_factor, [(3, 3)])
+
+    def test_cho_solve(self):
+        x = array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
+        xcho = cho_factor(x)
+        assert_no_overwrite(lambda b: cho_solve(xcho, b), [(3,)])
+
+    def test_cholesky_banded(self):
+        assert_no_overwrite(cholesky_banded, [(2, 3)])
+
+    def test_cho_solve_banded(self):
+        x = array([[0, -1, -1], [2, 2, 2]])
+        xcho = cholesky_banded(x)
+        assert_no_overwrite(lambda b: cho_solve_banded((xcho, False), b),
+                            [(3,)])
+
+class TestChoFactor:
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        x, lower = cho_factor(a)
+
+        assert x.shape == (0, 0)
+
+        xx, lower = cho_factor(np.eye(2, dtype=dt))
+        assert x.dtype == xx.dtype
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..df112f0e4cf75d03d2787c24306665b7027967ee
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py
@@ -0,0 +1,300 @@
+import pytest
+import numpy as np
+from numpy.random import default_rng
+from numpy.testing import assert_allclose
+
+from scipy import linalg
+from scipy.linalg.lapack import _compute_lwork
+from scipy.stats import ortho_group, unitary_group
+from scipy.linalg import cossin, get_lapack_funcs
+
+REAL_DTYPES = (np.float32, np.float64)
+COMPLEX_DTYPES = (np.complex64, np.complex128)
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+@pytest.mark.parametrize('dtype_', DTYPES)
+@pytest.mark.parametrize('m, p, q',
+                         [
+                             (2, 1, 1),
+                             (3, 2, 1),
+                             (3, 1, 2),
+                             (4, 2, 2),
+                             (4, 1, 2),
+                             (40, 12, 20),
+                             (40, 30, 1),
+                             (40, 1, 30),
+                             (100, 50, 1),
+                             (100, 50, 50),
+                         ])
+@pytest.mark.parametrize('swap_sign', [True, False])
+def test_cossin(dtype_, m, p, q, swap_sign):
+    rng = default_rng(1708093570726217)
+    if dtype_ in COMPLEX_DTYPES:
+        x = np.array(unitary_group.rvs(m, random_state=rng), dtype=dtype_)
+    else:
+        x = np.array(ortho_group.rvs(m, random_state=rng), dtype=dtype_)
+
+    u, cs, vh = cossin(x, p, q,
+                       swap_sign=swap_sign)
+    assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
+    assert u.dtype == dtype_
+    # Test for float32 or float 64
+    assert cs.dtype == np.real(u).dtype
+    assert vh.dtype == dtype_
+
+    u, cs, vh = cossin([x[:p, :q], x[:p, q:], x[p:, :q], x[p:, q:]],
+                       swap_sign=swap_sign)
+    assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
+    assert u.dtype == dtype_
+    assert cs.dtype == np.real(u).dtype
+    assert vh.dtype == dtype_
+
+    _, cs2, vh2 = cossin(x, p, q,
+                         compute_u=False,
+                         swap_sign=swap_sign)
+    assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+    assert_allclose(vh, vh2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+    u2, cs2, _ = cossin(x, p, q,
+                        compute_vh=False,
+                        swap_sign=swap_sign)
+    assert_allclose(u, u2, rtol=0., atol=10*np.finfo(dtype_).eps)
+    assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+    _, cs2, _ = cossin(x, p, q,
+                       compute_u=False,
+                       compute_vh=False,
+                       swap_sign=swap_sign)
+    assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+
+def test_cossin_mixed_types():
+    rng = default_rng(1708093736390459)
+    x = np.array(ortho_group.rvs(4, random_state=rng), dtype=np.float64)
+    u, cs, vh = cossin([x[:2, :2],
+                        np.array(x[:2, 2:], dtype=np.complex128),
+                        x[2:, :2],
+                        x[2:, 2:]])
+
+    assert u.dtype == np.complex128
+    assert cs.dtype == np.float64
+    assert vh.dtype == np.complex128
+    assert_allclose(x, u @ cs @ vh, rtol=0.,
+                    atol=1e4 * np.finfo(np.complex128).eps)
+
+
+def test_cossin_error_incorrect_subblocks():
+    with pytest.raises(ValueError, match="be due to missing p, q arguments."):
+        cossin(([1, 2], [3, 4, 5], [6, 7], [8, 9, 10]))
+
+
+def test_cossin_error_empty_subblocks():
+    with pytest.raises(ValueError, match="x11.*empty"):
+        cossin(([], [], [], []))
+    with pytest.raises(ValueError, match="x12.*empty"):
+        cossin(([1, 2], [], [6, 7], [8, 9, 10]))
+    with pytest.raises(ValueError, match="x21.*empty"):
+        cossin(([1, 2], [3, 4, 5], [], [8, 9, 10]))
+    with pytest.raises(ValueError, match="x22.*empty"):
+        cossin(([1, 2], [3, 4, 5], [2], []))
+
+
+def test_cossin_error_missing_partitioning():
+    with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"):
+        cossin(unitary_group.rvs(2))
+
+    with pytest.raises(ValueError, match=".*might be due to missing p, q"):
+        cossin(unitary_group.rvs(4))
+
+
+def test_cossin_error_non_iterable():
+    with pytest.raises(ValueError, match="containing the subblocks of X"):
+        cossin(12j)
+
+
+def test_cossin_error_non_square():
+    with pytest.raises(ValueError, match="only supports square"):
+        cossin(np.array([[1, 2]]), 1, 1)
+
+
+def test_cossin_error_partitioning():
+    x = np.array(ortho_group.rvs(4), dtype=np.float64)
+    with pytest.raises(ValueError, match="invalid p=0.*0= m) or (q >= m):
+        pytest.skip("`0 < p < m` and `0 < q < m` must hold")
+
+    # Generate unitary input
+    rng = np.random.default_rng(329548272348596421)
+    X = unitary_group.rvs(m, random_state=rng)
+    np.testing.assert_allclose(X @ X.conj().T, np.eye(m), atol=1e-15)
+
+    # Perform the decomposition
+    u0, cs0, vh0 = linalg.cossin(X, p=p, q=q, separate=True, swap_sign=swap_sign)
+    u1, u2 = u0
+    v1, v2 = vh0
+    v1, v2 = v1.conj().T, v2.conj().T
+
+    # "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"
+    np.testing.assert_allclose(u1 @ u1.conj().T, np.eye(p), atol=1e-13)
+    np.testing.assert_allclose(u2 @ u2.conj().T, np.eye(m-p), atol=1e-13)
+    np.testing.assert_allclose(v1 @ v1.conj().T, np.eye(q), atol=1e-13)
+    np.testing.assert_allclose(v2 @ v2.conj().T, np.eye(m-q), atol=1e-13)
+
+    # "and C and S are (r, r) nonnegative diagonal matrices..."
+    C = np.diag(np.cos(cs0))
+    S = np.diag(np.sin(cs0))
+    # "...satisfying C^2 + S^2 = I where r = min(p, m-p, q, m-q)."
+    r = min(p, m-p, q, m-q)
+    np.testing.assert_allclose(C**2 + S**2, np.eye(r))
+
+    # "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."
+    I11 = np.eye(min(p, q) - r)
+    I12 = np.eye(min(p, m - q) - r)
+    I21 = np.eye(min(m - p, q) - r)
+    I22 = np.eye(min(m - p, m - q) - r)
+
+    # From:
+    #                            ┌                   ┐
+    #                            │ 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 │
+    #                            └                   ┘
+
+    # We can see that U and V are block diagonal matrices like so:
+    U = linalg.block_diag(u1, u2)
+    V = linalg.block_diag(v1, v2)
+
+    # And the center matrix, which we'll call Q here, must be:
+    Q11 = np.zeros((u1.shape[1], v1.shape[0]))
+    IC11 = linalg.block_diag(I11, C)
+    Q11[:IC11.shape[0], :IC11.shape[1]] = IC11
+
+    Q12 = np.zeros((u1.shape[1], v2.shape[0]))
+    SI12 = linalg.block_diag(S, I12) if swap_sign else linalg.block_diag(-S, -I12)
+    Q12[-SI12.shape[0]:, -SI12.shape[1]:] = SI12
+
+    Q21 = np.zeros((u2.shape[1], v1.shape[0]))
+    SI21 = linalg.block_diag(-S, -I21) if swap_sign else linalg.block_diag(S, I21)
+    Q21[-SI21.shape[0]:, -SI21.shape[1]:] = SI21
+
+    Q22 = np.zeros((u2.shape[1], v2.shape[0]))
+    IC22 = linalg.block_diag(I22, C)
+    Q22[:IC22.shape[0], :IC22.shape[1]] = IC22
+
+    Q = np.block([[Q11, Q12], [Q21, Q22]])
+
+    # Confirm that `cossin` decomposes `X` as shown
+    np.testing.assert_allclose(X, U @ Q @ V.conj().T)
+
+    # And check that `separate=False` agrees
+    U0, CS0, Vh0 = linalg.cossin(X, p=p, q=q, swap_sign=swap_sign)
+    np.testing.assert_allclose(U, U0)
+    np.testing.assert_allclose(Q, CS0)
+    np.testing.assert_allclose(V, Vh0.conj().T)
+
+    # Confirm that `compute_u`/`compute_vh` don't affect the results
+    kwargs = dict(p=p, q=q, swap_sign=swap_sign)
+
+    # `compute_u=False`
+    u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, **kwargs)
+    assert u[0].shape == (0, 0)  # probably not ideal, but this is what it does
+    assert u[1].shape == (0, 0)
+    assert_allclose(cs, cs0, rtol=1e-15)
+    assert_allclose(vh[0], vh0[0], rtol=1e-15)
+    assert_allclose(vh[1], vh0[1], rtol=1e-15)
+
+    U, CS, Vh = linalg.cossin(X, compute_u=False, **kwargs)
+    assert U.shape == (0, 0)
+    assert_allclose(CS, CS0, rtol=1e-15)
+    assert_allclose(Vh, Vh0, rtol=1e-15)
+
+    # `compute_vh=False`
+    u, cs, vh = linalg.cossin(X, separate=True, compute_vh=False, **kwargs)
+    assert_allclose(u[0], u[0], rtol=1e-15)
+    assert_allclose(u[1], u[1], rtol=1e-15)
+    assert_allclose(cs, cs0, rtol=1e-15)
+    assert vh[0].shape == (0, 0)
+    assert vh[1].shape == (0, 0)
+
+    U, CS, Vh = linalg.cossin(X, compute_vh=False, **kwargs)
+    assert_allclose(U, U0, rtol=1e-15)
+    assert_allclose(CS, CS0, rtol=1e-15)
+    assert Vh.shape == (0, 0)
+
+    # `compute_u=False, compute_vh=False`
+    u, cs, vh = linalg.cossin(X, separate=True, compute_u=False,
+                              compute_vh=False, **kwargs)
+    assert u[0].shape == (0, 0)
+    assert u[1].shape == (0, 0)
+    assert_allclose(cs, cs0, rtol=1e-15)
+    assert vh[0].shape == (0, 0)
+    assert vh[1].shape == (0, 0)
+
+    U, CS, Vh = linalg.cossin(X, compute_u=False, compute_vh=False, **kwargs)
+    assert U.shape == (0, 0)
+    assert_allclose(CS, CS0, rtol=1e-15)
+    assert Vh.shape == (0, 0)
+
+
+def test_indexing_bug_gh19365():
+    # Regression test for gh-19365, which reported a bug with `separate=False`
+    rng = np.random.default_rng(32954827234421)
+    m = rng.integers(50, high=100)
+    p = rng.integers(10, 40)  # always p < m
+    q = rng.integers(m - p + 1, m - 1)  # always m-p < q < m
+    X = unitary_group.rvs(m, random_state=rng)  # random unitary matrix
+    U, D, Vt = linalg.cossin(X, p=p, q=q, separate=False)
+    assert np.allclose(U @ D @ Vt, X)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d74a746b4dd7bb6367500b4c893aa9f767de51f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py
@@ -0,0 +1,137 @@
+from numpy.testing import assert_array_almost_equal, assert_allclose, assert_
+from numpy import (array, eye, zeros, empty_like, empty, tril_indices_from,
+                   tril, triu_indices_from, spacing, float32, float64,
+                   complex64, complex128)
+from numpy.random import rand, randint, seed
+from scipy.linalg import ldl
+from scipy._lib._util import ComplexWarning
+import pytest
+from pytest import raises as assert_raises, warns
+
+
+@pytest.mark.thread_unsafe
+def test_args():
+    A = eye(3)
+    # Nonsquare array
+    assert_raises(ValueError, ldl, A[:, :2])
+    # Complex matrix with imaginary diagonal entries with "hermitian=True"
+    with warns(ComplexWarning):
+        ldl(A*1j)
+
+
+def test_empty_array():
+    a = empty((0, 0), dtype=complex)
+    l, d, p = ldl(empty((0, 0)))
+    assert_array_almost_equal(l, empty_like(a))
+    assert_array_almost_equal(d, empty_like(a))
+    assert_array_almost_equal(p, array([], dtype=int))
+
+
+def test_simple():
+    a = array([[-0.39-0.71j, 5.14-0.64j, -7.86-2.96j, 3.80+0.92j],
+               [5.14-0.64j, 8.86+1.81j, -3.52+0.58j, 5.32-1.59j],
+               [-7.86-2.96j, -3.52+0.58j, -2.83-0.03j, -1.54-2.86j],
+               [3.80+0.92j, 5.32-1.59j, -1.54-2.86j, -0.56+0.12j]])
+    b = array([[5., 10, 1, 18],
+               [10., 2, 11, 1],
+               [1., 11, 19, 9],
+               [18., 1, 9, 0]])
+    c = array([[52., 97, 112, 107, 50],
+               [97., 114, 89, 98, 13],
+               [112., 89, 64, 33, 6],
+               [107., 98, 33, 60, 73],
+               [50., 13, 6, 73, 77]])
+
+    d = array([[2., 2, -4, 0, 4],
+               [2., -2, -2, 10, -8],
+               [-4., -2, 6, -8, -4],
+               [0., 10, -8, 6, -6],
+               [4., -8, -4, -6, 10]])
+    e = array([[-1.36+0.00j, 0+0j, 0+0j, 0+0j],
+               [1.58-0.90j, -8.87+0j, 0+0j, 0+0j],
+               [2.21+0.21j, -1.84+0.03j, -4.63+0j, 0+0j],
+               [3.91-1.50j, -1.78-1.18j, 0.11-0.11j, -1.84+0.00j]])
+    for x in (b, c, d):
+        l, d, p = ldl(x)
+        assert_allclose(l.dot(d).dot(l.T), x, atol=spacing(1000.), rtol=0)
+
+        u, d, p = ldl(x, lower=False)
+        assert_allclose(u.dot(d).dot(u.T), x, atol=spacing(1000.), rtol=0)
+
+    l, d, p = ldl(a, hermitian=False)
+    assert_allclose(l.dot(d).dot(l.T), a, atol=spacing(1000.), rtol=0)
+
+    u, d, p = ldl(a, lower=False, hermitian=False)
+    assert_allclose(u.dot(d).dot(u.T), a, atol=spacing(1000.), rtol=0)
+
+    # Use upper part for the computation and use the lower part for comparison
+    l, d, p = ldl(e.conj().T, lower=0)
+    assert_allclose(tril(l.dot(d).dot(l.conj().T)-e), zeros((4, 4)),
+                    atol=spacing(1000.), rtol=0)
+
+
+def test_permutations():
+    seed(1234)
+    for _ in range(10):
+        n = randint(1, 100)
+        # Random real/complex array
+        x = rand(n, n) if randint(2) else rand(n, n) + rand(n, n)*1j
+        x = x + x.conj().T
+        x += eye(n)*randint(5, 1e6)
+        l_ind = tril_indices_from(x, k=-1)
+        u_ind = triu_indices_from(x, k=1)
+
+        # Test whether permutations lead to a triangular array
+        u, d, p = ldl(x, lower=0)
+        # lower part should be zero
+        assert_(not any(u[p, :][l_ind]), f'Spin {_} failed')
+
+        l, d, p = ldl(x, lower=1)
+        # upper part should be zero
+        assert_(not any(l[p, :][u_ind]), f'Spin {_} failed')
+
+
+@pytest.mark.parametrize("dtype", [float32, float64])
+@pytest.mark.parametrize("n", [30, 150])
+def test_ldl_type_size_combinations_real(n, dtype):
+    seed(1234)
+    msg = (f"Failed for size: {n}, dtype: {dtype}")
+
+    x = rand(n, n).astype(dtype)
+    x = x + x.T
+    x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
+
+    l, d1, p = ldl(x)
+    u, d2, p = ldl(x, lower=0)
+    rtol = 1e-4 if dtype is float32 else 1e-10
+    assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg)
+    assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg)
+
+
+@pytest.mark.parametrize("dtype", [complex64, complex128])
+@pytest.mark.parametrize("n", [30, 150])
+def test_ldl_type_size_combinations_complex(n, dtype):
+    seed(1234)
+    msg1 = (f"Her failed for size: {n}, dtype: {dtype}")
+    msg2 = (f"Sym failed for size: {n}, dtype: {dtype}")
+
+    # Complex hermitian upper/lower
+    x = (rand(n, n)+1j*rand(n, n)).astype(dtype)
+    x = x+x.conj().T
+    x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
+
+    l, d1, p = ldl(x)
+    u, d2, p = ldl(x, lower=0)
+    rtol = 2e-4 if dtype is complex64 else 1e-10
+    assert_allclose(l.dot(d1).dot(l.conj().T), x, rtol=rtol, err_msg=msg1)
+    assert_allclose(u.dot(d2).dot(u.conj().T), x, rtol=rtol, err_msg=msg1)
+
+    # Complex symmetric upper/lower
+    x = (rand(n, n)+1j*rand(n, n)).astype(dtype)
+    x = x+x.T
+    x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
+
+    l, d1, p = ldl(x, hermitian=0)
+    u, d2, p = ldl(x, lower=0, hermitian=0)
+    assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg2)
+    assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg2)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..da0beccf1f0e66baf4ac4ec80d7ff7129b2df345
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py
@@ -0,0 +1,308 @@
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from scipy.linalg import lu, lu_factor, lu_solve, get_lapack_funcs, solve
+from numpy.testing import assert_allclose, assert_array_equal, assert_equal
+
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+class TestLU:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1682281250228846)
+
+    def test_old_lu_smoke_tests(self):
+        "Tests from old fortran based lu test suite"
+        a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+        p, l, u = lu(a)
+        result_lu = np.array([[2., 5., 6.], [0.5, -0.5, 0.], [0.5, 1., 0.]])
+        assert_allclose(p, np.rot90(np.eye(3)))
+        assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3))
+        assert_allclose(u, np.triu(result_lu))
+
+        a = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
+        p, l, u = lu(a)
+        result_lu = np.array([[2., 5.j, 6.], [0.5, 2-2.5j, 0.], [0.5, 1., 0.]])
+        assert_allclose(p, np.rot90(np.eye(3)))
+        assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3))
+        assert_allclose(u, np.triu(result_lu))
+
+        b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+        p, l, u = lu(b)
+        assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+        assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]]))
+        assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]]),
+                        rtol=0., atol=1e-14)
+
+        cb = np.array([[1.j, 2.j, 3.j], [4j, 5j, 6j], [7j, 8j, 9j]])
+        p, l, u = lu(cb)
+        assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+        assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]]))
+        assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]])*1j,
+                        rtol=0., atol=1e-14)
+
+        # Rectangular matrices
+        hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])
+        p, l, u = lu(hrect)
+        assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+        assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]]))
+        assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9,  15/9,  24/9],
+                                     [0, 0, -0.5, 0]]), rtol=0., atol=1e-14)
+
+        chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])*1.j
+        p, l, u = lu(chrect)
+        assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+        assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]]))
+        assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9,  15/9,  24/9],
+                                     [0, 0, -0.5, 0]])*1j, rtol=0., atol=1e-14)
+
+        vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
+        p, l, u = lu(vrect)
+        assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :])
+        assert_allclose(l, np.array([[1., 0, 0], [0.1, 1, 0], [0.7, -0.5, 1],
+                                     [0.4, 0.25, 0.5]]))
+        assert_allclose(u, np.array([[10, 12, 12],
+                                     [0, 0.8, 1.8],
+                                     [0, 0,  1.5]]))
+
+        cvrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])*1j
+        p, l, u = lu(cvrect)
+        assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :])
+        assert_allclose(l, np.array([[1., 0, 0],
+                                     [0.1, 1, 0],
+                                     [0.7, -0.5, 1],
+                                     [0.4, 0.25, 0.5]]))
+        assert_allclose(u, np.array([[10, 12, 12],
+                                     [0, 0.8, 1.8],
+                                     [0, 0,  1.5]])*1j)
+
+    @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20],
+                                       [20, 4], [4, 20], [3, 2, 9, 9],
+                                       [2, 2, 17, 5], [2, 2, 11, 7]])
+    def test_simple_lu_shapes_real_complex(self, shape):
+        a = self.rng.uniform(-10., 10., size=shape)
+        p, l, u = lu(a)
+        assert_allclose(a, p @ l @ u)
+        pl, u = lu(a, permute_l=True)
+        assert_allclose(a, pl @ u)
+
+        b = self.rng.uniform(-10., 10., size=shape)*1j
+        b += self.rng.uniform(-10, 10, size=shape)
+        pl, u = lu(b, permute_l=True)
+        assert_allclose(b, pl @ u)
+
+    @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20],
+                                       [20, 4], [4, 20]])
+    def test_simple_lu_shapes_real_complex_2d_indices(self, shape):
+        a = self.rng.uniform(-10., 10., size=shape)
+        p, l, u = lu(a, p_indices=True)
+        assert_allclose(a, l[p, :] @ u)
+
+    def test_1by1_input_output(self):
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
+        p, l, u = lu(a, p_indices=True)
+        assert_allclose(p, np.zeros(shape=(4, 5, 1), dtype=int))
+        assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+        assert_allclose(u, a)
+
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
+        p, l, u = lu(a)
+        assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+        assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+        assert_allclose(u, a)
+
+        pl, u = lu(a, permute_l=True)
+        assert_allclose(pl, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+        assert_allclose(u, a)
+
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j)
+        p, l, u = lu(a)
+        assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64))
+        assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64))
+        assert_allclose(u, a)
+
+    def test_empty_edge_cases(self):
+        a = np.empty([0, 0])
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float64))
+        assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float64))
+        assert_allclose(u, np.empty(shape=(0, 0), dtype=np.float64))
+
+        a = np.empty([0, 3], dtype=np.float16)
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32))
+        assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float32))
+        assert_allclose(u, np.empty(shape=(0, 3), dtype=np.float32))
+
+        a = np.empty([3, 0], dtype=np.complex64)
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32))
+        assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64))
+        assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+        p, l, u = lu(a, p_indices=True)
+        assert_allclose(p, np.empty(shape=(0,), dtype=int))
+        assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64))
+        assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+        pl, u = lu(a, permute_l=True)
+        assert_allclose(pl, np.empty(shape=(3, 0), dtype=np.complex64))
+        assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+
+        a = np.empty([3, 0, 0], dtype=np.complex64)
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(3, 0, 0), dtype=np.float32))
+        assert_allclose(l, np.empty(shape=(3, 0, 0), dtype=np.complex64))
+        assert_allclose(u, np.empty(shape=(3, 0, 0), dtype=np.complex64))
+
+        a = np.empty([0, 0, 3])
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0, 0)))
+        assert_allclose(l, np.empty(shape=(0, 0, 0)))
+        assert_allclose(u, np.empty(shape=(0, 0, 3)))
+
+        with assert_raises(ValueError, match='at least two-dimensional'):
+            lu(np.array([]))
+
+        a = np.array([[]])
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0)))
+        assert_allclose(l, np.empty(shape=(1, 0)))
+        assert_allclose(u, np.empty(shape=(0, 0)))
+
+        a = np.array([[[]]])
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(1, 0, 0)))
+        assert_allclose(l, np.empty(shape=(1, 1, 0)))
+        assert_allclose(u, np.empty(shape=(1, 0, 0)))
+
+
+class TestLUFactor:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1682281250228846)
+
+        self.a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+        self.ca = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
+        # Those matrices are more robust to detect problems in permutation
+        # matrices than the ones above
+        self.b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+        self.cb = np.array([[1j, 2j, 3j], [4j, 5j, 6j], [7j, 8j, 9j]])
+
+        # Rectangular matrices
+        self.hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])
+        self.chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8],
+                                [9, 10, 12, 12]]) * 1.j
+
+        self.vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
+        self.cvrect = 1.j * np.array([[1, 2, 3],
+                                      [4, 5, 6],
+                                      [7, 8, 9],
+                                      [10, 12, 12]])
+
+        # Medium sizes matrices
+        self.med = self.rng.random((30, 40))
+        self.cmed = self.rng.random((30, 40)) + 1.j*self.rng.random((30, 40))
+
+    def _test_common_lu_factor(self, data):
+        l_and_u1, piv1 = lu_factor(data)
+        (getrf,) = get_lapack_funcs(("getrf",), (data,))
+        l_and_u2, piv2, _ = getrf(data, overwrite_a=False)
+        assert_allclose(l_and_u1, l_and_u2)
+        assert_allclose(piv1, piv2)
+
+    # Simple tests.
+    # For lu_factor gives a LinAlgWarning because these matrices are singular
+    def test_hrectangular(self):
+        self._test_common_lu_factor(self.hrect)
+
+    def test_vrectangular(self):
+        self._test_common_lu_factor(self.vrect)
+
+    def test_hrectangular_complex(self):
+        self._test_common_lu_factor(self.chrect)
+
+    def test_vrectangular_complex(self):
+        self._test_common_lu_factor(self.cvrect)
+
+    # Bigger matrices
+    def test_medium1(self):
+        """Check lu decomposition on medium size, rectangular matrix."""
+        self._test_common_lu_factor(self.med)
+
+    def test_medium1_complex(self):
+        """Check lu decomposition on medium size, rectangular matrix."""
+        self._test_common_lu_factor(self.cmed)
+
+    def test_check_finite(self):
+        p, l, u = lu(self.a, check_finite=False)
+        assert_allclose(p @ l @ u, self.a)
+
+    def test_simple_known(self):
+        # Ticket #1458
+        for order in ['C', 'F']:
+            A = np.array([[2, 1], [0, 1.]], order=order)
+            LU, P = lu_factor(A)
+            assert_allclose(LU, np.array([[2, 1], [0, 1]]))
+            assert_array_equal(P, np.array([0, 1]))
+
+    @pytest.mark.parametrize("m", [0, 1, 2])
+    @pytest.mark.parametrize("n", [0, 1, 2])
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_shape_dtype(self, m, n,  dtype):
+        k = min(m, n)
+
+        a = np.eye(m, n, dtype=dtype)
+        lu, p = lu_factor(a)
+        assert_equal(lu.shape, (m, n))
+        assert_equal(lu.dtype, dtype)
+        assert_equal(p.shape, (k,))
+        assert_equal(p.dtype, np.int32)
+
+    @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+    def test_empty(self, m, n):
+        a = np.zeros((m, n))
+        lu, p = lu_factor(a)
+        assert_allclose(lu, np.empty((m, n)))
+        assert_allclose(p, np.arange(0))
+
+
+class TestLUSolve:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1682281250228846)
+
+    def test_lu(self):
+        a0 = self.rng.random((10, 10))
+        b = self.rng.random((10,))
+
+        for order in ['C', 'F']:
+            a = np.array(a0, order=order)
+            x1 = solve(a, b)
+            lu_a = lu_factor(a)
+            x2 = lu_solve(lu_a, b)
+            assert_allclose(x1, x2)
+
+    def test_check_finite(self):
+        a = self.rng.random((10, 10))
+        b = self.rng.random((10,))
+        x1 = solve(a, b)
+        lu_a = lu_factor(a, check_finite=False)
+        x2 = lu_solve(lu_a, b, check_finite=False)
+        assert_allclose(x1, x2)
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt, dt_b):
+        lu_and_piv = (np.empty((0, 0), dtype=dt), np.array([]))
+        b = np.asarray([], dtype=dt_b)
+        x = lu_solve(lu_and_piv, b)
+        assert x.shape == (0,)
+
+        m = lu_solve((np.eye(2, dtype=dt), [0, 1]), np.ones(2, dtype=dt_b))
+        assert x.dtype == m.dtype
+
+        b = np.empty((0, 0), dtype=dt_b)
+        x = lu_solve(lu_and_piv, b)
+        assert x.shape == (0, 0)
+        assert x.dtype == m.dtype
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..607238842b3cc643d9665e40f29e41b15d8951a1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py
@@ -0,0 +1,110 @@
+import pytest
+import numpy as np
+from numpy.linalg import norm
+from numpy.testing import (assert_, assert_allclose, assert_equal)
+from scipy.linalg import polar, eigh
+
+
+diag2 = np.array([[2, 0], [0, 3]])
+a13 = np.array([[1, 2, 2]])
+
+precomputed_cases = [
+    [[[0]], 'right', [[1]], [[0]]],
+    [[[0]], 'left', [[1]], [[0]]],
+    [[[9]], 'right', [[1]], [[9]]],
+    [[[9]], 'left', [[1]], [[9]]],
+    [diag2, 'right', np.eye(2), diag2],
+    [diag2, 'left', np.eye(2), diag2],
+    [a13, 'right', a13/norm(a13[0]), a13.T.dot(a13)/norm(a13[0])],
+]
+
+verify_cases = [
+    [[1, 2], [3, 4]],
+    [[1, 2, 3]],
+    [[1], [2], [3]],
+    [[1, 2, 3], [3, 4, 0]],
+    [[1, 2], [3, 4], [5, 5]],
+    [[1, 2], [3, 4+5j]],
+    [[1, 2, 3j]],
+    [[1], [2], [3j]],
+    [[1, 2, 3+2j], [3, 4-1j, -4j]],
+    [[1, 2], [3-2j, 4+0.5j], [5, 5]],
+    [[10000, 10, 1], [-1, 2, 3j], [0, 1, 2]],
+    np.empty((0, 0)),
+    np.empty((0, 2)),
+    np.empty((2, 0)),
+]
+
+
+def check_precomputed_polar(a, side, expected_u, expected_p):
+    # Compare the result of the polar decomposition to a
+    # precomputed result.
+    u, p = polar(a, side=side)
+    assert_allclose(u, expected_u, atol=1e-15)
+    assert_allclose(p, expected_p, atol=1e-15)
+
+
+def verify_polar(a):
+    # Compute the polar decomposition, and then verify that
+    # the result has all the expected properties.
+    product_atol = np.sqrt(np.finfo(float).eps)
+
+    aa = np.asarray(a)
+    m, n = aa.shape
+
+    u, p = polar(a, side='right')
+    assert_equal(u.shape, (m, n))
+    assert_equal(p.shape, (n, n))
+    # a = up
+    assert_allclose(u.dot(p), a, atol=product_atol)
+    if m >= n:
+        assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
+    else:
+        assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
+    # p is Hermitian positive semidefinite.
+    assert_allclose(p.conj().T, p)
+    evals = eigh(p, eigvals_only=True)
+    nonzero_evals = evals[abs(evals) > 1e-14]
+    assert_((nonzero_evals >= 0).all())
+
+    u, p = polar(a, side='left')
+    assert_equal(u.shape, (m, n))
+    assert_equal(p.shape, (m, m))
+    # a = pu
+    assert_allclose(p.dot(u), a, atol=product_atol)
+    if m >= n:
+        assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
+    else:
+        assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
+    # p is Hermitian positive semidefinite.
+    assert_allclose(p.conj().T, p)
+    evals = eigh(p, eigvals_only=True)
+    nonzero_evals = evals[abs(evals) > 1e-14]
+    assert_((nonzero_evals >= 0).all())
+
+
+def test_precomputed_cases():
+    for a, side, expected_u, expected_p in precomputed_cases:
+        check_precomputed_polar(a, side, expected_u, expected_p)
+
+
+def test_verify_cases():
+    for a in verify_cases:
+        verify_polar(a)
+
+@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+@pytest.mark.parametrize('shape',  [(0, 0), (0, 2), (2, 0)])
+@pytest.mark.parametrize('side', ['left', 'right'])
+def test_empty(dt, shape, side):
+    a = np.empty(shape, dtype=dt)
+    m, n = shape
+    p_shape = (m, m) if side == 'left' else (n, n)
+
+    u, p = polar(a, side=side)
+    u_n, p_n = polar(np.eye(5, dtype=dt))
+
+    assert_equal(u.dtype, u_n.dtype)
+    assert_equal(p.dtype, p_n.dtype)
+    assert u.shape == shape
+    assert p.shape == p_shape
+    assert np.all(p == 0)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py
new file mode 100644
index 0000000000000000000000000000000000000000..7553e21d61ceaa774d24c48d9d4bc2e3a8e3cc00
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py
@@ -0,0 +1,1701 @@
+import itertools
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal
+from pytest import raises as assert_raises
+from scipy import linalg
+import scipy.linalg._decomp_update as _decomp_update
+from scipy.linalg._decomp_update import qr_delete, qr_update, qr_insert
+
+def assert_unitary(a, rtol=None, atol=None, assert_sqr=True):
+    if rtol is None:
+        rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
+    if atol is None:
+        atol = 10*np.finfo(a.dtype).eps
+
+    if assert_sqr:
+        assert_(a.shape[0] == a.shape[1], 'unitary matrices must be square')
+    aTa = np.dot(a.T.conj(), a)
+    assert_allclose(aTa, np.eye(a.shape[1]), rtol=rtol, atol=atol)
+
+def assert_upper_tri(a, rtol=None, atol=None):
+    if rtol is None:
+        rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
+    if atol is None:
+        atol = 2*np.finfo(a.dtype).eps
+    mask = np.tri(a.shape[0], a.shape[1], -1, np.bool_)
+    assert_allclose(a[mask], 0.0, rtol=rtol, atol=atol)
+
+def check_qr(q, r, a, rtol, atol, assert_sqr=True):
+    assert_unitary(q, rtol, atol, assert_sqr)
+    assert_upper_tri(r, rtol, atol)
+    assert_allclose(q.dot(r), a, rtol=rtol, atol=atol)
+
+def make_strided(arrs):
+    strides = [(3, 7), (2, 2), (3, 4), (4, 2), (5, 4), (2, 3), (2, 1), (4, 5)]
+    kmax = len(strides)
+    k = 0
+    ret = []
+    for a in arrs:
+        if a.ndim == 1:
+            s = strides[k % kmax]
+            k += 1
+            base = np.zeros(s[0]*a.shape[0]+s[1], a.dtype)
+            view = base[s[1]::s[0]]
+            view[...] = a
+        elif a.ndim == 2:
+            s = strides[k % kmax]
+            t = strides[(k+1) % kmax]
+            k += 2
+            base = np.zeros((s[0]*a.shape[0]+s[1], t[0]*a.shape[1]+t[1]),
+                            a.dtype)
+            view = base[s[1]::s[0], t[1]::t[0]]
+            view[...] = a
+        else:
+            raise ValueError('make_strided only works for ndim = 1 or'
+                             ' 2 arrays')
+        ret.append(view)
+    return ret
+
+def negate_strides(arrs):
+    ret = []
+    for a in arrs:
+        b = np.zeros_like(a)
+        if b.ndim == 2:
+            b = b[::-1, ::-1]
+        elif b.ndim == 1:
+            b = b[::-1]
+        else:
+            raise ValueError('negate_strides only works for ndim = 1 or'
+                             ' 2 arrays')
+        b[...] = a
+        ret.append(b)
+    return ret
+
+def nonitemsize_strides(arrs):
+    out = []
+    for a in arrs:
+        a_dtype = a.dtype
+        b = np.zeros(a.shape, [('a', a_dtype), ('junk', 'S1')])
+        c = b.getfield(a_dtype)
+        c[...] = a
+        out.append(c)
+    return out
+
+
+def make_nonnative(arrs):
+    return [a.astype(a.dtype.newbyteorder()) for a in arrs]
+
+
+class BaseQRdeltas:
+    def setup_method(self):
+        self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2)
+        self.atol = 10 * np.finfo(self.dtype).eps
+
+    def generate(self, type, mode='full'):
+        np.random.seed(29382)
+        shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12),
+                 'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type]
+        a = np.random.random(shape)
+        if np.iscomplexobj(self.dtype.type(1)):
+            b = np.random.random(shape)
+            a = a + 1j * b
+        a = a.astype(self.dtype)
+        q, r = linalg.qr(a, mode=mode)
+        return a, q, r
+
+class BaseQRdelete(BaseQRdeltas):
+    def test_sqr_1_row(self):
+        a, q, r = self.generate('sqr')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_p_row(self):
+        a, q, r = self.generate('sqr')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_1_col(self):
+        a, q, r = self.generate('sqr')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_p_col(self):
+        a, q, r = self.generate('sqr')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_1_row(self):
+        a, q, r = self.generate('tall')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_p_row(self):
+        a, q, r = self.generate('tall')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_1_col(self):
+        a, q, r = self.generate('tall')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_p_col(self):
+        a, q, r = self.generate('tall')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_1_row(self):
+        a, q, r = self.generate('fat')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_p_row(self):
+        a, q, r = self.generate('fat')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_1_col(self):
+        a, q, r = self.generate('fat')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_p_col(self):
+        a, q, r = self.generate('fat')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_economic_1_row(self):
+        # this test always starts and ends with an economic decomp.
+        a, q, r = self.generate('tall', 'economic')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    # for economic row deletes
+    # eco - prow = eco
+    # eco - prow = sqr
+    # eco - prow = fat
+    def base_economic_p_row_xxx(self, ndel):
+        a, q, r = self.generate('tall', 'economic')
+        for row in range(a.shape[0]-ndel):
+            q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+            a1 = np.delete(a, slice(row, row+ndel), 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_p_row_economic(self):
+        # (12, 7) - (3, 7) = (9,7) --> stays economic
+        self.base_economic_p_row_xxx(3)
+
+    def test_economic_p_row_sqr(self):
+        # (12, 7) - (5, 7) = (7, 7) --> becomes square
+        self.base_economic_p_row_xxx(5)
+
+    def test_economic_p_row_fat(self):
+        # (12, 7) - (7,7) = (5, 7) --> becomes fat
+        self.base_economic_p_row_xxx(7)
+
+    def test_economic_1_col(self):
+        a, q, r = self.generate('tall', 'economic')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_p_col(self):
+        a, q, r = self.generate('tall', 'economic')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_1_row(self):
+        a, q, r = self.generate('Mx1')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_p_row(self):
+        a, q, r = self.generate('Mx1')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_1_col(self):
+        a, q, r = self.generate('1xN')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_p_col(self):
+        a, q, r = self.generate('1xN')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_economic_1_row(self):
+        a, q, r = self.generate('Mx1', 'economic')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_p_row(self):
+        a, q, r = self.generate('Mx1', 'economic')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_delete_last_1_row(self):
+        # full and eco are the same for 1xN
+        a, q, r = self.generate('1xN')
+        q1, r1 = qr_delete(q, r, 0, 1, 'row')
+        assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+    def test_delete_last_p_row(self):
+        a, q, r = self.generate('tall', 'full')
+        q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
+        assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+        a, q, r = self.generate('tall', 'economic')
+        q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
+        assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+    def test_delete_last_1_col(self):
+        a, q, r = self.generate('Mx1', 'economic')
+        q1, r1 = qr_delete(q, r, 0, 1, 'col')
+        assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
+
+        a, q, r = self.generate('Mx1', 'full')
+        q1, r1 = qr_delete(q, r, 0, 1, 'col')
+        assert_unitary(q1)
+        assert_(q1.dtype == q.dtype)
+        assert_(q1.shape == q.shape)
+        assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+    def test_delete_last_p_col(self):
+        a, q, r = self.generate('tall', 'full')
+        q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
+        assert_unitary(q1)
+        assert_(q1.dtype == q.dtype)
+        assert_(q1.shape == q.shape)
+        assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+        a, q, r = self.generate('tall', 'economic')
+        q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
+        assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
+
+    def test_delete_1x1_row_col(self):
+        a, q, r = self.generate('1x1')
+        q1, r1 = qr_delete(q, r, 0, 1, 'row')
+        assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+        a, q, r = self.generate('1x1')
+        q1, r1 = qr_delete(q, r, 0, 1, 'col')
+        assert_unitary(q1)
+        assert_(q1.dtype == q.dtype)
+        assert_(q1.shape == q.shape)
+        assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+    # all full qr, row deletes and single column deletes should be able to
+    # handle any non negative strides. (only row and column vector
+    # operations are used.) p column delete require fortran ordered
+    # Q and R and will make a copy as necessary.  Economic qr row deletes
+    # require a contiguous q.
+
+    def base_non_simple_strides(self, adjust_strides, ks, p, which,
+                                overwriteable):
+        if which == 'row':
+            qind = (slice(p,None), slice(p,None))
+            rind = (slice(p,None), slice(None))
+        else:
+            qind = (slice(None), slice(None))
+            rind = (slice(None), slice(None,-p))
+
+        for type, k in itertools.product(['sqr', 'tall', 'fat'], ks):
+            a, q0, r0, = self.generate(type)
+            qs, rs = adjust_strides((q0, r0))
+            if p == 1:
+                a1 = np.delete(a, k, 0 if which == 'row' else 1)
+            else:
+                s = slice(k,k+p)
+                if k < 0:
+                    s = slice(k, k + p +
+                              (a.shape[0] if which == 'row' else a.shape[1]))
+                a1 = np.delete(a, s, 0 if which == 'row' else 1)
+
+            # for each variable, q, r we try with it strided and
+            # overwrite=False. Then we try with overwrite=True, and make
+            # sure that q and r are still overwritten.
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            q1, r1 = qr_delete(qs, r, k, p, which, False)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+            q1o, r1o = qr_delete(qs, r, k, p, which, True)
+            check_qr(q1o, r1o, a1, self.rtol, self.atol)
+            if overwriteable:
+                assert_allclose(q1o, qs[qind], rtol=self.rtol, atol=self.atol)
+                assert_allclose(r1o, r[rind], rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            q2, r2 = qr_delete(q, rs, k, p, which, False)
+            check_qr(q2, r2, a1, self.rtol, self.atol)
+            q2o, r2o = qr_delete(q, rs, k, p, which, True)
+            check_qr(q2o, r2o, a1, self.rtol, self.atol)
+            if overwriteable:
+                assert_allclose(q2o, q[qind], rtol=self.rtol, atol=self.atol)
+                assert_allclose(r2o, rs[rind], rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            # since some of these were consumed above
+            qs, rs = adjust_strides((q, r))
+            q3, r3 = qr_delete(qs, rs, k, p, which, False)
+            check_qr(q3, r3, a1, self.rtol, self.atol)
+            q3o, r3o = qr_delete(qs, rs, k, p, which, True)
+            check_qr(q3o, r3o, a1, self.rtol, self.atol)
+            if overwriteable:
+                assert_allclose(q2o, qs[qind], rtol=self.rtol, atol=self.atol)
+                assert_allclose(r3o, rs[rind], rtol=self.rtol, atol=self.atol)
+
+    def test_non_unit_strides_1_row(self):
+        self.base_non_simple_strides(make_strided, [0], 1, 'row', True)
+
+    def test_non_unit_strides_p_row(self):
+        self.base_non_simple_strides(make_strided, [0], 3, 'row', True)
+
+    def test_non_unit_strides_1_col(self):
+        self.base_non_simple_strides(make_strided, [0], 1, 'col', True)
+
+    def test_non_unit_strides_p_col(self):
+        self.base_non_simple_strides(make_strided, [0], 3, 'col', False)
+
+    def test_neg_strides_1_row(self):
+        self.base_non_simple_strides(negate_strides, [0], 1, 'row', False)
+
+    def test_neg_strides_p_row(self):
+        self.base_non_simple_strides(negate_strides, [0], 3, 'row', False)
+
+    def test_neg_strides_1_col(self):
+        self.base_non_simple_strides(negate_strides, [0], 1, 'col', False)
+
+    def test_neg_strides_p_col(self):
+        self.base_non_simple_strides(negate_strides, [0], 3, 'col', False)
+
+    def test_non_itemize_strides_1_row(self):
+        self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'row', False)
+
+    def test_non_itemize_strides_p_row(self):
+        self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'row', False)
+
+    def test_non_itemize_strides_1_col(self):
+        self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'col', False)
+
+    def test_non_itemize_strides_p_col(self):
+        self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'col', False)
+
+    def test_non_native_byte_order_1_row(self):
+        self.base_non_simple_strides(make_nonnative, [0], 1, 'row', False)
+
+    def test_non_native_byte_order_p_row(self):
+        self.base_non_simple_strides(make_nonnative, [0], 3, 'row', False)
+
+    def test_non_native_byte_order_1_col(self):
+        self.base_non_simple_strides(make_nonnative, [0], 1, 'col', False)
+
+    def test_non_native_byte_order_p_col(self):
+        self.base_non_simple_strides(make_nonnative, [0], 3, 'col', False)
+
+    def test_neg_k(self):
+        a, q, r = self.generate('sqr')
+        for k, p, w in itertools.product([-3, -7], [1, 3], ['row', 'col']):
+            q1, r1 = qr_delete(q, r, k, p, w, overwrite_qr=False)
+            if w == 'row':
+                a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[0]), 0)
+            else:
+                a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[1]), 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def base_overwrite_qr(self, which, p, test_C, test_F, mode='full'):
+        assert_sqr = True if mode == 'full' else False
+        if which == 'row':
+            qind = (slice(p,None), slice(p,None))
+            rind = (slice(p,None), slice(None))
+        else:
+            qind = (slice(None), slice(None))
+            rind = (slice(None), slice(None,-p))
+        a, q0, r0 = self.generate('sqr', mode)
+        if p == 1:
+            a1 = np.delete(a, 3, 0 if which == 'row' else 1)
+        else:
+            a1 = np.delete(a, slice(3, 3+p), 0 if which == 'row' else 1)
+
+        # don't overwrite
+        q = q0.copy('F')
+        r = r0.copy('F')
+        q1, r1 = qr_delete(q, r, 3, p, which, False)
+        check_qr(q1, r1, a1, self.rtol, self.atol, assert_sqr)
+        check_qr(q, r, a, self.rtol, self.atol, assert_sqr)
+
+        if test_F:
+            q = q0.copy('F')
+            r = r0.copy('F')
+            q2, r2 = qr_delete(q, r, 3, p, which, True)
+            check_qr(q2, r2, a1, self.rtol, self.atol, assert_sqr)
+            # verify the overwriting
+            assert_allclose(q2, q[qind], rtol=self.rtol, atol=self.atol)
+            assert_allclose(r2, r[rind], rtol=self.rtol, atol=self.atol)
+
+        if test_C:
+            q = q0.copy('C')
+            r = r0.copy('C')
+            q3, r3 = qr_delete(q, r, 3, p, which, True)
+            check_qr(q3, r3, a1, self.rtol, self.atol, assert_sqr)
+            assert_allclose(q3, q[qind], rtol=self.rtol, atol=self.atol)
+            assert_allclose(r3, r[rind], rtol=self.rtol, atol=self.atol)
+
+    def test_overwrite_qr_1_row(self):
+        # any positively strided q and r.
+        self.base_overwrite_qr('row', 1, True, True)
+
+    def test_overwrite_economic_qr_1_row(self):
+        # Any contiguous q and positively strided r.
+        self.base_overwrite_qr('row', 1, True, True, 'economic')
+
+    def test_overwrite_qr_1_col(self):
+        # any positively strided q and r.
+        # full and eco share code paths
+        self.base_overwrite_qr('col', 1, True, True)
+
+    def test_overwrite_qr_p_row(self):
+        # any positively strided q and r.
+        self.base_overwrite_qr('row', 3, True, True)
+
+    def test_overwrite_economic_qr_p_row(self):
+        # any contiguous q and positively strided r
+        self.base_overwrite_qr('row', 3, True, True, 'economic')
+
+    def test_overwrite_qr_p_col(self):
+        # only F ordered q and r can be overwritten for cols
+        # full and eco share code paths
+        self.base_overwrite_qr('col', 3, False, True)
+
+    def test_bad_which(self):
+        a, q, r = self.generate('sqr')
+        assert_raises(ValueError, qr_delete, q, r, 0, which='foo')
+
+    def test_bad_k(self):
+        a, q, r = self.generate('tall')
+        assert_raises(ValueError, qr_delete, q, r, q.shape[0], 1)
+        assert_raises(ValueError, qr_delete, q, r, -q.shape[0]-1, 1)
+        assert_raises(ValueError, qr_delete, q, r, r.shape[0], 1, 'col')
+        assert_raises(ValueError, qr_delete, q, r, -r.shape[0]-1, 1, 'col')
+
+    def test_bad_p(self):
+        a, q, r = self.generate('tall')
+        # p must be positive
+        assert_raises(ValueError, qr_delete, q, r, 0, -1)
+        assert_raises(ValueError, qr_delete, q, r, 0, -1, 'col')
+
+        # and nonzero
+        assert_raises(ValueError, qr_delete, q, r, 0, 0)
+        assert_raises(ValueError, qr_delete, q, r, 0, 0, 'col')
+
+        # must have at least k+p rows or cols, depending.
+        assert_raises(ValueError, qr_delete, q, r, 3, q.shape[0]-2)
+        assert_raises(ValueError, qr_delete, q, r, 3, r.shape[1]-2, 'col')
+
+    def test_empty_q(self):
+        a, q, r = self.generate('tall')
+        # same code path for 'row' and 'col'
+        assert_raises(ValueError, qr_delete, np.array([]), r, 0, 1)
+
+    def test_empty_r(self):
+        a, q, r = self.generate('tall')
+        # same code path for 'row' and 'col'
+        assert_raises(ValueError, qr_delete, q, np.array([]), 0, 1)
+
+    def test_mismatched_q_and_r(self):
+        a, q, r = self.generate('tall')
+        r = r[1:]
+        assert_raises(ValueError, qr_delete, q, r, 0, 1)
+
+    def test_unsupported_dtypes(self):
+        dts = ['int8', 'int16', 'int32', 'int64',
+               'uint8', 'uint16', 'uint32', 'uint64',
+               'float16', 'longdouble', 'clongdouble',
+               'bool']
+        a, q0, r0 = self.generate('tall')
+        for dtype in dts:
+            q = q0.real.astype(dtype)
+            with np.errstate(invalid="ignore"):
+                r = r0.real.astype(dtype)
+            assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
+            assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'row')
+            assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
+            assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'col')
+
+            assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
+            assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'row')
+            assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
+            assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'col')
+
+    def test_check_finite(self):
+        a0, q0, r0 = self.generate('tall')
+
+        q = q0.copy('F')
+        q[1,1] = np.nan
+        assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
+        assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'row')
+        assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
+        assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'col')
+
+        r = r0.copy('F')
+        r[1,1] = np.nan
+        assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
+        assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'row')
+        assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
+        assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'col')
+
+    def test_qr_scalar(self):
+        a, q, r = self.generate('1x1')
+        assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'row')
+        assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'row')
+        assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'col')
+        assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'col')
+
+class TestQRdelete_f(BaseQRdelete):
+    dtype = np.dtype('f')
+
+class TestQRdelete_F(BaseQRdelete):
+    dtype = np.dtype('F')
+
+class TestQRdelete_d(BaseQRdelete):
+    dtype = np.dtype('d')
+
+class TestQRdelete_D(BaseQRdelete):
+    dtype = np.dtype('D')
+
+class BaseQRinsert(BaseQRdeltas):
+    def generate(self, type, mode='full', which='row', p=1):
+        a, q, r = super().generate(type, mode)
+
+        assert_(p > 0)
+        rng = np.random.RandomState(1234)
+
+        # super call set the seed...
+        if which == 'row':
+            if p == 1:
+                u = rng.random(a.shape[1])
+            else:
+                u = rng.random((p, a.shape[1]))
+        elif which == 'col':
+            if p == 1:
+                u = rng.random(a.shape[0])
+            else:
+                u = rng.random((a.shape[0], p))
+        else:
+            ValueError('which should be either "row" or "col"')
+
+        if np.iscomplexobj(self.dtype.type(1)):
+            b = rng.random(u.shape)
+            u = u + 1j * b
+
+        u = u.astype(self.dtype)
+        return a, q, r, u
+
+    def test_sqr_1_row(self):
+        a, q, r, u = self.generate('sqr', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_p_row(self):
+        # sqr + rows --> fat always
+        a, q, r, u = self.generate('sqr', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_1_col(self):
+        a, q, r, u = self.generate('sqr', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_p_col(self):
+        # sqr + cols --> fat always
+        a, q, r, u = self.generate('sqr', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_1_row(self):
+        a, q, r, u = self.generate('tall', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_p_row(self):
+        # tall + rows --> tall always
+        a, q, r, u = self.generate('tall', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_1_col(self):
+        a, q, r, u = self.generate('tall', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    # for column adds to tall matrices there are three cases to test
+    # tall + pcol --> tall
+    # tall + pcol --> sqr
+    # tall + pcol --> fat
+    def base_tall_p_col_xxx(self, p):
+        a, q, r, u = self.generate('tall', which='col', p=p)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_p_col_tall(self):
+        # 12x7 + 12x3 = 12x10 --> stays tall
+        self.base_tall_p_col_xxx(3)
+
+    def test_tall_p_col_sqr(self):
+        # 12x7 + 12x5 = 12x12 --> becomes sqr
+        self.base_tall_p_col_xxx(5)
+
+    def test_tall_p_col_fat(self):
+        # 12x7 + 12x7 = 12x14 --> becomes fat
+        self.base_tall_p_col_xxx(7)
+
+    def test_fat_1_row(self):
+        a, q, r, u = self.generate('fat', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    # for row adds to fat matrices there are three cases to test
+    # fat + prow --> fat
+    # fat + prow --> sqr
+    # fat + prow --> tall
+    def base_fat_p_row_xxx(self, p):
+        a, q, r, u = self.generate('fat', which='row', p=p)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(p, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_p_row_fat(self):
+        # 7x12 + 3x12 = 10x12 --> stays fat
+        self.base_fat_p_row_xxx(3)
+
+    def test_fat_p_row_sqr(self):
+        # 7x12 + 5x12 = 12x12 --> becomes sqr
+        self.base_fat_p_row_xxx(5)
+
+    def test_fat_p_row_tall(self):
+        # 7x12 + 7x12 = 14x12 --> becomes tall
+        self.base_fat_p_row_xxx(7)
+
+    def test_fat_1_col(self):
+        a, q, r, u = self.generate('fat', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_p_col(self):
+        # fat + cols --> fat always
+        a, q, r, u = self.generate('fat', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_economic_1_row(self):
+        a, q, r, u = self.generate('tall', 'economic', 'row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_p_row(self):
+        # tall + rows --> tall always
+        a, q, r, u = self.generate('tall', 'economic', 'row', 3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_1_col(self):
+        a, q, r, u = self.generate('tall', 'economic', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u.copy(), col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_1_col_bad_update(self):
+        # When the column to be added lies in the span of Q, the update is
+        # not meaningful.  This is detected, and a LinAlgError is issued.
+        q = np.eye(5, 3, dtype=self.dtype)
+        r = np.eye(3, dtype=self.dtype)
+        u = np.array([1, 0, 0, 0, 0], self.dtype)
+        assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col')
+
+    # for column adds to economic matrices there are three cases to test
+    # eco + pcol --> eco
+    # eco + pcol --> sqr
+    # eco + pcol --> fat
+    def base_economic_p_col_xxx(self, p):
+        a, q, r, u = self.generate('tall', 'economic', which='col', p=p)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_p_col_eco(self):
+        # 12x7 + 12x3 = 12x10 --> stays eco
+        self.base_economic_p_col_xxx(3)
+
+    def test_economic_p_col_sqr(self):
+        # 12x7 + 12x5 = 12x12 --> becomes sqr
+        self.base_economic_p_col_xxx(5)
+
+    def test_economic_p_col_fat(self):
+        # 12x7 + 12x7 = 12x14 --> becomes fat
+        self.base_economic_p_col_xxx(7)
+
+    def test_Mx1_1_row(self):
+        a, q, r, u = self.generate('Mx1', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_p_row(self):
+        a, q, r, u = self.generate('Mx1', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_1_col(self):
+        a, q, r, u = self.generate('Mx1', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_p_col(self):
+        a, q, r, u = self.generate('Mx1', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_economic_1_row(self):
+        a, q, r, u = self.generate('Mx1', 'economic', 'row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_p_row(self):
+        a, q, r, u = self.generate('Mx1', 'economic', 'row', 3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_1_col(self):
+        a, q, r, u = self.generate('Mx1', 'economic', 'col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_p_col(self):
+        a, q, r, u = self.generate('Mx1', 'economic', 'col', 3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_1xN_1_row(self):
+        a, q, r, u = self.generate('1xN', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_p_row(self):
+        a, q, r, u = self.generate('1xN', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_1_col(self):
+        a, q, r, u = self.generate('1xN', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_p_col(self):
+        a, q, r, u = self.generate('1xN', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_1_row(self):
+        a, q, r, u = self.generate('1x1', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_p_row(self):
+        a, q, r, u = self.generate('1x1', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_1_col(self):
+        a, q, r, u = self.generate('1x1', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_p_col(self):
+        a, q, r, u = self.generate('1x1', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_1_scalar(self):
+        a, q, r, u = self.generate('1x1', which='row')
+        assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'row')
+
+        assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'col')
+
+    def base_non_simple_strides(self, adjust_strides, k, p, which):
+        for type in ['sqr', 'tall', 'fat']:
+            a, q0, r0, u0 = self.generate(type, which=which, p=p)
+            qs, rs, us = adjust_strides((q0, r0, u0))
+            if p == 1:
+                ai = np.insert(a, k, u0, 0 if which == 'row' else 1)
+            else:
+                ai = np.insert(a, np.full(p, k, np.intp),
+                        u0 if which == 'row' else u0,
+                        0 if which == 'row' else 1)
+
+            # for each variable, q, r, u we try with it strided and
+            # overwrite=False. Then we try with overwrite=True. Nothing
+            # is checked to see if it can be overwritten, since only
+            # F ordered Q can be overwritten when adding columns.
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            q1, r1 = qr_insert(qs, r, u, k, which, overwrite_qru=False)
+            check_qr(q1, r1, ai, self.rtol, self.atol)
+            q1o, r1o = qr_insert(qs, r, u, k, which, overwrite_qru=True)
+            check_qr(q1o, r1o, ai, self.rtol, self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            q2, r2 = qr_insert(q, rs, u, k, which, overwrite_qru=False)
+            check_qr(q2, r2, ai, self.rtol, self.atol)
+            q2o, r2o = qr_insert(q, rs, u, k, which, overwrite_qru=True)
+            check_qr(q2o, r2o, ai, self.rtol, self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            q3, r3 = qr_insert(q, r, us, k, which, overwrite_qru=False)
+            check_qr(q3, r3, ai, self.rtol, self.atol)
+            q3o, r3o = qr_insert(q, r, us, k, which, overwrite_qru=True)
+            check_qr(q3o, r3o, ai, self.rtol, self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            # since some of these were consumed above
+            qs, rs, us = adjust_strides((q, r, u))
+            q5, r5 = qr_insert(qs, rs, us, k, which, overwrite_qru=False)
+            check_qr(q5, r5, ai, self.rtol, self.atol)
+            q5o, r5o = qr_insert(qs, rs, us, k, which, overwrite_qru=True)
+            check_qr(q5o, r5o, ai, self.rtol, self.atol)
+
+    def test_non_unit_strides_1_row(self):
+        self.base_non_simple_strides(make_strided, 0, 1, 'row')
+
+    def test_non_unit_strides_p_row(self):
+        self.base_non_simple_strides(make_strided, 0, 3, 'row')
+
+    def test_non_unit_strides_1_col(self):
+        self.base_non_simple_strides(make_strided, 0, 1, 'col')
+
+    def test_non_unit_strides_p_col(self):
+        self.base_non_simple_strides(make_strided, 0, 3, 'col')
+
+    def test_neg_strides_1_row(self):
+        self.base_non_simple_strides(negate_strides, 0, 1, 'row')
+
+    def test_neg_strides_p_row(self):
+        self.base_non_simple_strides(negate_strides, 0, 3, 'row')
+
+    def test_neg_strides_1_col(self):
+        self.base_non_simple_strides(negate_strides, 0, 1, 'col')
+
+    def test_neg_strides_p_col(self):
+        self.base_non_simple_strides(negate_strides, 0, 3, 'col')
+
+    def test_non_itemsize_strides_1_row(self):
+        self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'row')
+
+    def test_non_itemsize_strides_p_row(self):
+        self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'row')
+
+    def test_non_itemsize_strides_1_col(self):
+        self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'col')
+
+    def test_non_itemsize_strides_p_col(self):
+        self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'col')
+
+    def test_non_native_byte_order_1_row(self):
+        self.base_non_simple_strides(make_nonnative, 0, 1, 'row')
+
+    def test_non_native_byte_order_p_row(self):
+        self.base_non_simple_strides(make_nonnative, 0, 3, 'row')
+
+    def test_non_native_byte_order_1_col(self):
+        self.base_non_simple_strides(make_nonnative, 0, 1, 'col')
+
+    def test_non_native_byte_order_p_col(self):
+        self.base_non_simple_strides(make_nonnative, 0, 3, 'col')
+
+    def test_overwrite_qu_rank_1(self):
+        # when inserting rows, the size of both Q and R change, so only
+        # column inserts can overwrite q. Only complex column inserts
+        # with C ordered Q overwrite u. Any contiguous Q is overwritten
+        # when inserting 1 column
+        a, q0, r, u, = self.generate('sqr', which='col', p=1)
+        q = q0.copy('C')
+        u0 = u.copy()
+        # don't overwrite
+        q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
+        a1 = np.insert(a, 0, u0, 1)
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+        check_qr(q, r, a, self.rtol, self.atol)
+
+        # try overwriting
+        q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
+        check_qr(q2, r2, a1, self.rtol, self.atol)
+        # verify the overwriting
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(u, u0.conj(), self.rtol, self.atol)
+
+        # now try with a fortran ordered Q
+        qF = q0.copy('F')
+        u1 = u0.copy()
+        q3, r3 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=False)
+        check_qr(q3, r3, a1, self.rtol, self.atol)
+        check_qr(qF, r, a, self.rtol, self.atol)
+
+        # try overwriting
+        q4, r4 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=True)
+        check_qr(q4, r4, a1, self.rtol, self.atol)
+        assert_allclose(q4, qF, rtol=self.rtol, atol=self.atol)
+
+    def test_overwrite_qu_rank_p(self):
+        # when inserting rows, the size of both Q and R change, so only
+        # column inserts can potentially overwrite Q.  In practice, only
+        # F ordered Q are overwritten with a rank p update.
+        a, q0, r, u, = self.generate('sqr', which='col', p=3)
+        q = q0.copy('F')
+        a1 = np.insert(a, np.zeros(3, np.intp), u, 1)
+
+        # don't overwrite
+        q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+        check_qr(q, r, a, self.rtol, self.atol)
+
+        # try overwriting
+        q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
+        check_qr(q2, r2, a1, self.rtol, self.atol)
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+
+    def test_empty_inputs(self):
+        a, q, r, u = self.generate('sqr', which='row')
+        assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'row')
+        assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'col')
+
+    def test_mismatched_shapes(self):
+        a, q, r, u = self.generate('tall', which='row')
+        assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'col')
+
+    def test_unsupported_dtypes(self):
+        dts = ['int8', 'int16', 'int32', 'int64',
+               'uint8', 'uint16', 'uint32', 'uint64',
+               'float16', 'longdouble', 'clongdouble',
+               'bool']
+        a, q0, r0, u0 = self.generate('sqr', which='row')
+        for dtype in dts:
+            q = q0.real.astype(dtype)
+            with np.errstate(invalid="ignore"):
+                r = r0.real.astype(dtype)
+            u = u0.real.astype(dtype)
+            assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
+            assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
+            assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
+            assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
+            assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
+            assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
+
+    def test_check_finite(self):
+        a0, q0, r0, u0 = self.generate('sqr', which='row', p=3)
+
+        q = q0.copy('F')
+        q[1,1] = np.nan
+        assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
+
+        r = r0.copy('F')
+        r[1,1] = np.nan
+        assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'row')
+        assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
+        assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'col')
+        assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
+
+        u = u0.copy('F')
+        u[0,0] = np.nan
+        assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'row')
+        assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'col')
+        assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
+
+class TestQRinsert_f(BaseQRinsert):
+    dtype = np.dtype('f')
+
+class TestQRinsert_F(BaseQRinsert):
+    dtype = np.dtype('F')
+
+class TestQRinsert_d(BaseQRinsert):
+    dtype = np.dtype('d')
+
+class TestQRinsert_D(BaseQRinsert):
+    dtype = np.dtype('D')
+
+class BaseQRupdate(BaseQRdeltas):
+    def generate(self, type, mode='full', p=1):
+        a, q, r = super().generate(type, mode)
+
+        # super call set the seed...
+        if p == 1:
+            u = np.random.random(q.shape[0])
+            v = np.random.random(r.shape[1])
+        else:
+            u = np.random.random((q.shape[0], p))
+            v = np.random.random((r.shape[1], p))
+
+        if np.iscomplexobj(self.dtype.type(1)):
+            b = np.random.random(u.shape)
+            u = u + 1j * b
+
+            c = np.random.random(v.shape)
+            v = v + 1j * c
+
+        u = u.astype(self.dtype)
+        v = v.astype(self.dtype)
+        return a, q, r, u, v
+
+    def test_sqr_rank_1(self):
+        a, q, r, u, v = self.generate('sqr')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_rank_p(self):
+        # test ndim = 2, rank 1 updates here too
+        for p in [1, 2, 3, 5]:
+            a, q, r, u, v = self.generate('sqr', p=p)
+            if p == 1:
+                u = u.reshape(u.size, 1)
+                v = v.reshape(v.size, 1)
+            q1, r1 = qr_update(q, r, u, v, False)
+            a1 = a + np.dot(u, v.T.conj())
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_rank_1(self):
+        a, q, r, u, v = self.generate('tall')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_rank_p(self):
+        for p in [1, 2, 3, 5]:
+            a, q, r, u, v = self.generate('tall', p=p)
+            if p == 1:
+                u = u.reshape(u.size, 1)
+                v = v.reshape(v.size, 1)
+            q1, r1 = qr_update(q, r, u, v, False)
+            a1 = a + np.dot(u, v.T.conj())
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_rank_1(self):
+        a, q, r, u, v = self.generate('fat')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_rank_p(self):
+        for p in [1, 2, 3, 5]:
+            a, q, r, u, v = self.generate('fat', p=p)
+            if p == 1:
+                u = u.reshape(u.size, 1)
+                v = v.reshape(v.size, 1)
+            q1, r1 = qr_update(q, r, u, v, False)
+            a1 = a + np.dot(u, v.T.conj())
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_economic_rank_1(self):
+        a, q, r, u, v = self.generate('tall', 'economic')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_rank_p(self):
+        for p in [1, 2, 3, 5]:
+            a, q, r, u, v = self.generate('tall', 'economic', p)
+            if p == 1:
+                u = u.reshape(u.size, 1)
+                v = v.reshape(v.size, 1)
+            q1, r1 = qr_update(q, r, u, v, False)
+            a1 = a + np.dot(u, v.T.conj())
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_rank_1(self):
+        a, q, r, u, v = self.generate('Mx1')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_rank_p(self):
+        # when M or N == 1, only a rank 1 update is allowed. This isn't
+        # fundamental limitation, but the code does not support it.
+        a, q, r, u, v = self.generate('Mx1', p=1)
+        u = u.reshape(u.size, 1)
+        v = v.reshape(v.size, 1)
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.dot(u, v.T.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_economic_rank_1(self):
+        a, q, r, u, v = self.generate('Mx1', 'economic')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_rank_p(self):
+        # when M or N == 1, only a rank 1 update is allowed. This isn't
+        # fundamental limitation, but the code does not support it.
+        a, q, r, u, v = self.generate('Mx1', 'economic', p=1)
+        u = u.reshape(u.size, 1)
+        v = v.reshape(v.size, 1)
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.dot(u, v.T.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_1xN_rank_1(self):
+        a, q, r, u, v = self.generate('1xN')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_rank_p(self):
+        # when M or N == 1, only a rank 1 update is allowed. This isn't
+        # fundamental limitation, but the code does not support it.
+        a, q, r, u, v = self.generate('1xN', p=1)
+        u = u.reshape(u.size, 1)
+        v = v.reshape(v.size, 1)
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.dot(u, v.T.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_rank_1(self):
+        a, q, r, u, v = self.generate('1x1')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_rank_p(self):
+        # when M or N == 1, only a rank 1 update is allowed. This isn't
+        # fundamental limitation, but the code does not support it.
+        a, q, r, u, v = self.generate('1x1', p=1)
+        u = u.reshape(u.size, 1)
+        v = v.reshape(v.size, 1)
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.dot(u, v.T.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_rank_1_scalar(self):
+        a, q, r, u, v = self.generate('1x1')
+        assert_raises(ValueError, qr_update, q[0, 0], r, u, v)
+        assert_raises(ValueError, qr_update, q, r[0, 0], u, v)
+        assert_raises(ValueError, qr_update, q, r, u[0], v)
+        assert_raises(ValueError, qr_update, q, r, u, v[0])
+
+    def base_non_simple_strides(self, adjust_strides, mode, p, overwriteable):
+        assert_sqr = False if mode == 'economic' else True
+        for type in ['sqr', 'tall', 'fat']:
+            a, q0, r0, u0, v0 = self.generate(type, mode, p)
+            qs, rs, us, vs = adjust_strides((q0, r0, u0, v0))
+            if p == 1:
+                aup = a + np.outer(u0, v0.conj())
+            else:
+                aup = a + np.dot(u0, v0.T.conj())
+
+            # for each variable, q, r, u, v we try with it strided and
+            # overwrite=False. Then we try with overwrite=True, and make
+            # sure that if p == 1, r and v are still overwritten.
+            # a strided q and u must always be copied.
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            q1, r1 = qr_update(qs, r, u, v, False)
+            check_qr(q1, r1, aup, self.rtol, self.atol, assert_sqr)
+            q1o, r1o = qr_update(qs, r, u, v, True)
+            check_qr(q1o, r1o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r1o, r, rtol=self.rtol, atol=self.atol)
+                assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            q2, r2 = qr_update(q, rs, u, v, False)
+            check_qr(q2, r2, aup, self.rtol, self.atol, assert_sqr)
+            q2o, r2o = qr_update(q, rs, u, v, True)
+            check_qr(q2o, r2o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r2o, rs, rtol=self.rtol, atol=self.atol)
+                assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            q3, r3 = qr_update(q, r, us, v, False)
+            check_qr(q3, r3, aup, self.rtol, self.atol, assert_sqr)
+            q3o, r3o = qr_update(q, r, us, v, True)
+            check_qr(q3o, r3o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r3o, r, rtol=self.rtol, atol=self.atol)
+                assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            q4, r4 = qr_update(q, r, u, vs, False)
+            check_qr(q4, r4, aup, self.rtol, self.atol, assert_sqr)
+            q4o, r4o = qr_update(q, r, u, vs, True)
+            check_qr(q4o, r4o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r4o, r, rtol=self.rtol, atol=self.atol)
+                assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            # since some of these were consumed above
+            qs, rs, us, vs = adjust_strides((q, r, u, v))
+            q5, r5 = qr_update(qs, rs, us, vs, False)
+            check_qr(q5, r5, aup, self.rtol, self.atol, assert_sqr)
+            q5o, r5o = qr_update(qs, rs, us, vs, True)
+            check_qr(q5o, r5o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r5o, rs, rtol=self.rtol, atol=self.atol)
+                assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+    def test_non_unit_strides_rank_1(self):
+        self.base_non_simple_strides(make_strided, 'full', 1, True)
+
+    def test_non_unit_strides_economic_rank_1(self):
+        self.base_non_simple_strides(make_strided, 'economic', 1, True)
+
+    def test_non_unit_strides_rank_p(self):
+        self.base_non_simple_strides(make_strided, 'full', 3, False)
+
+    def test_non_unit_strides_economic_rank_p(self):
+        self.base_non_simple_strides(make_strided, 'economic', 3, False)
+
+    def test_neg_strides_rank_1(self):
+        self.base_non_simple_strides(negate_strides, 'full', 1, False)
+
+    def test_neg_strides_economic_rank_1(self):
+        self.base_non_simple_strides(negate_strides, 'economic', 1, False)
+
+    def test_neg_strides_rank_p(self):
+        self.base_non_simple_strides(negate_strides, 'full', 3, False)
+
+    def test_neg_strides_economic_rank_p(self):
+        self.base_non_simple_strides(negate_strides, 'economic', 3, False)
+
+    def test_non_itemsize_strides_rank_1(self):
+        self.base_non_simple_strides(nonitemsize_strides, 'full', 1, False)
+
+    def test_non_itemsize_strides_economic_rank_1(self):
+        self.base_non_simple_strides(nonitemsize_strides, 'economic', 1, False)
+
+    def test_non_itemsize_strides_rank_p(self):
+        self.base_non_simple_strides(nonitemsize_strides, 'full', 3, False)
+
+    def test_non_itemsize_strides_economic_rank_p(self):
+        self.base_non_simple_strides(nonitemsize_strides, 'economic', 3, False)
+
+    def test_non_native_byte_order_rank_1(self):
+        self.base_non_simple_strides(make_nonnative, 'full', 1, False)
+
+    def test_non_native_byte_order_economic_rank_1(self):
+        self.base_non_simple_strides(make_nonnative, 'economic', 1, False)
+
+    def test_non_native_byte_order_rank_p(self):
+        self.base_non_simple_strides(make_nonnative, 'full', 3, False)
+
+    def test_non_native_byte_order_economic_rank_p(self):
+        self.base_non_simple_strides(make_nonnative, 'economic', 3, False)
+
+    def test_overwrite_qruv_rank_1(self):
+        # Any positive strided q, r, u, and v can be overwritten for a rank 1
+        # update, only checking C and F contiguous.
+        a, q0, r0, u0, v0 = self.generate('sqr')
+        a1 = a + np.outer(u0, v0.conj())
+        q = q0.copy('F')
+        r = r0.copy('F')
+        u = u0.copy('F')
+        v = v0.copy('F')
+
+        # don't overwrite
+        q1, r1 = qr_update(q, r, u, v, False)
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+        check_qr(q, r, a, self.rtol, self.atol)
+
+        q2, r2 = qr_update(q, r, u, v, True)
+        check_qr(q2, r2, a1, self.rtol, self.atol)
+        # verify the overwriting, no good way to check u and v.
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+        q = q0.copy('C')
+        r = r0.copy('C')
+        u = u0.copy('C')
+        v = v0.copy('C')
+        q3, r3 = qr_update(q, r, u, v, True)
+        check_qr(q3, r3, a1, self.rtol, self.atol)
+        assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
+
+    def test_overwrite_qruv_rank_1_economic(self):
+        # updating economic decompositions can overwrite any contiguous r,
+        # and positively strided r and u. V is only ever read.
+        # only checking C and F contiguous.
+        a, q0, r0, u0, v0 = self.generate('tall', 'economic')
+        a1 = a + np.outer(u0, v0.conj())
+        q = q0.copy('F')
+        r = r0.copy('F')
+        u = u0.copy('F')
+        v = v0.copy('F')
+
+        # don't overwrite
+        q1, r1 = qr_update(q, r, u, v, False)
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+        check_qr(q, r, a, self.rtol, self.atol, False)
+
+        q2, r2 = qr_update(q, r, u, v, True)
+        check_qr(q2, r2, a1, self.rtol, self.atol, False)
+        # verify the overwriting, no good way to check u and v.
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+        q = q0.copy('C')
+        r = r0.copy('C')
+        u = u0.copy('C')
+        v = v0.copy('C')
+        q3, r3 = qr_update(q, r, u, v, True)
+        check_qr(q3, r3, a1, self.rtol, self.atol, False)
+        assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
+
+    def test_overwrite_qruv_rank_p(self):
+        # for rank p updates, q r must be F contiguous, v must be C (v.T --> F)
+        # and u can be C or F, but is only overwritten if Q is C and complex
+        a, q0, r0, u0, v0 = self.generate('sqr', p=3)
+        a1 = a + np.dot(u0, v0.T.conj())
+        q = q0.copy('F')
+        r = r0.copy('F')
+        u = u0.copy('F')
+        v = v0.copy('C')
+
+        # don't overwrite
+        q1, r1 = qr_update(q, r, u, v, False)
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+        check_qr(q, r, a, self.rtol, self.atol)
+
+        q2, r2 = qr_update(q, r, u, v, True)
+        check_qr(q2, r2, a1, self.rtol, self.atol)
+        # verify the overwriting, no good way to check u and v.
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+    def test_empty_inputs(self):
+        a, q, r, u, v = self.generate('tall')
+        assert_raises(ValueError, qr_update, np.array([]), r, u, v)
+        assert_raises(ValueError, qr_update, q, np.array([]), u, v)
+        assert_raises(ValueError, qr_update, q, r, np.array([]), v)
+        assert_raises(ValueError, qr_update, q, r, u, np.array([]))
+
+    def test_mismatched_shapes(self):
+        a, q, r, u, v = self.generate('tall')
+        assert_raises(ValueError, qr_update, q, r[1:], u, v)
+        assert_raises(ValueError, qr_update, q[:-2], r, u, v)
+        assert_raises(ValueError, qr_update, q, r, u[1:], v)
+        assert_raises(ValueError, qr_update, q, r, u, v[1:])
+
+    def test_unsupported_dtypes(self):
+        dts = ['int8', 'int16', 'int32', 'int64',
+               'uint8', 'uint16', 'uint32', 'uint64',
+               'float16', 'longdouble', 'clongdouble',
+               'bool']
+        a, q0, r0, u0, v0 = self.generate('tall')
+        for dtype in dts:
+            q = q0.real.astype(dtype)
+            with np.errstate(invalid="ignore"):
+                r = r0.real.astype(dtype)
+            u = u0.real.astype(dtype)
+            v = v0.real.astype(dtype)
+            assert_raises(ValueError, qr_update, q, r0, u0, v0)
+            assert_raises(ValueError, qr_update, q0, r, u0, v0)
+            assert_raises(ValueError, qr_update, q0, r0, u, v0)
+            assert_raises(ValueError, qr_update, q0, r0, u0, v)
+
+    def test_integer_input(self):
+        q = np.arange(16).reshape(4, 4)
+        r = q.copy()  # doesn't matter
+        u = q[:, 0].copy()
+        v = r[0, :].copy()
+        assert_raises(ValueError, qr_update, q, r, u, v)
+
+    def test_check_finite(self):
+        a0, q0, r0, u0, v0 = self.generate('tall', p=3)
+
+        q = q0.copy('F')
+        q[1,1] = np.nan
+        assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q, r0, u0, v0)
+
+        r = r0.copy('F')
+        r[1,1] = np.nan
+        assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q0, r, u0, v0)
+
+        u = u0.copy('F')
+        u[0,0] = np.nan
+        assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q0, r0, u, v0)
+
+        v = v0.copy('F')
+        v[0,0] = np.nan
+        assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
+        assert_raises(ValueError, qr_update, q0, r0, u, v)
+
+    def test_economic_check_finite(self):
+        a0, q0, r0, u0, v0 = self.generate('tall', mode='economic', p=3)
+
+        q = q0.copy('F')
+        q[1,1] = np.nan
+        assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q, r0, u0, v0)
+
+        r = r0.copy('F')
+        r[1,1] = np.nan
+        assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q0, r, u0, v0)
+
+        u = u0.copy('F')
+        u[0,0] = np.nan
+        assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q0, r0, u, v0)
+
+        v = v0.copy('F')
+        v[0,0] = np.nan
+        assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
+        assert_raises(ValueError, qr_update, q0, r0, u, v)
+
+    def test_u_exactly_in_span_q(self):
+        q = np.array([[0, 0], [0, 0], [1, 0], [0, 1]], self.dtype)
+        r = np.array([[1, 0], [0, 1]], self.dtype)
+        u = np.array([0, 0, 0, -1], self.dtype)
+        v = np.array([1, 2], self.dtype)
+        q1, r1 = qr_update(q, r, u, v)
+        a1 = np.dot(q, r) + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+class TestQRupdate_f(BaseQRupdate):
+    dtype = np.dtype('f')
+
+class TestQRupdate_F(BaseQRupdate):
+    dtype = np.dtype('F')
+
+class TestQRupdate_d(BaseQRupdate):
+    dtype = np.dtype('d')
+
+class TestQRupdate_D(BaseQRupdate):
+    dtype = np.dtype('D')
+
+def test_form_qTu():
+    # We want to ensure that all of the code paths through this function are
+    # tested. Most of them should be hit with the rest of test suite, but
+    # explicit tests make clear precisely what is being tested.
+    #
+    # This function expects that Q is either C or F contiguous and square.
+    # Economic mode decompositions (Q is (M, N), M != N) do not go through this
+    # function. U may have any positive strides.
+    #
+    # Some of these test are duplicates, since contiguous 1d arrays are both C
+    # and F.
+
+    q_order = ['F', 'C']
+    q_shape = [(8, 8), ]
+    u_order = ['F', 'C', 'A']  # here A means is not F not C
+    u_shape = [1, 3]
+    dtype = ['f', 'd', 'F', 'D']
+
+    for qo, qs, uo, us, d in \
+            itertools.product(q_order, q_shape, u_order, u_shape, dtype):
+        if us == 1:
+            check_form_qTu(qo, qs, uo, us, 1, d)
+            check_form_qTu(qo, qs, uo, us, 2, d)
+        else:
+            check_form_qTu(qo, qs, uo, us, 2, d)
+
+def check_form_qTu(q_order, q_shape, u_order, u_shape, u_ndim, dtype):
+    np.random.seed(47)
+    if u_shape == 1 and u_ndim == 1:
+        u_shape = (q_shape[0],)
+    else:
+        u_shape = (q_shape[0], u_shape)
+    dtype = np.dtype(dtype)
+
+    if dtype.char in 'fd':
+        q = np.random.random(q_shape)
+        u = np.random.random(u_shape)
+    elif dtype.char in 'FD':
+        q = np.random.random(q_shape) + 1j*np.random.random(q_shape)
+        u = np.random.random(u_shape) + 1j*np.random.random(u_shape)
+    else:
+        ValueError("form_qTu doesn't support this dtype")
+
+    q = np.require(q, dtype, q_order)
+    if u_order != 'A':
+        u = np.require(u, dtype, u_order)
+    else:
+        u, = make_strided((u.astype(dtype),))
+
+    rtol = 10.0 ** -(np.finfo(dtype).precision-2)
+    atol = 2*np.finfo(dtype).eps
+
+    expected = np.dot(q.T.conj(), u)
+    res = _decomp_update._form_qTu(q, u)
+    assert_allclose(res, expected, rtol=rtol, atol=atol)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..36e4692cd9717a221cc683a663e8ee23a81aa5b6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py
@@ -0,0 +1,46 @@
+import os
+import platform
+import sysconfig
+
+import numpy as np
+import pytest
+
+from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython
+from scipy.linalg.blas import cdotu  # type: ignore[attr-defined]
+from scipy.linalg.lapack import dgtsv  # type: ignore[attr-defined]
+
+
+@pytest.mark.fail_slow(120)
+# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247
+@pytest.mark.skipif(IS_EDITABLE,
+                    reason='Editable install cannot find .pxd headers.')
+@pytest.mark.skipif((platform.system() == 'Windows' and
+                     sysconfig.get_config_var('Py_GIL_DISABLED')),
+                    reason='gh-22039')
+@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"],
+                    reason="Can't start subprocess")
+@pytest.mark.skipif(cython is None, reason="requires cython")
+def test_cython(tmp_path):
+    srcdir = os.path.dirname(os.path.dirname(__file__))
+    extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir)
+    # actually test the cython c-extensions
+    a = np.ones(8) * 3
+    b = np.ones(9)
+    c = np.ones(8) * 4
+    x = np.ones(9)
+    _, _, _, x, _ = dgtsv(a, b, c, x)
+    a = np.ones(8) * 3
+    b = np.ones(9)
+    c = np.ones(8) * 4
+    x_c = np.ones(9)
+    extensions.tridiag(a, b, c, x_c)
+    a = np.ones(8) * 3
+    b = np.ones(9)
+    c = np.ones(8) * 4
+    x_cpp = np.ones(9)
+    extensions_cpp.tridiag(a, b, c, x_cpp)
+    np.testing.assert_array_equal(x, x_cpp)
+    cx = np.array([1-1j, 2+2j, 3-3j], dtype=np.complex64)
+    cy = np.array([4+4j, 5-5j, 6+6j], dtype=np.complex64)
+    np.testing.assert_array_equal(cdotu(cx, cy), extensions.complex_dot(cx, cy))
+    np.testing.assert_array_equal(cdotu(cx, cy), extensions_cpp.complex_dot(cx, cy))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c5ada830043af0eecb6d04bf39aef13d29d777c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py
@@ -0,0 +1,607 @@
+# Test interfaces to fortran blas.
+#
+# The tests are more of interface than they are of the underlying blas.
+# Only very small matrices checked -- N=3 or so.
+#
+# !! Complex calculations really aren't checked that carefully.
+# !! Only real valued complex numbers are used in tests.
+
+from numpy import float32, float64, complex64, complex128, arange, array, \
+                  zeros, shape, transpose, newaxis, common_type, conjugate
+
+from scipy.linalg import _fblas as fblas
+
+from numpy.testing import assert_array_equal, \
+    assert_allclose, assert_array_almost_equal, assert_
+
+import pytest
+
+# decimal accuracy to require between Python and LAPACK/BLAS calculations
+accuracy = 5
+
+# Since numpy.dot likely uses the same blas, use this routine
+# to check.
+
+
+def matrixmultiply(a, b):
+    if len(b.shape) == 1:
+        b_is_vector = True
+        b = b[:, newaxis]
+    else:
+        b_is_vector = False
+    assert_(a.shape[1] == b.shape[0])
+    c = zeros((a.shape[0], b.shape[1]), common_type(a, b))
+    for i in range(a.shape[0]):
+        for j in range(b.shape[1]):
+            s = 0
+            for k in range(a.shape[1]):
+                s += a[i, k] * b[k, j]
+            c[i, j] = s
+    if b_is_vector:
+        c = c.reshape((a.shape[0],))
+    return c
+
+##################################################
+# Test blas ?axpy
+
+
+class BaseAxpy:
+    ''' Mixin class for axpy tests '''
+
+    def test_default_a(self):
+        x = arange(3., dtype=self.dtype)
+        y = arange(3., dtype=x.dtype)
+        real_y = x*1.+y
+        y = self.blas_func(x, y)
+        assert_array_equal(real_y, y)
+
+    def test_simple(self):
+        x = arange(3., dtype=self.dtype)
+        y = arange(3., dtype=x.dtype)
+        real_y = x*3.+y
+        y = self.blas_func(x, y, a=3.)
+        assert_array_equal(real_y, y)
+
+    def test_x_stride(self):
+        x = arange(6., dtype=self.dtype)
+        y = zeros(3, x.dtype)
+        y = arange(3., dtype=x.dtype)
+        real_y = x[::2]*3.+y
+        y = self.blas_func(x, y, a=3., n=3, incx=2)
+        assert_array_equal(real_y, y)
+
+    def test_y_stride(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        real_y = x*3.+y[::2]
+        y = self.blas_func(x, y, a=3., n=3, incy=2)
+        assert_array_equal(real_y, y[::2])
+
+    def test_x_and_y_stride(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        real_y = x[::4]*3.+y[::2]
+        y = self.blas_func(x, y, a=3., n=3, incx=4, incy=2)
+        assert_array_equal(real_y, y[::2])
+
+    def test_x_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=4, incx=5)
+
+    def test_y_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=3, incy=5)
+
+
+try:
+    class TestSaxpy(BaseAxpy):
+        blas_func = fblas.saxpy
+        dtype = float32
+except AttributeError:
+    class TestSaxpy:
+        pass
+
+
+class TestDaxpy(BaseAxpy):
+    blas_func = fblas.daxpy
+    dtype = float64
+
+
+try:
+    class TestCaxpy(BaseAxpy):
+        blas_func = fblas.caxpy
+        dtype = complex64
+except AttributeError:
+    class TestCaxpy:
+        pass
+
+
+class TestZaxpy(BaseAxpy):
+    blas_func = fblas.zaxpy
+    dtype = complex128
+
+
+##################################################
+# Test blas ?scal
+
+class BaseScal:
+    ''' Mixin class for scal testing '''
+
+    def test_simple(self):
+        x = arange(3., dtype=self.dtype)
+        real_x = x*3.
+        x = self.blas_func(3., x)
+        assert_array_equal(real_x, x)
+
+    def test_x_stride(self):
+        x = arange(6., dtype=self.dtype)
+        real_x = x.copy()
+        real_x[::2] = x[::2]*array(3., self.dtype)
+        x = self.blas_func(3., x, n=3, incx=2)
+        assert_array_equal(real_x, x)
+
+    def test_x_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(2., x, n=4, incx=5)
+
+
+try:
+    class TestSscal(BaseScal):
+        blas_func = fblas.sscal
+        dtype = float32
+except AttributeError:
+    class TestSscal:
+        pass
+
+
+class TestDscal(BaseScal):
+    blas_func = fblas.dscal
+    dtype = float64
+
+
+try:
+    class TestCscal(BaseScal):
+        blas_func = fblas.cscal
+        dtype = complex64
+except AttributeError:
+    class TestCscal:
+        pass
+
+
+class TestZscal(BaseScal):
+    blas_func = fblas.zscal
+    dtype = complex128
+
+
+##################################################
+# Test blas ?copy
+
+class BaseCopy:
+    ''' Mixin class for copy testing '''
+
+    def test_simple(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(shape(x), x.dtype)
+        y = self.blas_func(x, y)
+        assert_array_equal(x, y)
+
+    def test_x_stride(self):
+        x = arange(6., dtype=self.dtype)
+        y = zeros(3, x.dtype)
+        y = self.blas_func(x, y, n=3, incx=2)
+        assert_array_equal(x[::2], y)
+
+    def test_y_stride(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        y = self.blas_func(x, y, n=3, incy=2)
+        assert_array_equal(x, y[::2])
+
+    def test_x_and_y_stride(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        y = self.blas_func(x, y, n=3, incx=4, incy=2)
+        assert_array_equal(x[::4], y[::2])
+
+    def test_x_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=4, incx=5)
+
+    def test_y_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=3, incy=5)
+
+    # def test_y_bad_type(self):
+    ##   Hmmm. Should this work?  What should be the output.
+    #    x = arange(3.,dtype=self.dtype)
+    #    y = zeros(shape(x))
+    #    self.blas_func(x,y)
+    #    assert_array_equal(x,y)
+
+
+try:
+    class TestScopy(BaseCopy):
+        blas_func = fblas.scopy
+        dtype = float32
+except AttributeError:
+    class TestScopy:
+        pass
+
+
+class TestDcopy(BaseCopy):
+    blas_func = fblas.dcopy
+    dtype = float64
+
+
+try:
+    class TestCcopy(BaseCopy):
+        blas_func = fblas.ccopy
+        dtype = complex64
+except AttributeError:
+    class TestCcopy:
+        pass
+
+
+class TestZcopy(BaseCopy):
+    blas_func = fblas.zcopy
+    dtype = complex128
+
+
+##################################################
+# Test blas ?swap
+
+class BaseSwap:
+    ''' Mixin class for swap tests '''
+
+    def test_simple(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(shape(x), x.dtype)
+        desired_x = y.copy()
+        desired_y = x.copy()
+        x, y = self.blas_func(x, y)
+        assert_array_equal(desired_x, x)
+        assert_array_equal(desired_y, y)
+
+    def test_x_stride(self):
+        x = arange(6., dtype=self.dtype)
+        y = zeros(3, x.dtype)
+        desired_x = y.copy()
+        desired_y = x.copy()[::2]
+        x, y = self.blas_func(x, y, n=3, incx=2)
+        assert_array_equal(desired_x, x[::2])
+        assert_array_equal(desired_y, y)
+
+    def test_y_stride(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        desired_x = y.copy()[::2]
+        desired_y = x.copy()
+        x, y = self.blas_func(x, y, n=3, incy=2)
+        assert_array_equal(desired_x, x)
+        assert_array_equal(desired_y, y[::2])
+
+    def test_x_and_y_stride(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        desired_x = y.copy()[::2]
+        desired_y = x.copy()[::4]
+        x, y = self.blas_func(x, y, n=3, incx=4, incy=2)
+        assert_array_equal(desired_x, x[::4])
+        assert_array_equal(desired_y, y[::2])
+
+    def test_x_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=4, incx=5)
+
+    def test_y_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=3, incy=5)
+
+
+try:
+    class TestSswap(BaseSwap):
+        blas_func = fblas.sswap
+        dtype = float32
+except AttributeError:
+    class TestSswap:
+        pass
+
+
+class TestDswap(BaseSwap):
+    blas_func = fblas.dswap
+    dtype = float64
+
+
+try:
+    class TestCswap(BaseSwap):
+        blas_func = fblas.cswap
+        dtype = complex64
+except AttributeError:
+    class TestCswap:
+        pass
+
+
+class TestZswap(BaseSwap):
+    blas_func = fblas.zswap
+    dtype = complex128
+
+##################################################
+# Test blas ?gemv
+# This will be a mess to test all cases.
+
+
+class BaseGemv:
+    ''' Mixin class for gemv tests '''
+
+    def get_data(self, x_stride=1, y_stride=1):
+        mult = array(1, dtype=self.dtype)
+        if self.dtype in [complex64, complex128]:
+            mult = array(1+1j, dtype=self.dtype)
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1., dtype=self.dtype) * mult
+        beta = array(1., dtype=self.dtype) * mult
+        a = normal(0., 1., (3, 3)).astype(self.dtype) * mult
+        x = arange(shape(a)[0]*x_stride, dtype=self.dtype) * mult
+        y = arange(shape(a)[1]*y_stride, dtype=self.dtype) * mult
+        return alpha, beta, a, x, y
+
+    def test_simple(self):
+        alpha, beta, a, x, y = self.get_data()
+        desired_y = alpha*matrixmultiply(a, x)+beta*y
+        y = self.blas_func(alpha, a, x, beta, y)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_default_beta_y(self):
+        alpha, beta, a, x, y = self.get_data()
+        desired_y = matrixmultiply(a, x)
+        y = self.blas_func(1, a, x)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_simple_transpose(self):
+        alpha, beta, a, x, y = self.get_data()
+        desired_y = alpha*matrixmultiply(transpose(a), x)+beta*y
+        y = self.blas_func(alpha, a, x, beta, y, trans=1)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_simple_transpose_conj(self):
+        alpha, beta, a, x, y = self.get_data()
+        desired_y = alpha*matrixmultiply(transpose(conjugate(a)), x)+beta*y
+        y = self.blas_func(alpha, a, x, beta, y, trans=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_x_stride(self):
+        alpha, beta, a, x, y = self.get_data(x_stride=2)
+        desired_y = alpha*matrixmultiply(a, x[::2])+beta*y
+        y = self.blas_func(alpha, a, x, beta, y, incx=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_x_stride_transpose(self):
+        alpha, beta, a, x, y = self.get_data(x_stride=2)
+        desired_y = alpha*matrixmultiply(transpose(a), x[::2])+beta*y
+        y = self.blas_func(alpha, a, x, beta, y, trans=1, incx=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_x_stride_assert(self):
+        # What is the use of this test?
+        alpha, beta, a, x, y = self.get_data(x_stride=2)
+        with pytest.raises(Exception, match='failed for 3rd argument'):
+            y = self.blas_func(1, a, x, 1, y, trans=0, incx=3)
+        with pytest.raises(Exception, match='failed for 3rd argument'):
+            y = self.blas_func(1, a, x, 1, y, trans=1, incx=3)
+
+    def test_y_stride(self):
+        alpha, beta, a, x, y = self.get_data(y_stride=2)
+        desired_y = y.copy()
+        desired_y[::2] = alpha*matrixmultiply(a, x)+beta*y[::2]
+        y = self.blas_func(alpha, a, x, beta, y, incy=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_y_stride_transpose(self):
+        alpha, beta, a, x, y = self.get_data(y_stride=2)
+        desired_y = y.copy()
+        desired_y[::2] = alpha*matrixmultiply(transpose(a), x)+beta*y[::2]
+        y = self.blas_func(alpha, a, x, beta, y, trans=1, incy=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_y_stride_assert(self):
+        # What is the use of this test?
+        alpha, beta, a, x, y = self.get_data(y_stride=2)
+        with pytest.raises(Exception, match='failed for 2nd keyword'):
+            y = self.blas_func(1, a, x, 1, y, trans=0, incy=3)
+        with pytest.raises(Exception, match='failed for 2nd keyword'):
+            y = self.blas_func(1, a, x, 1, y, trans=1, incy=3)
+
+
+try:
+    class TestSgemv(BaseGemv):
+        blas_func = fblas.sgemv
+        dtype = float32
+
+        def test_sgemv_on_osx(self):
+            from itertools import product
+            import sys
+            import numpy as np
+
+            if sys.platform != 'darwin':
+                return
+
+            def aligned_array(shape, align, dtype, order='C'):
+                # Make array shape `shape` with aligned at `align` bytes
+                d = dtype()
+                # Make array of correct size with `align` extra bytes
+                N = np.prod(shape)
+                tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8)
+                address = tmp.__array_interface__["data"][0]
+                # Find offset into array giving desired alignment
+                for offset in range(align):
+                    if (address + offset) % align == 0:
+                        break
+                tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype)
+                return tmp.reshape(shape, order=order)
+
+            def as_aligned(arr, align, dtype, order='C'):
+                # Copy `arr` into an aligned array with same shape
+                aligned = aligned_array(arr.shape, align, dtype, order)
+                aligned[:] = arr[:]
+                return aligned
+
+            def assert_dot_close(A, X, desired):
+                assert_allclose(self.blas_func(1.0, A, X), desired,
+                                rtol=1e-5, atol=1e-7)
+
+            testdata = product((15, 32), (10000,), (200, 89), ('C', 'F'))
+            for align, m, n, a_order in testdata:
+                A_d = np.random.rand(m, n)
+                X_d = np.random.rand(n)
+                desired = np.dot(A_d, X_d)
+                # Calculation with aligned single precision
+                A_f = as_aligned(A_d, align, np.float32, order=a_order)
+                X_f = as_aligned(X_d, align, np.float32, order=a_order)
+                assert_dot_close(A_f, X_f, desired)
+
+except AttributeError:
+    class TestSgemv:
+        pass
+
+
+class TestDgemv(BaseGemv):
+    blas_func = fblas.dgemv
+    dtype = float64
+
+
+try:
+    class TestCgemv(BaseGemv):
+        blas_func = fblas.cgemv
+        dtype = complex64
+except AttributeError:
+    class TestCgemv:
+        pass
+
+
+class TestZgemv(BaseGemv):
+    blas_func = fblas.zgemv
+    dtype = complex128
+
+
+"""
+##################################################
+### Test blas ?ger
+### This will be a mess to test all cases.
+
+class BaseGer:
+    def get_data(self,x_stride=1,y_stride=1):
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1., dtype = self.dtype)
+        a = normal(0.,1.,(3,3)).astype(self.dtype)
+        x = arange(shape(a)[0]*x_stride,dtype=self.dtype)
+        y = arange(shape(a)[1]*y_stride,dtype=self.dtype)
+        return alpha,a,x,y
+    def test_simple(self):
+        alpha,a,x,y = self.get_data()
+        # transpose takes care of Fortran vs. C(and Python) memory layout
+        desired_a = alpha*transpose(x[:,newaxis]*y) + a
+        self.blas_func(x,y,a)
+        assert_array_almost_equal(desired_a,a)
+    def test_x_stride(self):
+        alpha,a,x,y = self.get_data(x_stride=2)
+        desired_a = alpha*transpose(x[::2,newaxis]*y) + a
+        self.blas_func(x,y,a,incx=2)
+        assert_array_almost_equal(desired_a,a)
+    def test_x_stride_assert(self):
+        alpha,a,x,y = self.get_data(x_stride=2)
+        with pytest.raises(ValueError, match='foo'):
+            self.blas_func(x,y,a,incx=3)
+    def test_y_stride(self):
+        alpha,a,x,y = self.get_data(y_stride=2)
+        desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a
+        self.blas_func(x,y,a,incy=2)
+        assert_array_almost_equal(desired_a,a)
+
+    def test_y_stride_assert(self):
+        alpha,a,x,y = self.get_data(y_stride=2)
+        with pytest.raises(ValueError, match='foo'):
+            self.blas_func(a,x,y,incy=3)
+
+class TestSger(BaseGer):
+    blas_func = fblas.sger
+    dtype = float32
+class TestDger(BaseGer):
+    blas_func = fblas.dger
+    dtype = float64
+"""
+##################################################
+# Test blas ?gerc
+# This will be a mess to test all cases.
+
+"""
+class BaseGerComplex(BaseGer):
+    def get_data(self,x_stride=1,y_stride=1):
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1+1j, dtype = self.dtype)
+        a = normal(0.,1.,(3,3)).astype(self.dtype)
+        a = a + normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype)
+        x = normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype)
+        x = x + x * array(1j, dtype = self.dtype)
+        y = normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype)
+        y = y + y * array(1j, dtype = self.dtype)
+        return alpha,a,x,y
+    def test_simple(self):
+        alpha,a,x,y = self.get_data()
+        # transpose takes care of Fortran vs. C(and Python) memory layout
+        a = a * array(0.,dtype = self.dtype)
+        #desired_a = alpha*transpose(x[:,newaxis]*self.transform(y)) + a
+        desired_a = alpha*transpose(x[:,newaxis]*y) + a
+        #self.blas_func(x,y,a,alpha = alpha)
+        fblas.cgeru(x,y,a,alpha = alpha)
+        assert_array_almost_equal(desired_a,a)
+
+    #def test_x_stride(self):
+    #    alpha,a,x,y = self.get_data(x_stride=2)
+    #    desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a
+    #    self.blas_func(x,y,a,incx=2)
+    #    assert_array_almost_equal(desired_a,a)
+    #def test_y_stride(self):
+    #    alpha,a,x,y = self.get_data(y_stride=2)
+    #    desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a
+    #    self.blas_func(x,y,a,incy=2)
+    #    assert_array_almost_equal(desired_a,a)
+
+class TestCgeru(BaseGerComplex):
+    blas_func = fblas.cgeru
+    dtype = complex64
+    def transform(self,x):
+        return x
+class TestZgeru(BaseGerComplex):
+    blas_func = fblas.zgeru
+    dtype = complex128
+    def transform(self,x):
+        return x
+
+class TestCgerc(BaseGerComplex):
+    blas_func = fblas.cgerc
+    dtype = complex64
+    def transform(self,x):
+        return conjugate(x)
+
+class TestZgerc(BaseGerComplex):
+    blas_func = fblas.zgerc
+    dtype = complex128
+    def transform(self,x):
+        return conjugate(x)
+"""
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e1cc5496eafe19ced81ea546e3bad386148ae7b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py
@@ -0,0 +1,232 @@
+#  ******************************************************************************
+#   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.
+#  ******************************************************************************
+
+import scipy.linalg.interpolative as pymatrixid
+import numpy as np
+from scipy.linalg import hilbert, svdvals, norm
+from scipy.sparse.linalg import aslinearoperator
+from scipy.linalg.interpolative import interp_decomp
+
+from numpy.testing import (assert_, assert_allclose, assert_equal,
+                           assert_array_equal)
+import pytest
+from pytest import raises as assert_raises
+
+
+@pytest.fixture()
+def eps():
+    yield 1e-12
+
+
+@pytest.fixture()
+def rng():
+    rng = np.random.default_rng(1718313768084012)
+    yield rng
+
+
+@pytest.fixture(params=[np.float64, np.complex128])
+def A(request):
+    # construct Hilbert matrix
+    # set parameters
+    n = 300
+    yield hilbert(n).astype(request.param)
+
+
+@pytest.fixture()
+def L(A):
+    yield aslinearoperator(A)
+
+
+@pytest.fixture()
+def rank(A, eps):
+    S = np.linalg.svd(A, compute_uv=False)
+    try:
+        rank = np.nonzero(S < eps)[0][0]
+    except IndexError:
+        rank = A.shape[0]
+    return rank
+
+
+class TestInterpolativeDecomposition:
+
+    @pytest.mark.parametrize(
+        "rand,lin_op",
+        [(False, False), (True, False), (True, True)])
+    def test_real_id_fixed_precision(self, A, L, eps, rand, lin_op, rng):
+        # Test ID routines on a Hilbert matrix.
+        A_or_L = A if not lin_op else L
+
+        k, idx, proj = pymatrixid.interp_decomp(A_or_L, eps, rand=rand, rng=rng)
+        B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj)
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    @pytest.mark.parametrize(
+        "rand,lin_op",
+        [(False, False), (True, False), (True, True)])
+    def test_real_id_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng):
+        k = rank
+        A_or_L = A if not lin_op else L
+
+        idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng)
+        B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj)
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    @pytest.mark.parametrize("rand,lin_op", [(False, False)])
+    def test_real_id_skel_and_interp_matrices(
+            self, A, L, eps, rank, rand, lin_op, rng):
+        k = rank
+        A_or_L = A if not lin_op else L
+
+        idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng)
+        P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+        B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+        assert_allclose(B, A[:, idx[:k]], rtol=eps, atol=1e-08)
+        assert_allclose(B @ P, A, rtol=eps, atol=1e-08)
+
+    @pytest.mark.parametrize(
+        "rand,lin_op",
+        [(False, False), (True, False), (True, True)])
+    def test_svd_fixed_precision(self, A, L, eps, rand, lin_op, rng):
+        A_or_L = A if not lin_op else L
+
+        U, S, V = pymatrixid.svd(A_or_L, eps, rand=rand, rng=rng)
+        B = U * S @ V.T.conj()
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    @pytest.mark.parametrize(
+        "rand,lin_op",
+        [(False, False), (True, False), (True, True)])
+    def test_svd_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng):
+        k = rank
+        A_or_L = A if not lin_op else L
+
+        U, S, V = pymatrixid.svd(A_or_L, k, rand=rand, rng=rng)
+        B = U * S @ V.T.conj()
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    def test_id_to_svd(self, A, eps, rank):
+        k = rank
+
+        idx, proj = pymatrixid.interp_decomp(A, k, rand=False)
+        U, S, V = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj)
+        B = U * S @ V.T.conj()
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    def test_estimate_spectral_norm(self, A, rng):
+        s = svdvals(A)
+        norm_2_est = pymatrixid.estimate_spectral_norm(A, rng=rng)
+        assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
+
+    def test_estimate_spectral_norm_diff(self, A, rng):
+        B = A.copy()
+        B[:, 0] *= 1.2
+        s = svdvals(A - B)
+        norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B, rng=rng)
+        assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
+
+    def test_rank_estimates_array(self, A, rng):
+        B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
+
+        for M in [A, B]:
+            rank_tol = 1e-9
+            rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol)
+            rank_est = pymatrixid.estimate_rank(M, rank_tol, rng=rng)
+            assert_(rank_est >= rank_np)
+            assert_(rank_est <= rank_np + 10)
+
+    def test_rank_estimates_lin_op(self, A, rng):
+        B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
+
+        for M in [A, B]:
+            ML = aslinearoperator(M)
+            rank_tol = 1e-9
+            rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol)
+            rank_est = pymatrixid.estimate_rank(ML, rank_tol, rng=rng)
+            assert_(rank_est >= rank_np - 4)
+            assert_(rank_est <= rank_np + 4)
+
+    def test_badcall(self):
+        A = hilbert(5).astype(np.float32)
+        with assert_raises(ValueError):
+            pymatrixid.interp_decomp(A, 1e-6, rand=False)
+
+    def test_rank_too_large(self):
+        # svd(array, k) should not segfault
+        a = np.ones((4, 3))
+        with assert_raises(ValueError):
+            pymatrixid.svd(a, 4)
+
+    def test_full_rank(self):
+        eps = 1.0e-12
+
+        # fixed precision
+        A = np.random.rand(16, 8)
+        k, idx, proj = pymatrixid.interp_decomp(A, eps)
+        assert_equal(k, A.shape[1])
+
+        P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+        B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+        assert_allclose(A, B @ P)
+
+        # fixed rank
+        idx, proj = pymatrixid.interp_decomp(A, k)
+
+        P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+        B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+        assert_allclose(A, B @ P)
+
+    @pytest.mark.parametrize("dtype", [np.float64, np.complex128])
+    @pytest.mark.parametrize("rand", [True, False])
+    @pytest.mark.parametrize("eps", [1, 0.1])
+    def test_bug_9793(self, dtype, rand, eps):
+        A = np.array([[-1, -1, -1, 0, 0, 0],
+                      [0, 0, 0, 1, 1, 1],
+                      [1, 0, 0, 1, 0, 0],
+                      [0, 1, 0, 0, 1, 0],
+                      [0, 0, 1, 0, 0, 1]],
+                     dtype=dtype, order="C")
+        B = A.copy()
+        interp_decomp(A.T, eps, rand=rand)
+        assert_array_equal(A, B)
+
+    def test_svd_aslinearoperator_shape_check(self):
+        # See gh-issue #22451
+        rng = np.random.default_rng(1744580941832515)
+        x = rng.uniform(size=[7, 5])
+        xl = aslinearoperator(x)
+        u, s, v = pymatrixid.svd(xl, 3)
+        assert_equal(u.shape, (7, 3))
+        assert_equal(s.shape, (3,))
+        assert_equal(v.shape, (5, 3))
+
+        x = rng.uniform(size=[4, 9])
+        xl = aslinearoperator(x)
+        u, s, v = pymatrixid.svd(xl, 2)
+        assert_equal(u.shape, (4, 2))
+        assert_equal(s.shape, (2,))
+        assert_equal(v.shape, (9, 2))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..86555d6c19916c8ae1f6a796fb009a6b803b2159
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py
@@ -0,0 +1,3508 @@
+#
+# Created by: Pearu Peterson, September 2002
+#
+
+from functools import reduce
+import random
+
+from numpy.testing import (assert_equal, assert_array_almost_equal, assert_,
+                           assert_allclose, assert_almost_equal,
+                           assert_array_equal)
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from numpy import (eye, ones, zeros, zeros_like, triu, tril, tril_indices,
+                   triu_indices)
+
+from numpy.random import rand, randint, seed
+
+from scipy.linalg import (_flapack as flapack, lapack, inv, svd, cholesky,
+                          solve, ldl, norm, block_diag, qr, eigh, qz)
+
+from scipy.linalg.lapack import _compute_lwork
+from scipy.stats import ortho_group, unitary_group
+
+import scipy.sparse as sps
+try:
+    from scipy.__config__ import CONFIG
+except ImportError:
+    CONFIG = None
+
+try:
+    from scipy.linalg import _clapack as clapack
+except ImportError:
+    clapack = None
+from scipy.linalg.lapack import get_lapack_funcs
+from scipy.linalg.blas import get_blas_funcs
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+blas_provider = blas_version = None
+if CONFIG is not None:
+    blas_provider = CONFIG['Build Dependencies']['blas']['name']
+    blas_version = CONFIG['Build Dependencies']['blas']['version']
+
+
+def generate_random_dtype_array(shape, dtype, rng):
+    # generates a random matrix of desired data type of shape
+    if dtype in COMPLEX_DTYPES:
+        return (rng.rand(*shape)
+                + rng.rand(*shape)*1.0j).astype(dtype)
+    return rng.rand(*shape).astype(dtype)
+
+
+def test_lapack_documented():
+    """Test that all entries are in the doc."""
+    if lapack.__doc__ is None:  # just in case there is a python -OO
+        pytest.skip('lapack.__doc__ is None')
+    names = set(lapack.__doc__.split())
+    ignore_list = {
+        "absolute_import",
+        "clapack",
+        "division",
+        "find_best_lapack_type",
+        "flapack",
+        "print_function",
+        "HAS_ILP64",
+        "np",
+    }
+    missing = list()
+    for name in dir(lapack):
+        if (not name.startswith('_') and name not in ignore_list and
+                name not in names):
+            missing.append(name)
+    assert missing == [], 'Name(s) missing from lapack.__doc__ or ignore_list'
+
+
+class TestFlapackSimple:
+
+    def test_gebal(self):
+        a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+        a1 = [[1, 0, 0, 3e-4],
+              [4, 0, 0, 2e-3],
+              [7, 1, 0, 0],
+              [0, 1, 0, 0]]
+        for p in 'sdzc':
+            f = getattr(flapack, p+'gebal', None)
+            if f is None:
+                continue
+            ba, lo, hi, pivscale, info = f(a)
+            assert_(not info, repr(info))
+            assert_array_almost_equal(ba, a)
+            assert_equal((lo, hi), (0, len(a[0])-1))
+            assert_array_almost_equal(pivscale, np.ones(len(a)))
+
+            ba, lo, hi, pivscale, info = f(a1, permute=1, scale=1)
+            assert_(not info, repr(info))
+            # print(a1)
+            # print(ba, lo, hi, pivscale)
+
+    def test_gehrd(self):
+        a = [[-149, -50, -154],
+             [537, 180, 546],
+             [-27, -9, -25]]
+        for p in 'd':
+            f = getattr(flapack, p+'gehrd', None)
+            if f is None:
+                continue
+            ht, tau, info = f(a)
+            assert_(not info, repr(info))
+
+    def test_trsyl(self):
+        a = np.array([[1, 2], [0, 4]])
+        b = np.array([[5, 6], [0, 8]])
+        c = np.array([[9, 10], [11, 12]])
+        trans = 'T'
+
+        # Test single and double implementations, including most
+        # of the options
+        for dtype in 'fdFD':
+            a1, b1, c1 = a.astype(dtype), b.astype(dtype), c.astype(dtype)
+            trsyl, = get_lapack_funcs(('trsyl',), (a1,))
+            if dtype.isupper():  # is complex dtype
+                a1[0] += 1j
+                trans = 'C'
+
+            x, scale, info = trsyl(a1, b1, c1)
+            assert_array_almost_equal(np.dot(a1, x) + np.dot(x, b1),
+                                      scale * c1)
+
+            x, scale, info = trsyl(a1, b1, c1, trana=trans, tranb=trans)
+            assert_array_almost_equal(
+                    np.dot(a1.conjugate().T, x) + np.dot(x, b1.conjugate().T),
+                    scale * c1, decimal=4)
+
+            x, scale, info = trsyl(a1, b1, c1, isgn=-1)
+            assert_array_almost_equal(np.dot(a1, x) - np.dot(x, b1),
+                                      scale * c1, decimal=4)
+
+    def test_lange(self):
+        a = np.array([
+            [-149, -50, -154],
+            [537, 180, 546],
+            [-27, -9, -25]])
+
+        for dtype in 'fdFD':
+            for norm_str in 'Mm1OoIiFfEe':
+                a1 = a.astype(dtype)
+                if dtype.isupper():
+                    # is complex dtype
+                    a1[0, 0] += 1j
+
+                lange, = get_lapack_funcs(('lange',), (a1,))
+                value = lange(norm_str, a1)
+
+                if norm_str in 'FfEe':
+                    if dtype in 'Ff':
+                        decimal = 3
+                    else:
+                        decimal = 7
+                    ref = np.sqrt(np.sum(np.square(np.abs(a1))))
+                    assert_almost_equal(value, ref, decimal)
+                else:
+                    if norm_str in 'Mm':
+                        ref = np.max(np.abs(a1))
+                    elif norm_str in '1Oo':
+                        ref = np.max(np.sum(np.abs(a1), axis=0))
+                    elif norm_str in 'Ii':
+                        ref = np.max(np.sum(np.abs(a1), axis=1))
+
+                    assert_equal(value, ref)
+
+
+class TestLapack:
+
+    def test_flapack(self):
+        if hasattr(flapack, 'empty_module'):
+            # flapack module is empty
+            pass
+
+    def test_clapack(self):
+        if hasattr(clapack, 'empty_module'):
+            # clapack module is empty
+            pass
+
+
+class TestLeastSquaresSolvers:
+
+    def test_gels(self):
+        seed(1234)
+        # Test fat/tall matrix argument handling - gh-issue #8329
+        for ind, dtype in enumerate(DTYPES):
+            m = 10
+            n = 20
+            nrhs = 1
+            a1 = rand(m, n).astype(dtype)
+            b1 = rand(n).astype(dtype)
+            gls, glslw = get_lapack_funcs(('gels', 'gels_lwork'), dtype=dtype)
+
+            # Request of sizes
+            lwork = _compute_lwork(glslw, m, n, nrhs)
+            _, _, info = gls(a1, b1, lwork=lwork)
+            assert_(info >= 0)
+            _, _, info = gls(a1, b1, trans='TTCC'[ind], lwork=lwork)
+            assert_(info >= 0)
+
+        for dtype in REAL_DTYPES:
+            a1 = np.array([[1.0, 2.0],
+                           [4.0, 5.0],
+                           [7.0, 8.0]], dtype=dtype)
+            b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+            gels, gels_lwork, geqrf = get_lapack_funcs(
+                    ('gels', 'gels_lwork', 'geqrf'), (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            lwork = _compute_lwork(gels_lwork, m, n, nrhs)
+
+            lqr, x, info = gels(a1, b1, lwork=lwork)
+            assert_allclose(x[:-1], np.array([-14.333333333333323,
+                                              14.999999999999991],
+                                             dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+            lqr_truth, _, _, _ = geqrf(a1)
+            assert_array_equal(lqr, lqr_truth)
+
+        for dtype in COMPLEX_DTYPES:
+            a1 = np.array([[1.0+4.0j, 2.0],
+                           [4.0+0.5j, 5.0-3.0j],
+                           [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+            b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+            gels, gels_lwork, geqrf = get_lapack_funcs(
+                    ('gels', 'gels_lwork', 'geqrf'), (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            lwork = _compute_lwork(gels_lwork, m, n, nrhs)
+
+            lqr, x, info = gels(a1, b1, lwork=lwork)
+            assert_allclose(x[:-1],
+                            np.array([1.161753632288328-1.901075709391912j,
+                                      1.735882340522193+1.521240901196909j],
+                                     dtype=dtype), rtol=25*np.finfo(dtype).eps)
+            lqr_truth, _, _, _ = geqrf(a1)
+            assert_array_equal(lqr, lqr_truth)
+
+    def test_gelsd(self):
+        for dtype in REAL_DTYPES:
+            a1 = np.array([[1.0, 2.0],
+                           [4.0, 5.0],
+                           [7.0, 8.0]], dtype=dtype)
+            b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+            gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, iwork, info = gelsd_lwork(m, n, nrhs, -1)
+            lwork = int(np.real(work))
+            iwork_size = iwork
+
+            x, s, rank, info = gelsd(a1, b1, lwork, iwork_size,
+                                     -1, False, False)
+            assert_allclose(x[:-1], np.array([-14.333333333333323,
+                                              14.999999999999991],
+                                             dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+            assert_allclose(s, np.array([12.596017180511966,
+                                         0.583396253199685], dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+        for dtype in COMPLEX_DTYPES:
+            a1 = np.array([[1.0+4.0j, 2.0],
+                           [4.0+0.5j, 5.0-3.0j],
+                           [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+            b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+            gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, rwork, iwork, info = gelsd_lwork(m, n, nrhs, -1)
+            lwork = int(np.real(work))
+            rwork_size = int(rwork)
+            iwork_size = iwork
+
+            x, s, rank, info = gelsd(a1, b1, lwork, rwork_size, iwork_size,
+                                     -1, False, False)
+            assert_allclose(x[:-1],
+                            np.array([1.161753632288328-1.901075709391912j,
+                                      1.735882340522193+1.521240901196909j],
+                                     dtype=dtype), rtol=25*np.finfo(dtype).eps)
+            assert_allclose(s,
+                            np.array([13.035514762572043, 4.337666985231382],
+                                     dtype=dtype), rtol=25*np.finfo(dtype).eps)
+
+    def test_gelss(self):
+
+        for dtype in REAL_DTYPES:
+            a1 = np.array([[1.0, 2.0],
+                           [4.0, 5.0],
+                           [7.0, 8.0]], dtype=dtype)
+            b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+            gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, info = gelss_lwork(m, n, nrhs, -1)
+            lwork = int(np.real(work))
+
+            v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False)
+            assert_allclose(x[:-1], np.array([-14.333333333333323,
+                                              14.999999999999991],
+                                             dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+            assert_allclose(s, np.array([12.596017180511966,
+                                         0.583396253199685], dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+        for dtype in COMPLEX_DTYPES:
+            a1 = np.array([[1.0+4.0j, 2.0],
+                           [4.0+0.5j, 5.0-3.0j],
+                           [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+            b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+            gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, info = gelss_lwork(m, n, nrhs, -1)
+            lwork = int(np.real(work))
+
+            v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False)
+            assert_allclose(x[:-1],
+                            np.array([1.161753632288328-1.901075709391912j,
+                                      1.735882340522193+1.521240901196909j],
+                                     dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+            assert_allclose(s, np.array([13.035514762572043,
+                                         4.337666985231382], dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+    def test_gelsy(self):
+
+        for dtype in REAL_DTYPES:
+            a1 = np.array([[1.0, 2.0],
+                           [4.0, 5.0],
+                           [7.0, 8.0]], dtype=dtype)
+            b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+            gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps)
+            lwork = int(np.real(work))
+
+            jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+            v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps,
+                                        lwork, False, False)
+            assert_allclose(x[:-1], np.array([-14.333333333333323,
+                                              14.999999999999991],
+                                             dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+        for dtype in COMPLEX_DTYPES:
+            a1 = np.array([[1.0+4.0j, 2.0],
+                           [4.0+0.5j, 5.0-3.0j],
+                           [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+            b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+            gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps)
+            lwork = int(np.real(work))
+
+            jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+            v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps,
+                                        lwork, False, False)
+            assert_allclose(x[:-1],
+                            np.array([1.161753632288328-1.901075709391912j,
+                                      1.735882340522193+1.521240901196909j],
+                                     dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('shape', [(3, 4), (5, 2), (2**18, 2**18)])
+def test_geqrf_lwork(dtype, shape):
+    geqrf_lwork = get_lapack_funcs(('geqrf_lwork'), dtype=dtype)
+    m, n = shape
+    lwork, info = geqrf_lwork(m=m, n=n)
+    assert_equal(info, 0)
+
+
+class TestRegression:
+
+    def test_ticket_1645(self):
+        # Check that RQ routines have correct lwork
+        for dtype in DTYPES:
+            a = np.zeros((300, 2), dtype=dtype)
+
+            gerqf, = get_lapack_funcs(['gerqf'], [a])
+            assert_raises(Exception, gerqf, a, lwork=2)
+            rq, tau, work, info = gerqf(a)
+
+            if dtype in REAL_DTYPES:
+                orgrq, = get_lapack_funcs(['orgrq'], [a])
+                assert_raises(Exception, orgrq, rq[-2:], tau, lwork=1)
+                orgrq(rq[-2:], tau, lwork=2)
+            elif dtype in COMPLEX_DTYPES:
+                ungrq, = get_lapack_funcs(['ungrq'], [a])
+                assert_raises(Exception, ungrq, rq[-2:], tau, lwork=1)
+                ungrq(rq[-2:], tau, lwork=2)
+
+
+class TestDpotr:
+    def test_gh_2691(self):
+        # 'lower' argument of dportf/dpotri
+        for lower in [True, False]:
+            for clean in [True, False]:
+                np.random.seed(42)
+                x = np.random.normal(size=(3, 3))
+                a = x.dot(x.T)
+
+                dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, ))
+
+                c, info = dpotrf(a, lower, clean=clean)
+                dpt = dpotri(c, lower)[0]
+
+                if lower:
+                    assert_allclose(np.tril(dpt), np.tril(inv(a)))
+                else:
+                    assert_allclose(np.triu(dpt), np.triu(inv(a)))
+
+
+class TestDlasd4:
+    def test_sing_val_update(self):
+
+        sigmas = np.array([4., 3., 2., 0])
+        m_vec = np.array([3.12, 5.7, -4.8, -2.2])
+
+        M = np.hstack((np.vstack((np.diag(sigmas[0:-1]),
+                                  np.zeros((1, len(m_vec) - 1)))),
+                       m_vec[:, np.newaxis]))
+        SM = svd(M, full_matrices=False, compute_uv=False, overwrite_a=False,
+                 check_finite=False)
+
+        it_len = len(sigmas)
+        sgm = np.concatenate((sigmas[::-1], [sigmas[0] + it_len*norm(m_vec)]))
+        mvc = np.concatenate((m_vec[::-1], (0,)))
+
+        lasd4 = get_lapack_funcs('lasd4', (sigmas,))
+
+        roots = []
+        for i in range(0, it_len):
+            res = lasd4(i, sgm, mvc)
+            roots.append(res[1])
+
+            assert_((res[3] <= 0), "LAPACK root finding dlasd4 failed to find \
+                                    the singular value %i" % i)
+        roots = np.array(roots)[::-1]
+
+        assert_((not np.any(np.isnan(roots)), "There are NaN roots"))
+        assert_allclose(SM, roots, atol=100*np.finfo(np.float64).eps,
+                        rtol=100*np.finfo(np.float64).eps)
+
+
+class TestTbtrs:
+
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_nag_example_f07vef_f07vsf(self, dtype):
+        """Test real (f07vef) and complex (f07vsf) examples from NAG
+
+        Examples available from:
+        * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vef.html
+        * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vsf.html
+
+        """
+        if dtype in REAL_DTYPES:
+            ab = np.array([[-4.16, 4.78, 6.32, 0.16],
+                           [-2.25, 5.86, -4.82, 0]],
+                          dtype=dtype)
+            b = np.array([[-16.64, -4.16],
+                          [-13.78, -16.59],
+                          [13.10, -4.94],
+                          [-14.14, -9.96]],
+                         dtype=dtype)
+            x_out = np.array([[4, 1],
+                              [-1, -3],
+                              [3, 2],
+                              [2, -2]],
+                             dtype=dtype)
+        elif dtype in COMPLEX_DTYPES:
+            ab = np.array([[-1.94+4.43j, 4.12-4.27j, 0.43-2.66j, 0.44+0.1j],
+                           [-3.39+3.44j, -1.84+5.52j, 1.74 - 0.04j, 0],
+                           [1.62+3.68j, -2.77-1.93j, 0, 0]],
+                          dtype=dtype)
+            b = np.array([[-8.86 - 3.88j, -24.09 - 5.27j],
+                          [-15.57 - 23.41j, -57.97 + 8.14j],
+                          [-7.63 + 22.78j, 19.09 - 29.51j],
+                          [-14.74 - 2.40j, 19.17 + 21.33j]],
+                         dtype=dtype)
+            x_out = np.array([[2j, 1 + 5j],
+                              [1 - 3j, -7 - 2j],
+                              [-4.001887 - 4.988417j, 3.026830 + 4.003182j],
+                              [1.996158 - 1.045105j, -6.103357 - 8.986653j]],
+                             dtype=dtype)
+        else:
+            raise ValueError(f"Datatype {dtype} not understood.")
+
+        tbtrs = get_lapack_funcs(('tbtrs'), dtype=dtype)
+        x, info = tbtrs(ab=ab, b=b, uplo='L')
+        assert_equal(info, 0)
+        assert_allclose(x, x_out, rtol=0, atol=1e-5)
+
+    @pytest.mark.parametrize('dtype,trans',
+                             [(dtype, trans)
+                              for dtype in DTYPES for trans in ['N', 'T', 'C']
+                              if not (trans == 'C' and dtype in REAL_DTYPES)])
+    @pytest.mark.parametrize('uplo', ['U', 'L'])
+    @pytest.mark.parametrize('diag', ['N', 'U'])
+    def test_random_matrices(self, dtype, trans, uplo, diag):
+        rng = np.random.RandomState(1724)
+
+        # n, nrhs, kd are used to specify A and b.
+        # A is of shape n x n with kd super/sub-diagonals
+        # b is of shape n x nrhs matrix
+        n, nrhs, kd = 4, 3, 2
+        tbtrs = get_lapack_funcs('tbtrs', dtype=dtype)
+
+        is_upper = (uplo == 'U')
+        ku = kd * is_upper
+        kl = kd - ku
+
+        # Construct the diagonal and kd super/sub diagonals of A with
+        # the corresponding offsets.
+        band_offsets = range(ku, -kl - 1, -1)
+        band_widths = [n - abs(x) for x in band_offsets]
+        bands = [generate_random_dtype_array((width,), dtype, rng)
+                 for width in band_widths]
+
+        if diag == 'U':  # A must be unit triangular
+            bands[ku] = np.ones(n, dtype=dtype)
+
+        # Construct the diagonal banded matrix A from the bands and offsets.
+        a = sps.diags(bands, band_offsets, format='dia')
+
+        # Convert A into banded storage form
+        ab = np.zeros((kd + 1, n), dtype)
+        for row, k in enumerate(band_offsets):
+            ab[row, max(k, 0):min(n+k, n)] = a.diagonal(k)
+
+        # The RHS values.
+        b = generate_random_dtype_array((n, nrhs), dtype, rng)
+
+        x, info = tbtrs(ab=ab, b=b, uplo=uplo, trans=trans, diag=diag)
+        assert_equal(info, 0)
+
+        if trans == 'N':
+            assert_allclose(a @ x, b, rtol=5e-5)
+        elif trans == 'T':
+            assert_allclose(a.T @ x, b, rtol=5e-5)
+        elif trans == 'C':
+            assert_allclose(a.T.conjugate() @ x, b, rtol=5e-5)
+        else:
+            raise ValueError('Invalid trans argument')
+
+    @pytest.mark.parametrize('uplo,trans,diag',
+                             [['U', 'N', 'Invalid'],
+                              ['U', 'Invalid', 'N'],
+                              ['Invalid', 'N', 'N']])
+    def test_invalid_argument_raises_exception(self, uplo, trans, diag):
+        """Test if invalid values of uplo, trans and diag raise exceptions"""
+        # Argument checks occur independently of used datatype.
+        # This mean we must not parameterize all available datatypes.
+        tbtrs = get_lapack_funcs('tbtrs', dtype=np.float64)
+        ab = rand(4, 2)
+        b = rand(2, 4)
+        assert_raises(Exception, tbtrs, ab, b, uplo, trans, diag)
+
+    def test_zero_element_in_diagonal(self):
+        """Test if a matrix with a zero diagonal element is singular
+
+        If the i-th diagonal of A is zero, ?tbtrs should return `i` in `info`
+        indicating the provided matrix is singular.
+
+        Note that ?tbtrs requires the matrix A to be stored in banded form.
+        In this form the diagonal corresponds to the last row."""
+        ab = np.ones((3, 4), dtype=float)
+        b = np.ones(4, dtype=float)
+        tbtrs = get_lapack_funcs('tbtrs', dtype=float)
+
+        ab[-1, 3] = 0
+        _, info = tbtrs(ab=ab, b=b, uplo='U')
+        assert_equal(info, 4)
+
+    @pytest.mark.parametrize('ldab,n,ldb,nrhs', [
+                              (5, 5, 0, 5),
+                              (5, 5, 3, 5)
+    ])
+    def test_invalid_matrix_shapes(self, ldab, n, ldb, nrhs):
+        """Test ?tbtrs fails correctly if shapes are invalid."""
+        ab = np.ones((ldab, n), dtype=float)
+        b = np.ones((ldb, nrhs), dtype=float)
+        tbtrs = get_lapack_funcs('tbtrs', dtype=float)
+        assert_raises(Exception, tbtrs, ab, b)
+
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('norm', ['I', '1', 'O'])
+@pytest.mark.parametrize('uplo', ['U', 'L'])
+@pytest.mark.parametrize('diag', ['N', 'U'])
+@pytest.mark.parametrize('n', [3, 10])
+def test_trcon(dtype, norm, uplo, diag, n):
+    # Simple way to get deterministic (unlike `hash`) integer seed based on arguments
+    random.seed(f"{dtype}{norm}{uplo}{diag}{n}")
+    rng = np.random.default_rng(random.randint(0, 9999999999999))
+
+    A = rng.random(size=(n, n)) + rng.random(size=(n, n))*1j
+    # make the condition numbers more interesting
+    offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n))
+    A += offset
+    A = A.real if np.issubdtype(dtype, np.floating) else A
+    A = np.triu(A) if uplo == 'U' else np.tril(A)
+    if diag == 'U':
+        A /= np.diag(A)[:, np.newaxis]
+    A = A.astype(dtype)
+
+    trcon = get_lapack_funcs('trcon', (A,))
+    res, _ = trcon(A, norm=norm, uplo=uplo, diag=diag)
+
+    if norm == 'I':
+        norm_A = np.linalg.norm(A, ord=np.inf)
+        norm_inv_A = np.linalg.norm(np.linalg.inv(A), ord=np.inf)
+        ref = 1 / (norm_A * norm_inv_A)
+    else:
+        anorm = np.abs(A).sum(axis=0).max()
+        gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
+        lu, ipvt, info = getrf(A)
+        ref, _ = gecon(lu, anorm, norm=norm)
+
+    # This is an estimate of reciprocal condition number; we just need order of
+    # magnitude. In testing, we observed that much smaller rtol is OK in almost
+    # all cases... but sometimes it isn't.
+    rtol = 1  # np.finfo(dtype).eps**0.75
+    assert_allclose(res, ref, rtol=rtol)
+
+
+def test_lartg():
+    for dtype in 'fdFD':
+        lartg = get_lapack_funcs('lartg', dtype=dtype)
+
+        f = np.array(3, dtype)
+        g = np.array(4, dtype)
+
+        if np.iscomplexobj(g):
+            g *= 1j
+
+        cs, sn, r = lartg(f, g)
+
+        assert_allclose(cs, 3.0/5.0)
+        assert_allclose(r, 5.0)
+
+        if np.iscomplexobj(g):
+            assert_allclose(sn, -4.0j/5.0)
+            assert_(isinstance(r, complex))
+            assert_(isinstance(cs, float))
+        else:
+            assert_allclose(sn, 4.0/5.0)
+
+
+def test_rot():
+    # srot, drot from blas and crot and zrot from lapack.
+
+    for dtype in 'fdFD':
+        c = 0.6
+        s = 0.8
+
+        u = np.full(4, 3, dtype)
+        v = np.full(4, 4, dtype)
+        atol = 10**-(np.finfo(dtype).precision-1)
+
+        if dtype in 'fd':
+            rot = get_blas_funcs('rot', dtype=dtype)
+            f = 4
+        else:
+            rot = get_lapack_funcs('rot', dtype=dtype)
+            s *= -1j
+            v *= 1j
+            f = 4j
+
+        assert_allclose(rot(u, v, c, s), [[5, 5, 5, 5],
+                                          [0, 0, 0, 0]], atol=atol)
+        assert_allclose(rot(u, v, c, s, n=2), [[5, 5, 3, 3],
+                                               [0, 0, f, f]], atol=atol)
+        assert_allclose(rot(u, v, c, s, offx=2, offy=2),
+                        [[3, 3, 5, 5], [f, f, 0, 0]], atol=atol)
+        assert_allclose(rot(u, v, c, s, incx=2, offy=2, n=2),
+                        [[5, 3, 5, 3], [f, f, 0, 0]], atol=atol)
+        assert_allclose(rot(u, v, c, s, offx=2, incy=2, n=2),
+                        [[3, 3, 5, 5], [0, f, 0, f]], atol=atol)
+        assert_allclose(rot(u, v, c, s, offx=2, incx=2, offy=2, incy=2, n=1),
+                        [[3, 3, 5, 3], [f, f, 0, f]], atol=atol)
+        assert_allclose(rot(u, v, c, s, incx=-2, incy=-2, n=2),
+                        [[5, 3, 5, 3], [0, f, 0, f]], atol=atol)
+
+        a, b = rot(u, v, c, s, overwrite_x=1, overwrite_y=1)
+        assert_(a is u)
+        assert_(b is v)
+        assert_allclose(a, [5, 5, 5, 5], atol=atol)
+        assert_allclose(b, [0, 0, 0, 0], atol=atol)
+
+
+def test_larfg_larf():
+    np.random.seed(1234)
+    a0 = np.random.random((4, 4))
+    a0 = a0.T.dot(a0)
+
+    a0j = np.random.random((4, 4)) + 1j*np.random.random((4, 4))
+    a0j = a0j.T.conj().dot(a0j)
+
+    # our test here will be to do one step of reducing a hermetian matrix to
+    # tridiagonal form using householder transforms.
+
+    for dtype in 'fdFD':
+        larfg, larf = get_lapack_funcs(['larfg', 'larf'], dtype=dtype)
+
+        if dtype in 'FD':
+            a = a0j.copy()
+        else:
+            a = a0.copy()
+
+        # generate a householder transform to clear a[2:,0]
+        alpha, x, tau = larfg(a.shape[0]-1, a[1, 0], a[2:, 0])
+
+        # create expected output
+        expected = np.zeros_like(a[:, 0])
+        expected[0] = a[0, 0]
+        expected[1] = alpha
+
+        # assemble householder vector
+        v = np.zeros_like(a[1:, 0])
+        v[0] = 1.0
+        v[1:] = x
+
+        # apply transform from the left
+        a[1:, :] = larf(v, tau.conjugate(), a[1:, :], np.zeros(a.shape[1]))
+
+        # apply transform from the right
+        a[:, 1:] = larf(v, tau, a[:, 1:], np.zeros(a.shape[0]), side='R')
+
+        assert_allclose(a[:, 0], expected, atol=1e-5)
+        assert_allclose(a[0, :], expected, atol=1e-5)
+
+
+def test_sgesdd_lwork_bug_workaround():
+    # Test that SGESDD lwork is sufficiently large for LAPACK.
+    #
+    # This checks that _compute_lwork() correctly works around a bug in
+    # LAPACK versions older than 3.10.1.
+
+    sgesdd_lwork = get_lapack_funcs('gesdd_lwork', dtype=np.float32,
+                                    ilp64='preferred')
+    n = 9537
+    lwork = _compute_lwork(sgesdd_lwork, n, n,
+                           compute_uv=True, full_matrices=True)
+    # If we called the Fortran function SGESDD directly with IWORK=-1, the
+    # LAPACK bug would result in lwork being 272929856, which was too small.
+    # (The result was returned in a single precision float, which does not
+    # have sufficient precision to represent the exact integer value that it
+    # computed internally.)  The work-around implemented in _compute_lwork()
+    # will convert that to 272929888.  If we are using LAPACK 3.10.1 or later
+    # (such as in OpenBLAS 0.3.21 or later), the work-around will return
+    # 272929920, because it does not know which version of LAPACK is being
+    # used, so it always applies the correction to whatever it is given.  We
+    # will accept either 272929888 or 272929920.
+    # Note that the acceptable values are a LAPACK implementation detail.
+    # If a future version of LAPACK changes how SGESDD works, and therefore
+    # changes the required LWORK size, the acceptable values might have to
+    # be updated.
+    assert lwork == 272929888 or lwork == 272929920
+
+
+class TestSytrd:
+    @pytest.mark.parametrize('dtype', REAL_DTYPES)
+    def test_sytrd_with_zero_dim_array(self, dtype):
+        # Assert that a 0x0 matrix raises an error
+        A = np.zeros((0, 0), dtype=dtype)
+        sytrd = get_lapack_funcs('sytrd', (A,))
+        assert_raises(ValueError, sytrd, A)
+
+    @pytest.mark.parametrize('dtype', REAL_DTYPES)
+    @pytest.mark.parametrize('n', (1, 3))
+    def test_sytrd(self, dtype, n):
+        A = np.zeros((n, n), dtype=dtype)
+
+        sytrd, sytrd_lwork = \
+            get_lapack_funcs(('sytrd', 'sytrd_lwork'), (A,))
+
+        # some upper triangular array
+        A[np.triu_indices_from(A)] = \
+            np.arange(1, n*(n+1)//2+1, dtype=dtype)
+
+        # query lwork
+        lwork, info = sytrd_lwork(n)
+        assert_equal(info, 0)
+
+        # check lower=1 behavior (shouldn't do much since the matrix is
+        # upper triangular)
+        data, d, e, tau, info = sytrd(A, lower=1, lwork=lwork)
+        assert_equal(info, 0)
+
+        assert_allclose(data, A, atol=5*np.finfo(dtype).eps, rtol=1.0)
+        assert_allclose(d, np.diag(A))
+        assert_allclose(e, 0.0)
+        assert_allclose(tau, 0.0)
+
+        # and now for the proper test (lower=0 is the default)
+        data, d, e, tau, info = sytrd(A, lwork=lwork)
+        assert_equal(info, 0)
+
+        # assert Q^T*A*Q = tridiag(e, d, e)
+
+        # build tridiagonal matrix
+        T = np.zeros_like(A, dtype=dtype)
+        k = np.arange(A.shape[0])
+        T[k, k] = d
+        k2 = np.arange(A.shape[0]-1)
+        T[k2+1, k2] = e
+        T[k2, k2+1] = e
+
+        # build Q
+        Q = np.eye(n, n, dtype=dtype)
+        for i in range(n-1):
+            v = np.zeros(n, dtype=dtype)
+            v[:i] = data[:i, i+1]
+            v[i] = 1.0
+            H = np.eye(n, n, dtype=dtype) - tau[i] * np.outer(v, v)
+            Q = np.dot(H, Q)
+
+        # Make matrix fully symmetric
+        i_lower = np.tril_indices(n, -1)
+        A[i_lower] = A.T[i_lower]
+
+        QTAQ = np.dot(Q.T, np.dot(A, Q))
+
+        # disable rtol here since some values in QTAQ and T are very close
+        # to 0.
+        assert_allclose(QTAQ, T, atol=5*np.finfo(dtype).eps, rtol=1.0)
+
+
+class TestHetrd:
+    @pytest.mark.parametrize('complex_dtype', COMPLEX_DTYPES)
+    def test_hetrd_with_zero_dim_array(self, complex_dtype):
+        # Assert that a 0x0 matrix raises an error
+        A = np.zeros((0, 0), dtype=complex_dtype)
+        hetrd = get_lapack_funcs('hetrd', (A,))
+        assert_raises(ValueError, hetrd, A)
+
+    @pytest.mark.parametrize('real_dtype,complex_dtype',
+                             zip(REAL_DTYPES, COMPLEX_DTYPES))
+    @pytest.mark.parametrize('n', (1, 3))
+    def test_hetrd(self, n, real_dtype, complex_dtype):
+        A = np.zeros((n, n), dtype=complex_dtype)
+        hetrd, hetrd_lwork = \
+            get_lapack_funcs(('hetrd', 'hetrd_lwork'), (A,))
+
+        # some upper triangular array
+        A[np.triu_indices_from(A)] = (
+            np.arange(1, n*(n+1)//2+1, dtype=real_dtype)
+            + 1j * np.arange(1, n*(n+1)//2+1, dtype=real_dtype)
+            )
+        np.fill_diagonal(A, np.real(np.diag(A)))
+
+        # test query lwork
+        for x in [0, 1]:
+            _, info = hetrd_lwork(n, lower=x)
+            assert_equal(info, 0)
+        # lwork returns complex which segfaults hetrd call (gh-10388)
+        # use the safe and recommended option
+        lwork = _compute_lwork(hetrd_lwork, n)
+
+        # check lower=1 behavior (shouldn't do much since the matrix is
+        # upper triangular)
+        data, d, e, tau, info = hetrd(A, lower=1, lwork=lwork)
+        assert_equal(info, 0)
+
+        assert_allclose(data, A, atol=5*np.finfo(real_dtype).eps, rtol=1.0)
+
+        assert_allclose(d, np.real(np.diag(A)))
+        assert_allclose(e, 0.0)
+        assert_allclose(tau, 0.0)
+
+        # and now for the proper test (lower=0 is the default)
+        data, d, e, tau, info = hetrd(A, lwork=lwork)
+        assert_equal(info, 0)
+
+        # assert Q^T*A*Q = tridiag(e, d, e)
+
+        # build tridiagonal matrix
+        T = np.zeros_like(A, dtype=real_dtype)
+        k = np.arange(A.shape[0], dtype=int)
+        T[k, k] = d
+        k2 = np.arange(A.shape[0]-1, dtype=int)
+        T[k2+1, k2] = e
+        T[k2, k2+1] = e
+
+        # build Q
+        Q = np.eye(n, n, dtype=complex_dtype)
+        for i in range(n-1):
+            v = np.zeros(n, dtype=complex_dtype)
+            v[:i] = data[:i, i+1]
+            v[i] = 1.0
+            H = np.eye(n, n, dtype=complex_dtype) \
+                - tau[i] * np.outer(v, np.conj(v))
+            Q = np.dot(H, Q)
+
+        # Make matrix fully Hermitian
+        i_lower = np.tril_indices(n, -1)
+        A[i_lower] = np.conj(A.T[i_lower])
+
+        QHAQ = np.dot(np.conj(Q.T), np.dot(A, Q))
+
+        # disable rtol here since some values in QTAQ and T are very close
+        # to 0.
+        assert_allclose(
+            QHAQ, T, atol=10*np.finfo(real_dtype).eps, rtol=1.0
+            )
+
+
+def test_gglse():
+    # Example data taken from NAG manual
+    for ind, dtype in enumerate(DTYPES):
+        # DTYPES =  gglse
+        func, func_lwork = get_lapack_funcs(('gglse', 'gglse_lwork'),
+                                            dtype=dtype)
+        lwork = _compute_lwork(func_lwork, m=6, n=4, p=2)
+        # For gglse
+        if ind < 2:
+            a = np.array([[-0.57, -1.28, -0.39, 0.25],
+                          [-1.93, 1.08, -0.31, -2.14],
+                          [2.30, 0.24, 0.40, -0.35],
+                          [-1.93, 0.64, -0.66, 0.08],
+                          [0.15, 0.30, 0.15, -2.13],
+                          [-0.02, 1.03, -1.43, 0.50]], dtype=dtype)
+            c = np.array([-1.50, -2.14, 1.23, -0.54, -1.68, 0.82], dtype=dtype)
+            d = np.array([0., 0.], dtype=dtype)
+        # For gglse
+        else:
+            a = np.array([[0.96-0.81j, -0.03+0.96j, -0.91+2.06j, -0.05+0.41j],
+                          [-0.98+1.98j, -1.20+0.19j, -0.66+0.42j, -0.81+0.56j],
+                          [0.62-0.46j, 1.01+0.02j, 0.63-0.17j, -1.11+0.60j],
+                          [0.37+0.38j, 0.19-0.54j, -0.98-0.36j, 0.22-0.20j],
+                          [0.83+0.51j, 0.20+0.01j, -0.17-0.46j, 1.47+1.59j],
+                          [1.08-0.28j, 0.20-0.12j, -0.07+1.23j, 0.26+0.26j]])
+            c = np.array([[-2.54+0.09j],
+                          [1.65-2.26j],
+                          [-2.11-3.96j],
+                          [1.82+3.30j],
+                          [-6.41+3.77j],
+                          [2.07+0.66j]])
+            d = np.zeros(2, dtype=dtype)
+
+        b = np.array([[1., 0., -1., 0.], [0., 1., 0., -1.]], dtype=dtype)
+
+        _, _, _, result, _ = func(a, b, c, d, lwork=lwork)
+        if ind < 2:
+            expected = np.array([0.48904455,
+                                 0.99754786,
+                                 0.48904455,
+                                 0.99754786])
+        else:
+            expected = np.array([1.08742917-1.96205783j,
+                                 -0.74093902+3.72973919j,
+                                 1.08742917-1.96205759j,
+                                 -0.74093896+3.72973895j])
+        assert_array_almost_equal(result, expected, decimal=4)
+
+
+def test_sycon_hecon():
+    seed(1234)
+    for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+        # DTYPES + COMPLEX DTYPES =  sycon + hecon
+        n = 10
+        # For sycon
+        if ind < 4:
+            func_lwork = get_lapack_funcs('sytrf_lwork', dtype=dtype)
+            funcon, functrf = get_lapack_funcs(('sycon', 'sytrf'), dtype=dtype)
+            A = (rand(n, n)).astype(dtype)
+        # For hecon
+        else:
+            func_lwork = get_lapack_funcs('hetrf_lwork', dtype=dtype)
+            funcon, functrf = get_lapack_funcs(('hecon', 'hetrf'), dtype=dtype)
+            A = (rand(n, n) + rand(n, n)*1j).astype(dtype)
+
+        # Since sycon only refers to upper/lower part, conj() is safe here.
+        A = (A + A.conj().T)/2 + 2*np.eye(n, dtype=dtype)
+
+        anorm = norm(A, 1)
+        lwork = _compute_lwork(func_lwork, n)
+        ldu, ipiv, _ = functrf(A, lwork=lwork, lower=1)
+        rcond, _ = funcon(a=ldu, ipiv=ipiv, anorm=anorm, lower=1)
+        # The error is at most 1-fold
+        assert_(abs(1/rcond - np.linalg.cond(A, p=1))*rcond < 1)
+
+
+def test_sygst():
+    seed(1234)
+    for ind, dtype in enumerate(REAL_DTYPES):
+        # DTYPES =  sygst
+        n = 10
+
+        potrf, sygst, syevd, sygvd = get_lapack_funcs(('potrf', 'sygst',
+                                                       'syevd', 'sygvd'),
+                                                      dtype=dtype)
+
+        A = rand(n, n).astype(dtype)
+        A = (A + A.T)/2
+        # B must be positive definite
+        B = rand(n, n).astype(dtype)
+        B = (B + B.T)/2 + 2 * np.eye(n, dtype=dtype)
+
+        # Perform eig (sygvd)
+        eig_gvd, _, info = sygvd(A, B)
+        assert_(info == 0)
+
+        # Convert to std problem potrf
+        b, info = potrf(B)
+        assert_(info == 0)
+        a, info = sygst(A, b)
+        assert_(info == 0)
+
+        eig, _, info = syevd(a)
+        assert_(info == 0)
+        assert_allclose(eig, eig_gvd, rtol=1.2e-4)
+
+
+def test_hegst():
+    seed(1234)
+    for ind, dtype in enumerate(COMPLEX_DTYPES):
+        # DTYPES =  hegst
+        n = 10
+
+        potrf, hegst, heevd, hegvd = get_lapack_funcs(('potrf', 'hegst',
+                                                       'heevd', 'hegvd'),
+                                                      dtype=dtype)
+
+        A = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype)
+        A = (A + A.conj().T)/2
+        # B must be positive definite
+        B = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype)
+        B = (B + B.conj().T)/2 + 2 * np.eye(n, dtype=dtype)
+
+        # Perform eig (hegvd)
+        eig_gvd, _, info = hegvd(A, B)
+        assert_(info == 0)
+
+        # Convert to std problem potrf
+        b, info = potrf(B)
+        assert_(info == 0)
+        a, info = hegst(A, b)
+        assert_(info == 0)
+
+        eig, _, info = heevd(a)
+        assert_(info == 0)
+        assert_allclose(eig, eig_gvd, rtol=1e-4)
+
+
+def test_tzrzf():
+    """
+    This test performs an RZ decomposition in which an m x n upper trapezoidal
+    array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular
+    and Z is unitary.
+    """
+    rng = np.random.RandomState(1234)
+    m, n = 10, 15
+    for ind, dtype in enumerate(DTYPES):
+        tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
+                                           dtype=dtype)
+        lwork = _compute_lwork(tzrzf_lw, m, n)
+
+        if ind < 2:
+            A = triu(rng.rand(m, n).astype(dtype))
+        else:
+            A = triu((rng.rand(m, n) + rng.rand(m, n)*1j).astype(dtype))
+
+        # assert wrong shape arg, f2py returns generic error
+        assert_raises(Exception, tzrzf, A.T)
+        rz, tau, info = tzrzf(A, lwork=lwork)
+        # Check success
+        assert_(info == 0)
+
+        # Get Z manually for comparison
+        R = np.hstack((rz[:, :m], np.zeros((m, n-m), dtype=dtype)))
+        V = np.hstack((np.eye(m, dtype=dtype), rz[:, m:]))
+        Id = np.eye(n, dtype=dtype)
+        ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(m)]
+        Z = reduce(np.dot, ref)
+        assert_allclose(R.dot(Z) - A, zeros_like(A, dtype=dtype),
+                        atol=10*np.spacing(dtype(1.0).real), rtol=0.)
+
+
+def test_tfsm():
+    """
+    Test for solving a linear system with the coefficient matrix is a
+    triangular array stored in Full Packed (RFP) format.
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = triu(rng.rand(n, n) + rng.rand(n, n)*1j + eye(n)).astype(dtype)
+            trans = 'C'
+        else:
+            A = triu(rng.rand(n, n) + eye(n)).astype(dtype)
+            trans = 'T'
+
+        trttf, tfttr, tfsm = get_lapack_funcs(('trttf', 'tfttr', 'tfsm'),
+                                              dtype=dtype)
+
+        Afp, _ = trttf(A)
+        B = rng.rand(n, 2).astype(dtype)
+        soln = tfsm(-1, Afp, B)
+        assert_array_almost_equal(soln, solve(-A, B),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+        soln = tfsm(-1, Afp, B, trans=trans)
+        assert_array_almost_equal(soln, solve(-A.conj().T, B),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+        # Make A, unit diagonal
+        A[np.arange(n), np.arange(n)] = dtype(1.)
+        soln = tfsm(-1, Afp, B, trans=trans, diag='U')
+        assert_array_almost_equal(soln, solve(-A.conj().T, B),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+        # Change side
+        B2 = rng.rand(3, n).astype(dtype)
+        soln = tfsm(-1, Afp, B2, trans=trans, diag='U', side='R')
+        assert_array_almost_equal(soln, solve(-A, B2.T).conj().T,
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_ormrz_unmrz():
+    """
+    This test performs a matrix multiplication with an arbitrary m x n matrix C
+    and a unitary matrix Q without explicitly forming the array. The array data
+    is encoded in the rectangular part of A which is obtained from ?TZRZF. Q
+    size is inferred by m, n, side keywords.
+    """
+    rng = np.random.RandomState(1234)
+    qm, qn, cn = 10, 15, 15
+    for ind, dtype in enumerate(DTYPES):
+        tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
+                                           dtype=dtype)
+        lwork_rz = _compute_lwork(tzrzf_lw, qm, qn)
+
+        if ind < 2:
+            A = triu(rng.rand(qm, qn).astype(dtype))
+            C = rng.rand(cn, cn).astype(dtype)
+            orun_mrz, orun_mrz_lw = get_lapack_funcs(('ormrz', 'ormrz_lwork'),
+                                                     dtype=dtype)
+        else:
+            A = triu((rng.rand(qm, qn) + rng.rand(qm, qn)*1j).astype(dtype))
+            C = (rng.rand(cn, cn) + rand(cn, cn)*1j).astype(dtype)
+            orun_mrz, orun_mrz_lw = get_lapack_funcs(('unmrz', 'unmrz_lwork'),
+                                                     dtype=dtype)
+
+        lwork_mrz = _compute_lwork(orun_mrz_lw, cn, cn)
+        rz, tau, info = tzrzf(A, lwork=lwork_rz)
+
+        # Get Q manually for comparison
+        V = np.hstack((np.eye(qm, dtype=dtype), rz[:, qm:]))
+        Id = np.eye(qn, dtype=dtype)
+        ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(qm)]
+        Q = reduce(np.dot, ref)
+
+        # Now that we have Q, we can test whether lapack results agree with
+        # each case of CQ, CQ^H, QC, and QC^H
+        trans = 'T' if ind < 2 else 'C'
+        tol = 10*np.spacing(dtype(1.0).real)
+
+        cq, info = orun_mrz(rz, tau, C, lwork=lwork_mrz)
+        assert_(info == 0)
+        assert_allclose(cq - Q.dot(C), zeros_like(C), atol=tol, rtol=0.)
+
+        cq, info = orun_mrz(rz, tau, C, trans=trans, lwork=lwork_mrz)
+        assert_(info == 0)
+        assert_allclose(cq - Q.conj().T.dot(C), zeros_like(C), atol=tol,
+                        rtol=0.)
+
+        cq, info = orun_mrz(rz, tau, C, side='R', lwork=lwork_mrz)
+        assert_(info == 0)
+        assert_allclose(cq - C.dot(Q), zeros_like(C), atol=tol, rtol=0.)
+
+        cq, info = orun_mrz(rz, tau, C, side='R', trans=trans, lwork=lwork_mrz)
+        assert_(info == 0)
+        assert_allclose(cq - C.dot(Q.conj().T), zeros_like(C), atol=tol,
+                        rtol=0.)
+
+
+def test_tfttr_trttf():
+    """
+    Test conversion routines between the Rectangular Full Packed (RFP) format
+    and Standard Triangular Array (TR)
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            transr = 'C'
+        else:
+            A_full = (rng.rand(n, n)).astype(dtype)
+            transr = 'T'
+
+        trttf, tfttr = get_lapack_funcs(('trttf', 'tfttr'), dtype=dtype)
+        A_tf_U, info = trttf(A_full)
+        assert_(info == 0)
+        A_tf_L, info = trttf(A_full, uplo='L')
+        assert_(info == 0)
+        A_tf_U_T, info = trttf(A_full, transr=transr, uplo='U')
+        assert_(info == 0)
+        A_tf_L_T, info = trttf(A_full, transr=transr, uplo='L')
+        assert_(info == 0)
+
+        # Create the RFP array manually (n is even!)
+        A_tf_U_m = zeros((n+1, n//2), dtype=dtype)
+        A_tf_U_m[:-1, :] = triu(A_full)[:, n//2:]
+        A_tf_U_m[n//2+1:, :] += triu(A_full)[:n//2, :n//2].conj().T
+
+        A_tf_L_m = zeros((n+1, n//2), dtype=dtype)
+        A_tf_L_m[1:, :] = tril(A_full)[:, :n//2]
+        A_tf_L_m[:n//2, :] += tril(A_full)[n//2:, n//2:].conj().T
+
+        assert_array_almost_equal(A_tf_U, A_tf_U_m.reshape(-1, order='F'))
+        assert_array_almost_equal(A_tf_U_T,
+                                  A_tf_U_m.conj().T.reshape(-1, order='F'))
+
+        assert_array_almost_equal(A_tf_L, A_tf_L_m.reshape(-1, order='F'))
+        assert_array_almost_equal(A_tf_L_T,
+                                  A_tf_L_m.conj().T.reshape(-1, order='F'))
+
+        # Get the original array from RFP
+        A_tr_U, info = tfttr(n, A_tf_U)
+        assert_(info == 0)
+        A_tr_L, info = tfttr(n, A_tf_L, uplo='L')
+        assert_(info == 0)
+        A_tr_U_T, info = tfttr(n, A_tf_U_T, transr=transr, uplo='U')
+        assert_(info == 0)
+        A_tr_L_T, info = tfttr(n, A_tf_L_T, transr=transr, uplo='L')
+        assert_(info == 0)
+
+        assert_array_almost_equal(A_tr_U, triu(A_full))
+        assert_array_almost_equal(A_tr_U_T, triu(A_full))
+        assert_array_almost_equal(A_tr_L, tril(A_full))
+        assert_array_almost_equal(A_tr_L_T, tril(A_full))
+
+
+def test_tpttr_trttp():
+    """
+    Test conversion routines between the Rectangular Full Packed (RFP) format
+    and Standard Triangular Array (TR)
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+        else:
+            A_full = (rng.rand(n, n)).astype(dtype)
+
+        trttp, tpttr = get_lapack_funcs(('trttp', 'tpttr'), dtype=dtype)
+        A_tp_U, info = trttp(A_full)
+        assert_(info == 0)
+        A_tp_L, info = trttp(A_full, uplo='L')
+        assert_(info == 0)
+
+        # Create the TP array manually
+        inds = tril_indices(n)
+        A_tp_U_m = zeros(n*(n+1)//2, dtype=dtype)
+        A_tp_U_m[:] = (triu(A_full).T)[inds]
+
+        inds = triu_indices(n)
+        A_tp_L_m = zeros(n*(n+1)//2, dtype=dtype)
+        A_tp_L_m[:] = (tril(A_full).T)[inds]
+
+        assert_array_almost_equal(A_tp_U, A_tp_U_m)
+        assert_array_almost_equal(A_tp_L, A_tp_L_m)
+
+        # Get the original array from TP
+        A_tr_U, info = tpttr(n, A_tp_U)
+        assert_(info == 0)
+        A_tr_L, info = tpttr(n, A_tp_L, uplo='L')
+        assert_(info == 0)
+
+        assert_array_almost_equal(A_tr_U, triu(A_full))
+        assert_array_almost_equal(A_tr_L, tril(A_full))
+
+
+def test_pftrf():
+    """
+    Test Cholesky factorization of a positive definite Rectangular Full
+    Packed (RFP) format array
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            A = A + A.conj().T + n*eye(n)
+        else:
+            A = (rng.rand(n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        pftrf, trttf, tfttr = get_lapack_funcs(('pftrf', 'trttf', 'tfttr'),
+                                               dtype=dtype)
+
+        # Get the original array from TP
+        Afp, info = trttf(A)
+        Achol_rfp, info = pftrf(n, Afp)
+        assert_(info == 0)
+        A_chol_r, _ = tfttr(n, Achol_rfp)
+        Achol = cholesky(A)
+        assert_array_almost_equal(A_chol_r, Achol)
+
+
+def test_pftri():
+    """
+    Test Cholesky factorization of a positive definite Rectangular Full
+    Packed (RFP) format array to find its inverse
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            A = A + A.conj().T + n*eye(n)
+        else:
+            A = (rng.rand(n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        pftri, pftrf, trttf, tfttr = get_lapack_funcs(('pftri',
+                                                       'pftrf',
+                                                       'trttf',
+                                                       'tfttr'),
+                                                      dtype=dtype)
+
+        # Get the original array from TP
+        Afp, info = trttf(A)
+        A_chol_rfp, info = pftrf(n, Afp)
+        A_inv_rfp, info = pftri(n, A_chol_rfp)
+        assert_(info == 0)
+        A_inv_r, _ = tfttr(n, A_inv_rfp)
+        Ainv = inv(A)
+        assert_array_almost_equal(A_inv_r, triu(Ainv),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_pftrs():
+    """
+    Test Cholesky factorization of a positive definite Rectangular Full
+    Packed (RFP) format array and solve a linear system
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            A = A + A.conj().T + n*eye(n)
+        else:
+            A = (rng.rand(n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        B = ones((n, 3), dtype=dtype)
+        Bf1 = ones((n+2, 3), dtype=dtype)
+        Bf2 = ones((n-2, 3), dtype=dtype)
+        pftrs, pftrf, trttf, tfttr = get_lapack_funcs(('pftrs',
+                                                       'pftrf',
+                                                       'trttf',
+                                                       'tfttr'),
+                                                      dtype=dtype)
+
+        # Get the original array from TP
+        Afp, info = trttf(A)
+        A_chol_rfp, info = pftrf(n, Afp)
+        # larger B arrays shouldn't segfault
+        soln, info = pftrs(n, A_chol_rfp, Bf1)
+        assert_(info == 0)
+        assert_raises(Exception, pftrs, n, A_chol_rfp, Bf2)
+        soln, info = pftrs(n, A_chol_rfp, B)
+        assert_(info == 0)
+        assert_array_almost_equal(solve(A, B), soln,
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_sfrk_hfrk():
+    """
+    Test for performing a symmetric rank-k operation for matrix in RFP format.
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            A = A + A.conj().T + n*eye(n)
+        else:
+            A = (rng.rand(n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        prefix = 's'if ind < 2 else 'h'
+        trttf, tfttr, shfrk = get_lapack_funcs(('trttf', 'tfttr', f'{prefix}frk'),
+                                               dtype=dtype)
+
+        Afp, _ = trttf(A)
+        C = rng.rand(n, 2).astype(dtype)
+        Afp_out = shfrk(n, 2, -1, C, 2, Afp)
+        A_out, _ = tfttr(n, Afp_out)
+        assert_array_almost_equal(A_out, triu(-C.dot(C.conj().T) + 2*A),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_syconv():
+    """
+    Test for going back and forth between the returned format of he/sytrf to
+    L and D factors/permutations.
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 10
+
+        if ind > 1:
+            A = (rng.randint(-30, 30, (n, n)) +
+                 rng.randint(-30, 30, (n, n))*1j).astype(dtype)
+
+            A = A + A.conj().T
+        else:
+            A = rng.randint(-30, 30, (n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        tol = 100*np.spacing(dtype(1.0).real)
+        syconv, trf, trf_lwork = get_lapack_funcs(('syconv', 'sytrf',
+                                                   'sytrf_lwork'), dtype=dtype)
+        lw = _compute_lwork(trf_lwork, n, lower=1)
+        L, D, perm = ldl(A, lower=1, hermitian=False)
+        lw = _compute_lwork(trf_lwork, n, lower=1)
+        ldu, ipiv, info = trf(A, lower=1, lwork=lw)
+        a, e, info = syconv(ldu, ipiv, lower=1)
+        assert_allclose(tril(a, -1,), tril(L[perm, :], -1), atol=tol, rtol=0.)
+
+        # Test also upper
+        U, D, perm = ldl(A, lower=0, hermitian=False)
+        ldu, ipiv, info = trf(A, lower=0)
+        a, e, info = syconv(ldu, ipiv, lower=0)
+        assert_allclose(triu(a, 1), triu(U[perm, :], 1), atol=tol, rtol=0.)
+
+
+class TestBlockedQR:
+    """
+    Tests for the blocked QR factorization, namely through geqrt, gemqrt, tpqrt
+    and tpmqr.
+    """
+
+    def test_geqrt_gemqrt(self):
+        rng = np.random.RandomState(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 20
+
+            if ind > 1:
+                A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            else:
+                A = (rng.rand(n, n)).astype(dtype)
+
+            tol = 100*np.spacing(dtype(1.0).real)
+            geqrt, gemqrt = get_lapack_funcs(('geqrt', 'gemqrt'), dtype=dtype)
+
+            a, t, info = geqrt(n, A)
+            assert info == 0
+
+            # Extract elementary reflectors from lower triangle, adding the
+            # main diagonal of ones.
+            v = np.tril(a, -1) + np.eye(n, dtype=dtype)
+            # Generate the block Householder transform I - VTV^H
+            Q = np.eye(n, dtype=dtype) - v @ t @ v.T.conj()
+            R = np.triu(a)
+
+            # Test columns of Q are orthogonal
+            assert_allclose(Q.T.conj() @ Q, np.eye(n, dtype=dtype), atol=tol,
+                            rtol=0.)
+            assert_allclose(Q @ R, A, atol=tol, rtol=0.)
+
+            if ind > 1:
+                C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+                transpose = 'C'
+            else:
+                C = (rng.rand(n, n)).astype(dtype)
+                transpose = 'T'
+
+            for side in ('L', 'R'):
+                for trans in ('N', transpose):
+                    c, info = gemqrt(a, t, C, side=side, trans=trans)
+                    assert info == 0
+
+                    if trans == transpose:
+                        q = Q.T.conj()
+                    else:
+                        q = Q
+
+                    if side == 'L':
+                        qC = q @ C
+                    else:
+                        qC = C @ q
+
+                    assert_allclose(c, qC, atol=tol, rtol=0.)
+
+                    # Test default arguments
+                    if (side, trans) == ('L', 'N'):
+                        c_default, info = gemqrt(a, t, C)
+                        assert info == 0
+                        assert_equal(c_default, c)
+
+            # Test invalid side/trans
+            assert_raises(Exception, gemqrt, a, t, C, side='A')
+            assert_raises(Exception, gemqrt, a, t, C, trans='A')
+
+    def test_tpqrt_tpmqrt(self):
+        rng = np.random.RandomState(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 20
+
+            if ind > 1:
+                A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+                B = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            else:
+                A = (rng.rand(n, n)).astype(dtype)
+                B = (rng.rand(n, n)).astype(dtype)
+
+            tol = 100*np.spacing(dtype(1.0).real)
+            tpqrt, tpmqrt = get_lapack_funcs(('tpqrt', 'tpmqrt'), dtype=dtype)
+
+            # Test for the range of pentagonal B, from square to upper
+            # triangular
+            for l in (0, n // 2, n):
+                a, b, t, info = tpqrt(l, n, A, B)
+                assert info == 0
+
+                # Check that lower triangular part of A has not been modified
+                assert_equal(np.tril(a, -1), np.tril(A, -1))
+                # Check that elements not part of the pentagonal portion of B
+                # have not been modified.
+                assert_equal(np.tril(b, l - n - 1), np.tril(B, l - n - 1))
+
+                # Extract pentagonal portion of B
+                B_pent, b_pent = np.triu(B, l - n), np.triu(b, l - n)
+
+                # Generate elementary reflectors
+                v = np.concatenate((np.eye(n, dtype=dtype), b_pent))
+                # Generate the block Householder transform I - VTV^H
+                Q = np.eye(2 * n, dtype=dtype) - v @ t @ v.T.conj()
+                R = np.concatenate((np.triu(a), np.zeros_like(a)))
+
+                # Test columns of Q are orthogonal
+                assert_allclose(Q.T.conj() @ Q, np.eye(2 * n, dtype=dtype),
+                                atol=tol, rtol=0.)
+                assert_allclose(Q @ R, np.concatenate((np.triu(A), B_pent)),
+                                atol=tol, rtol=0.)
+
+                if ind > 1:
+                    C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+                    D = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+                    transpose = 'C'
+                else:
+                    C = (rng.rand(n, n)).astype(dtype)
+                    D = (rng.rand(n, n)).astype(dtype)
+                    transpose = 'T'
+
+                for side in ('L', 'R'):
+                    for trans in ('N', transpose):
+                        c, d, info = tpmqrt(l, b, t, C, D, side=side,
+                                            trans=trans)
+                        assert info == 0
+
+                        if trans == transpose:
+                            q = Q.T.conj()
+                        else:
+                            q = Q
+
+                        if side == 'L':
+                            cd = np.concatenate((c, d), axis=0)
+                            CD = np.concatenate((C, D), axis=0)
+                            qCD = q @ CD
+                        else:
+                            cd = np.concatenate((c, d), axis=1)
+                            CD = np.concatenate((C, D), axis=1)
+                            qCD = CD @ q
+
+                        assert_allclose(cd, qCD, atol=tol, rtol=0.)
+
+                        if (side, trans) == ('L', 'N'):
+                            c_default, d_default, info = tpmqrt(l, b, t, C, D)
+                            assert info == 0
+                            assert_equal(c_default, c)
+                            assert_equal(d_default, d)
+
+                # Test invalid side/trans
+                assert_raises(Exception, tpmqrt, l, b, t, C, D, side='A')
+                assert_raises(Exception, tpmqrt, l, b, t, C, D, trans='A')
+
+
+def test_pstrf():
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        # DTYPES =  pstrf
+        n = 10
+        r = 2
+        pstrf = get_lapack_funcs('pstrf', dtype=dtype)
+
+        # Create positive semidefinite A
+        if ind > 1:
+            A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype)
+            A = A @ A.conj().T
+        else:
+            A = rng.rand(n, n-r).astype(dtype)
+            A = A @ A.T
+
+        c, piv, r_c, info = pstrf(A)
+        U = triu(c)
+        U[r_c - n:, r_c - n:] = 0.
+
+        assert_equal(info, 1)
+        # python-dbg 3.5.2 runs cause trouble with the following assertion.
+        # assert_equal(r_c, n - r)
+        single_atol = 1000 * np.finfo(np.float32).eps
+        double_atol = 1000 * np.finfo(np.float64).eps
+        atol = single_atol if ind in [0, 2] else double_atol
+        assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol)
+
+        c, piv, r_c, info = pstrf(A, lower=1)
+        L = tril(c)
+        L[r_c - n:, r_c - n:] = 0.
+
+        assert_equal(info, 1)
+        # assert_equal(r_c, n - r)
+        single_atol = 1000 * np.finfo(np.float32).eps
+        double_atol = 1000 * np.finfo(np.float64).eps
+        atol = single_atol if ind in [0, 2] else double_atol
+        assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol)
+
+
+def test_pstf2():
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        # DTYPES =  pstf2
+        n = 10
+        r = 2
+        pstf2 = get_lapack_funcs('pstf2', dtype=dtype)
+
+        # Create positive semidefinite A
+        if ind > 1:
+            A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype)
+            A = A @ A.conj().T
+        else:
+            A = rng.rand(n, n-r).astype(dtype)
+            A = A @ A.T
+
+        c, piv, r_c, info = pstf2(A)
+        U = triu(c)
+        U[r_c - n:, r_c - n:] = 0.
+
+        assert_equal(info, 1)
+        # python-dbg 3.5.2 runs cause trouble with the commented assertions.
+        # assert_equal(r_c, n - r)
+        single_atol = 1000 * np.finfo(np.float32).eps
+        double_atol = 1000 * np.finfo(np.float64).eps
+        atol = single_atol if ind in [0, 2] else double_atol
+        assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol)
+
+        c, piv, r_c, info = pstf2(A, lower=1)
+        L = tril(c)
+        L[r_c - n:, r_c - n:] = 0.
+
+        assert_equal(info, 1)
+        # assert_equal(r_c, n - r)
+        single_atol = 1000 * np.finfo(np.float32).eps
+        double_atol = 1000 * np.finfo(np.float64).eps
+        atol = single_atol if ind in [0, 2] else double_atol
+        assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol)
+
+
+def test_geequ():
+    desired_real = np.array([[0.6250, 1.0000, 0.0393, -0.4269],
+                             [1.0000, -0.5619, -1.0000, -1.0000],
+                             [0.5874, -1.0000, -0.0596, -0.5341],
+                             [-1.0000, -0.5946, -0.0294, 0.9957]])
+
+    desired_cplx = np.array([[-0.2816+0.5359*1j,
+                              0.0812+0.9188*1j,
+                              -0.7439-0.2561*1j],
+                             [-0.3562-0.2954*1j,
+                              0.9566-0.0434*1j,
+                              -0.0174+0.1555*1j],
+                             [0.8607+0.1393*1j,
+                              -0.2759+0.7241*1j,
+                              -0.1642-0.1365*1j]])
+
+    for ind, dtype in enumerate(DTYPES):
+        if ind < 2:
+            # Use examples from the NAG documentation
+            A = np.array([[1.80e+10, 2.88e+10, 2.05e+00, -8.90e+09],
+                          [5.25e+00, -2.95e+00, -9.50e-09, -3.80e+00],
+                          [1.58e+00, -2.69e+00, -2.90e-10, -1.04e+00],
+                          [-1.11e+00, -6.60e-01, -5.90e-11, 8.00e-01]])
+            A = A.astype(dtype)
+        else:
+            A = np.array([[-1.34e+00, 0.28e+10, -6.39e+00],
+                          [-1.70e+00, 3.31e+10, -0.15e+00],
+                          [2.41e-10, -0.56e+00, -0.83e-10]], dtype=dtype)
+            A += np.array([[2.55e+00, 3.17e+10, -2.20e+00],
+                           [-1.41e+00, -0.15e+10, 1.34e+00],
+                           [0.39e-10, 1.47e+00, -0.69e-10]])*1j
+
+            A = A.astype(dtype)
+
+        geequ = get_lapack_funcs('geequ', dtype=dtype)
+        r, c, rowcnd, colcnd, amax, info = geequ(A)
+
+        if ind < 2:
+            assert_allclose(desired_real.astype(dtype), r[:, None]*A*c,
+                            rtol=0, atol=1e-4)
+        else:
+            assert_allclose(desired_cplx.astype(dtype), r[:, None]*A*c,
+                            rtol=0, atol=1e-4)
+
+
+def test_syequb():
+    desired_log2s = np.array([0, 0, 0, 0, 0, 0, -1, -1, -2, -3])
+
+    for ind, dtype in enumerate(DTYPES):
+        A = np.eye(10, dtype=dtype)
+        alpha = dtype(1. if ind < 2 else 1.j)
+        d = np.array([alpha * 2.**x for x in range(-5, 5)], dtype=dtype)
+        A += np.rot90(np.diag(d))
+
+        syequb = get_lapack_funcs('syequb', dtype=dtype)
+        s, scond, amax, info = syequb(A)
+
+        assert_equal(np.log2(s).astype(int), desired_log2s)
+
+
+@pytest.mark.skipif(True,
+                    reason="Failing on some OpenBLAS version, see gh-12276")
+def test_heequb():
+    # zheequb has a bug for versions =< LAPACK 3.9.0
+    # See Reference-LAPACK gh-61 and gh-408
+    # Hence the zheequb test is customized accordingly to avoid
+    # work scaling.
+    A = np.diag([2]*5 + [1002]*5) + np.diag(np.ones(9), k=1)*1j
+    s, scond, amax, info = lapack.zheequb(A)
+    assert_equal(info, 0)
+    assert_allclose(np.log2(s), [0., -1.]*2 + [0.] + [-4]*5)
+
+    A = np.diag(2**np.abs(np.arange(-5, 6)) + 0j)
+    A[5, 5] = 1024
+    A[5, 0] = 16j
+    s, scond, amax, info = lapack.cheequb(A.astype(np.complex64), lower=1)
+    assert_equal(info, 0)
+    assert_allclose(np.log2(s), [-2, -1, -1, 0, 0, -5, 0, -1, -1, -2, -2])
+
+
+def test_getc2_gesc2():
+    rng = np.random.RandomState(42)
+    n = 10
+    desired_real = rng.rand(n)
+    desired_cplx = rng.rand(n) + rng.rand(n)*1j
+
+    for ind, dtype in enumerate(DTYPES):
+        if ind < 2:
+            A = rng.rand(n, n)
+            A = A.astype(dtype)
+            b = A @ desired_real
+            b = b.astype(dtype)
+        else:
+            A = rng.rand(n, n) + rng.rand(n, n)*1j
+            A = A.astype(dtype)
+            b = A @ desired_cplx
+            b = b.astype(dtype)
+
+        getc2 = get_lapack_funcs('getc2', dtype=dtype)
+        gesc2 = get_lapack_funcs('gesc2', dtype=dtype)
+        lu, ipiv, jpiv, info = getc2(A, overwrite_a=0)
+        x, scale = gesc2(lu, b, ipiv, jpiv, overwrite_rhs=0)
+
+        if ind < 2:
+            assert_array_almost_equal(desired_real.astype(dtype),
+                                      x/scale, decimal=4)
+        else:
+            assert_array_almost_equal(desired_cplx.astype(dtype),
+                                      x/scale, decimal=4)
+
+
+@pytest.mark.parametrize('size', [(6, 5), (5, 5)])
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+@pytest.mark.parametrize('joba', range(6))  # 'C', 'E', 'F', 'G', 'A', 'R'
+@pytest.mark.parametrize('jobu', range(4))  # 'U', 'F', 'W', 'N'
+@pytest.mark.parametrize('jobv', range(4))  # 'V', 'J', 'W', 'N'
+@pytest.mark.parametrize('jobr', [0, 1])
+@pytest.mark.parametrize('jobp', [0, 1])
+def test_gejsv_general(size, dtype, joba, jobu, jobv, jobr, jobp, jobt=0):
+    """Test the lapack routine ?gejsv.
+
+    This function tests that a singular value decomposition can be performed
+    on the random M-by-N matrix A. The test performs the SVD using ?gejsv
+    then performs the following checks:
+
+    * ?gejsv exist successfully (info == 0)
+    * The returned singular values are correct
+    * `A` can be reconstructed from `u`, `SIGMA`, `v`
+    * Ensure that u.T @ u is the identity matrix
+    * Ensure that v.T @ v is the identity matrix
+    * The reported matrix rank
+    * The reported number of singular values
+    * If denormalized floats are required
+
+    Notes
+    -----
+    joba specifies several choices effecting the calculation's accuracy
+    Although all arguments are tested, the tests only check that the correct
+    solution is returned - NOT that the prescribed actions are performed
+    internally.
+
+    jobt is, as of v3.9.0, still experimental and removed to cut down number of
+    test cases. However keyword itself is tested externally.
+    """
+    rng = np.random.RandomState(42)
+
+    # Define some constants for later use:
+    m, n = size
+    atol = 100 * np.finfo(dtype).eps
+    A = generate_random_dtype_array(size, dtype, rng)
+    gejsv = get_lapack_funcs('gejsv', dtype=dtype)
+
+    # Set up checks for invalid job? combinations
+    # if an invalid combination occurs we set the appropriate
+    # exit status.
+    lsvec = jobu < 2  # Calculate left singular vectors
+    rsvec = jobv < 2  # Calculate right singular vectors
+    l2tran = (jobt == 1) and (m == n)
+    is_complex = np.iscomplexobj(A)
+
+    invalid_real_jobv = (jobv == 1) and (not lsvec) and (not is_complex)
+    invalid_cplx_jobu = (jobu == 2) and not (rsvec and l2tran) and is_complex
+    invalid_cplx_jobv = (jobv == 2) and not (lsvec and l2tran) and is_complex
+
+    # Set the exit status to the expected value.
+    # Here we only check for invalid combinations, not individual
+    # parameters.
+    if invalid_cplx_jobu:
+        exit_status = -2
+    elif invalid_real_jobv or invalid_cplx_jobv:
+        exit_status = -3
+    else:
+        exit_status = 0
+
+    if (jobu > 1) and (jobv == 1):
+        assert_raises(Exception, gejsv, A, joba, jobu, jobv, jobr, jobt, jobp)
+    else:
+        sva, u, v, work, iwork, info = gejsv(A,
+                                             joba=joba,
+                                             jobu=jobu,
+                                             jobv=jobv,
+                                             jobr=jobr,
+                                             jobt=jobt,
+                                             jobp=jobp)
+
+        # Check that ?gejsv exited successfully/as expected
+        assert_equal(info, exit_status)
+
+        # If exit_status is non-zero the combination of jobs is invalid.
+        # We test this above but no calculations are performed.
+        if not exit_status:
+
+            # Check the returned singular values
+            sigma = (work[0] / work[1]) * sva[:n]
+            assert_allclose(sigma, svd(A, compute_uv=False), atol=atol)
+
+            if jobu == 1:
+                # If JOBU = 'F', then u contains the M-by-M matrix of
+                # the left singular vectors, including an ONB of the orthogonal
+                # complement of the Range(A)
+                # However, to recalculate A we are concerned about the
+                # first n singular values and so can ignore the latter.
+                # TODO: Add a test for ONB?
+                u = u[:, :n]
+
+            if lsvec and rsvec:
+                assert_allclose(u @ np.diag(sigma) @ v.conj().T, A, atol=atol)
+            if lsvec:
+                assert_allclose(u.conj().T @ u, np.identity(n), atol=atol)
+            if rsvec:
+                assert_allclose(v.conj().T @ v, np.identity(n), atol=atol)
+
+            assert_equal(iwork[0], np.linalg.matrix_rank(A))
+            assert_equal(iwork[1], np.count_nonzero(sigma))
+            # iwork[2] is non-zero if requested accuracy is not warranted for
+            # the data. This should never occur for these tests.
+            assert_equal(iwork[2], 0)
+
+
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+def test_gejsv_edge_arguments(dtype):
+    """Test edge arguments return expected status"""
+    gejsv = get_lapack_funcs('gejsv', dtype=dtype)
+
+    # scalar A
+    sva, u, v, work, iwork, info = gejsv(1.)
+    assert_equal(info, 0)
+    assert_equal(u.shape, (1, 1))
+    assert_equal(v.shape, (1, 1))
+    assert_equal(sva, np.array([1.], dtype=dtype))
+
+    # 1d A
+    A = np.ones((1,), dtype=dtype)
+    sva, u, v, work, iwork, info = gejsv(A)
+    assert_equal(info, 0)
+    assert_equal(u.shape, (1, 1))
+    assert_equal(v.shape, (1, 1))
+    assert_equal(sva, np.array([1.], dtype=dtype))
+
+    # 2d empty A
+    A = np.ones((1, 0), dtype=dtype)
+    sva, u, v, work, iwork, info = gejsv(A)
+    assert_equal(info, 0)
+    assert_equal(u.shape, (1, 0))
+    assert_equal(v.shape, (1, 0))
+    assert_equal(sva, np.array([], dtype=dtype))
+
+    # make sure "overwrite_a" is respected - user reported in gh-13191
+    A = np.sin(np.arange(100).reshape(10, 10)).astype(dtype)
+    A = np.asfortranarray(A + A.T)  # make it symmetric and column major
+    Ac = A.copy('A')
+    _ = gejsv(A)
+    assert_allclose(A, Ac)
+
+
+@pytest.mark.parametrize(('kwargs'),
+                         ({'joba': 9},
+                          {'jobu': 9},
+                          {'jobv': 9},
+                          {'jobr': 9},
+                          {'jobt': 9},
+                          {'jobp': 9})
+                         )
+def test_gejsv_invalid_job_arguments(kwargs):
+    """Test invalid job arguments raise an Exception"""
+    A = np.ones((2, 2), dtype=float)
+    gejsv = get_lapack_funcs('gejsv', dtype=float)
+    assert_raises(Exception, gejsv, A, **kwargs)
+
+
+@pytest.mark.parametrize("A,sva_expect,u_expect,v_expect",
+                         [(np.array([[2.27, -1.54, 1.15, -1.94],
+                                     [0.28, -1.67, 0.94, -0.78],
+                                     [-0.48, -3.09, 0.99, -0.21],
+                                     [1.07, 1.22, 0.79, 0.63],
+                                     [-2.35, 2.93, -1.45, 2.30],
+                                     [0.62, -7.39, 1.03, -2.57]]),
+                           np.array([9.9966, 3.6831, 1.3569, 0.5000]),
+                           np.array([[0.2774, -0.6003, -0.1277, 0.1323],
+                                     [0.2020, -0.0301, 0.2805, 0.7034],
+                                     [0.2918, 0.3348, 0.6453, 0.1906],
+                                     [-0.0938, -0.3699, 0.6781, -0.5399],
+                                     [-0.4213, 0.5266, 0.0413, -0.0575],
+                                     [0.7816, 0.3353, -0.1645, -0.3957]]),
+                           np.array([[0.1921, -0.8030, 0.0041, -0.5642],
+                                     [-0.8794, -0.3926, -0.0752, 0.2587],
+                                     [0.2140, -0.2980, 0.7827, 0.5027],
+                                     [-0.3795, 0.3351, 0.6178, -0.6017]]))])
+def test_gejsv_NAG(A, sva_expect, u_expect, v_expect):
+    """
+    This test implements the example found in the NAG manual, f08khf.
+    An example was not found for the complex case.
+    """
+    # NAG manual provides accuracy up to 4 decimals
+    atol = 1e-4
+    gejsv = get_lapack_funcs('gejsv', dtype=A.dtype)
+
+    sva, u, v, work, iwork, info = gejsv(A)
+
+    assert_allclose(sva_expect, sva, atol=atol)
+    assert_allclose(u_expect, u, atol=atol)
+    assert_allclose(v_expect, v, atol=atol)
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+def test_gttrf_gttrs(dtype):
+    # The test uses ?gttrf and ?gttrs to solve a random system for each dtype,
+    # tests that the output of ?gttrf define LU matrices, that input
+    # parameters are unmodified, transposal options function correctly, that
+    # incompatible matrix shapes raise an error, and singular matrices return
+    # non zero info.
+
+    rng = np.random.RandomState(42)
+    n = 10
+    atol = 100 * np.finfo(dtype).eps
+
+    # create the matrix in accordance with the data type
+    du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+    dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+
+    diag_cpy = [dl.copy(), d.copy(), du.copy()]
+
+    A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1)
+    x = np.random.rand(n)
+    b = A @ x
+
+    gttrf, gttrs = get_lapack_funcs(('gttrf', 'gttrs'), dtype=dtype)
+
+    _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du)
+    # test to assure that the inputs of ?gttrf are unmodified
+    assert_array_equal(dl, diag_cpy[0])
+    assert_array_equal(d, diag_cpy[1])
+    assert_array_equal(du, diag_cpy[2])
+
+    # generate L and U factors from ?gttrf return values
+    # L/U are lower/upper triangular by construction (initially and at end)
+    U = np.diag(_d, 0) + np.diag(_du, 1) + np.diag(du2, 2)
+    L = np.eye(n, dtype=dtype)
+
+    for i, m in enumerate(_dl):
+        # L is given in a factored form.
+        # See
+        # www.hpcavf.uclan.ac.uk/softwaredoc/sgi_scsl_html/sgi_html/ch03.html
+        piv = ipiv[i] - 1
+        # right multiply by permutation matrix
+        L[:, [i, piv]] = L[:, [piv, i]]
+        # right multiply by Li, rank-one modification of identity
+        L[:, i] += L[:, i+1]*m
+
+    # one last permutation
+    i, piv = -1, ipiv[-1] - 1
+    # right multiply by final permutation matrix
+    L[:, [i, piv]] = L[:, [piv, i]]
+
+    # check that the outputs of ?gttrf define an LU decomposition of A
+    assert_allclose(A, L @ U, atol=atol)
+
+    b_cpy = b.copy()
+    x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b)
+    # test that the inputs of ?gttrs are unmodified
+    assert_array_equal(b, b_cpy)
+    # test that the result of ?gttrs matches the expected input
+    assert_allclose(x, x_gttrs, atol=atol)
+
+    # test that ?gttrf and ?gttrs work with transposal options
+    if dtype in REAL_DTYPES:
+        trans = "T"
+        b_trans = A.T @ x
+    else:
+        trans = "C"
+        b_trans = A.conj().T @ x
+
+    x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b_trans, trans=trans)
+    assert_allclose(x, x_gttrs, atol=atol)
+
+    # test that ValueError is raised with incompatible matrix shapes
+    with assert_raises(ValueError):
+        gttrf(dl[:-1], d, du)
+    with assert_raises(ValueError):
+        gttrf(dl, d[:-1], du)
+    with assert_raises(ValueError):
+        gttrf(dl, d, du[:-1])
+
+    # test that matrix of size n=2 raises exception
+    with assert_raises(ValueError):
+        gttrf(dl[0], d[:1], du[0])
+
+    # test that singular (row of all zeroes) matrix fails via info
+    du[0] = 0
+    d[0] = 0
+    __dl, __d, __du, _du2, _ipiv, _info = gttrf(dl, d, du)
+    np.testing.assert_(__d[info - 1] == 0, (f"?gttrf: _d[info-1] is {__d[info - 1]},"
+                                            " not the illegal value :0."))
+
+
+@pytest.mark.parametrize("du, d, dl, du_exp, d_exp, du2_exp, ipiv_exp, b, x",
+                         [(np.array([2.1, -1.0, 1.9, 8.0]),
+                             np.array([3.0, 2.3, -5.0, -.9, 7.1]),
+                             np.array([3.4, 3.6, 7.0, -6.0]),
+                             np.array([2.3, -5, -.9, 7.1]),
+                             np.array([3.4, 3.6, 7, -6, -1.015373]),
+                             np.array([-1, 1.9, 8]),
+                             np.array([2, 3, 4, 5, 5]),
+                             np.array([[2.7, 6.6],
+                                       [-0.5, 10.8],
+                                       [2.6, -3.2],
+                                       [0.6, -11.2],
+                                       [2.7, 19.1]
+                                       ]),
+                             np.array([[-4, 5],
+                                       [7, -4],
+                                       [3, -3],
+                                       [-4, -2],
+                                       [-3, 1]])),
+                          (
+                             np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]),
+                             np.array([-1.3 + 1.3j, -1.3 + 1.3j,
+                                       -1.3 + 3.3j, - .3 + 4.3j,
+                                       -3.3 + 1.3j]),
+                             np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]),
+                             # du exp
+                             np.array([-1.3 + 1.3j, -1.3 + 3.3j,
+                                       -0.3 + 4.3j, -3.3 + 1.3j]),
+                             np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j,
+                                       -1.3399 + 0.2875j]),
+                             np.array([2 + 1j, -1 + 1j, 1 - 1j]),
+                             np.array([2, 3, 4, 5, 5]),
+                             np.array([[2.4 - 5j, 2.7 + 6.9j],
+                                       [3.4 + 18.2j, - 6.9 - 5.3j],
+                                       [-14.7 + 9.7j, - 6 - .6j],
+                                       [31.9 - 7.7j, -3.9 + 9.3j],
+                                       [-1 + 1.6j, -3 + 12.2j]]),
+                             np.array([[1 + 1j, 2 - 1j],
+                                       [3 - 1j, 1 + 2j],
+                                       [4 + 5j, -1 + 1j],
+                                       [-1 - 2j, 2 + 1j],
+                                       [1 - 1j, 2 - 2j]])
+                            )])
+def test_gttrf_gttrs_NAG_f07cdf_f07cef_f07crf_f07csf(du, d, dl, du_exp, d_exp,
+                                                     du2_exp, ipiv_exp, b, x):
+    # test to assure that wrapper is consistent with NAG Library Manual Mark 26
+    # example problems: f07cdf and f07cef (real)
+    # examples: f07crf and f07csf (complex)
+    # (Links may expire, so search for "NAG Library Manual Mark 26" online)
+
+    gttrf, gttrs = get_lapack_funcs(('gttrf', "gttrs"), (du[0], du[0]))
+
+    _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du)
+    assert_allclose(du2, du2_exp)
+    assert_allclose(_du, du_exp)
+    assert_allclose(_d, d_exp, atol=1e-4)  # NAG examples provide 4 decimals.
+    assert_allclose(ipiv, ipiv_exp)
+
+    x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b)
+
+    assert_allclose(x_gttrs, x)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('norm', ['1', 'I', 'O'])
+@pytest.mark.parametrize('n', [3, 10])
+def test_gtcon(dtype, norm, n):
+    rng = np.random.default_rng(23498324)
+
+    d = rng.random(n) + rng.random(n)*1j
+    dl = rng.random(n - 1) + rng.random(n - 1)*1j
+    du = rng.random(n - 1) + rng.random(n - 1)*1j
+    A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1)
+    if np.issubdtype(dtype, np.floating):
+        A, d, dl, du = A.real, d.real, dl.real, du.real
+    A, d, dl, du = A.astype(dtype), d.astype(dtype), dl.astype(dtype), du.astype(dtype)
+
+    anorm = np.abs(A).sum(axis=0).max()
+
+    gttrf, gtcon = get_lapack_funcs(('gttrf', 'gtcon'), (A,))
+    dl, d, du, du2, ipiv, info = gttrf(dl, d, du)
+    res, _ = gtcon(dl, d, du, du2, ipiv, anorm, norm=norm)
+
+    gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
+    lu, ipvt, info = getrf(A)
+    ref, _ = gecon(lu, anorm, norm=norm)
+
+    rtol = np.finfo(dtype).eps**0.75
+    assert_allclose(res, ref, rtol=rtol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('shape', [(3, 7), (7, 3), (2**18, 2**18)])
+def test_geqrfp_lwork(dtype, shape):
+    geqrfp_lwork = get_lapack_funcs(('geqrfp_lwork'), dtype=dtype)
+    m, n = shape
+    lwork, info = geqrfp_lwork(m=m, n=n)
+    assert_equal(info, 0)
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+                         zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
+def test_pttrf_pttrs(ddtype, dtype):
+    rng = np.random.RandomState(42)
+    # set test tolerance appropriate for dtype
+    atol = 100*np.finfo(dtype).eps
+    # n is the length diagonal of A
+    n = 10
+    # create diagonals according to size and dtype
+
+    # diagonal d should always be real.
+    # add 4 to d so it will be dominant for all dtypes
+    d = generate_random_dtype_array((n,), ddtype, rng) + 4
+    # diagonal e may be real or complex.
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+
+    # assemble diagonals together into matrix
+    A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+    # store a copy of diagonals to later verify
+    diag_cpy = [d.copy(), e.copy()]
+
+    pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+
+    _d, _e, info = pttrf(d, e)
+    # test to assure that the inputs of ?pttrf are unmodified
+    assert_array_equal(d, diag_cpy[0])
+    assert_array_equal(e, diag_cpy[1])
+    assert_equal(info, 0, err_msg=f"pttrf: info = {info}, should be 0")
+
+    # test that the factors from pttrf can be recombined to make A
+    L = np.diag(_e, -1) + np.diag(np.ones(n))
+    D = np.diag(_d)
+
+    assert_allclose(A, L@D@L.conjugate().T, atol=atol)
+
+    # generate random solution x
+    x = generate_random_dtype_array((n,), dtype, rng)
+    # determine accompanying b to get soln x
+    b = A@x
+
+    # determine _x from pttrs
+    pttrs = get_lapack_funcs('pttrs', dtype=dtype)
+    _x, info = pttrs(_d, _e.conj(), b)
+    assert_equal(info, 0, err_msg=f"pttrs: info = {info}, should be 0")
+
+    # test that _x from pttrs matches the expected x
+    assert_allclose(x, _x, atol=atol)
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+                         zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
+def test_pttrf_pttrs_errors_incompatible_shape(ddtype, dtype):
+    n = 10
+    rng = np.random.RandomState(1234)
+    pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+    d = generate_random_dtype_array((n,), ddtype, rng) + 2
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    # test that ValueError is raised with incompatible matrix shapes
+    assert_raises(ValueError, pttrf, d[:-1], e)
+    assert_raises(ValueError, pttrf, d, e[:-1])
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+                         zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
+def test_pttrf_pttrs_errors_singular_nonSPD(ddtype, dtype):
+    n = 10
+    rng = np.random.RandomState(42)
+    pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+    d = generate_random_dtype_array((n,), ddtype, rng) + 2
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    # test that singular (row of all zeroes) matrix fails via info
+    d[0] = 0
+    e[0] = 0
+    _d, _e, info = pttrf(d, e)
+    assert_equal(_d[info - 1], 0,
+                 f"?pttrf: _d[info-1] is {_d[info - 1]}, not the illegal value :0.")
+
+    # test with non-spd matrix
+    d = generate_random_dtype_array((n,), ddtype, rng)
+    _d, _e, info = pttrf(d, e)
+    assert_(info != 0, "?pttrf should fail with non-spd matrix, but didn't")
+
+
+@pytest.mark.parametrize(("d, e, d_expect, e_expect, b, x_expect"), [
+                         (np.array([4, 10, 29, 25, 5]),
+                          np.array([-2, -6, 15, 8]),
+                          np.array([4, 9, 25, 16, 1]),
+                          np.array([-.5, -.6667, .6, .5]),
+                          np.array([[6, 10], [9, 4], [2, 9], [14, 65],
+                                    [7, 23]]),
+                          np.array([[2.5, 2], [2, -1], [1, -3], [-1, 6],
+                                    [3, -5]])
+                          ), (
+                          np.array([16, 41, 46, 21]),
+                          np.array([16 + 16j, 18 - 9j, 1 - 4j]),
+                          np.array([16, 9, 1, 4]),
+                          np.array([1+1j, 2-1j, 1-4j]),
+                          np.array([[64+16j, -16-32j], [93+62j, 61-66j],
+                                    [78-80j, 71-74j], [14-27j, 35+15j]]),
+                          np.array([[2+1j, -3-2j], [1+1j, 1+1j], [1-2j, 1-2j],
+                                    [1-1j, 2+1j]])
+                         )])
+def test_pttrf_pttrs_NAG(d, e, d_expect, e_expect, b, x_expect):
+    # test to assure that wrapper is consistent with NAG Manual Mark 26
+    # example problems: f07jdf and f07jef (real)
+    # examples: f07jrf and f07csf (complex)
+    # NAG examples provide 4 decimals.
+    # (Links expire, so please search for "NAG Library Manual Mark 26" online)
+
+    atol = 1e-4
+    pttrf = get_lapack_funcs('pttrf', dtype=e[0])
+    _d, _e, info = pttrf(d, e)
+    assert_allclose(_d, d_expect, atol=atol)
+    assert_allclose(_e, e_expect, atol=atol)
+
+    pttrs = get_lapack_funcs('pttrs', dtype=e[0])
+    _x, info = pttrs(_d, _e.conj(), b)
+    assert_allclose(_x, x_expect, atol=atol)
+
+    # also test option `lower`
+    if e.dtype in COMPLEX_DTYPES:
+        _x, info = pttrs(_d, _e, b, lower=1)
+        assert_allclose(_x, x_expect, atol=atol)
+
+
+def pteqr_get_d_e_A_z(dtype, realtype, n, compute_z):
+    # used by ?pteqr tests to build parameters
+    # returns tuple of (d, e, A, z)
+    rng = np.random.RandomState(42)
+    if compute_z == 1:
+        # build Hermitian A from Q**T * tri * Q = A by creating Q and tri
+        A_eig = generate_random_dtype_array((n, n), dtype, rng)
+        A_eig = A_eig + np.diag(np.zeros(n) + 4*n)
+        A_eig = (A_eig + A_eig.conj().T) / 2
+        # obtain right eigenvectors (orthogonal)
+        vr = eigh(A_eig)[1]
+        # create tridiagonal matrix
+        d = generate_random_dtype_array((n,), realtype, rng) + 4
+        e = generate_random_dtype_array((n-1,), realtype, rng)
+        tri = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+        # Build A using these factors that sytrd would: (Q**T * tri * Q = A)
+        A = vr @ tri @ vr.conj().T
+        # vr is orthogonal
+        z = vr
+
+    else:
+        # d and e are always real per lapack docs.
+        d = generate_random_dtype_array((n,), realtype, rng)
+        e = generate_random_dtype_array((n-1,), realtype, rng)
+
+        # make SPD
+        d = d + 4
+        A = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+        z = np.diag(d) + np.diag(e, -1) + np.diag(e, 1)
+    return (d, e, A, z)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr(dtype, realtype, compute_z):
+    '''
+    Tests the ?pteqr lapack routine for all dtypes and compute_z parameters.
+    It generates random SPD matrix diagonals d and e, and then confirms
+    correct eigenvalues with scipy.linalg.eig. With applicable compute_z=2 it
+    tests that z can reform A.
+    '''
+    seed(42)
+    atol = 1000*np.finfo(dtype).eps
+    pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+
+    n = 10
+
+    d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+
+    d_pteqr, e_pteqr, z_pteqr, info = pteqr(d=d, e=e, z=z, compute_z=compute_z)
+    assert_equal(info, 0, f"info = {info}, should be 0.")
+
+    # compare the routine's eigenvalues with scipy.linalg.eig's.
+    assert_allclose(np.sort(eigh(A)[0]), np.sort(d_pteqr), atol=atol)
+
+    if compute_z:
+        # verify z_pteqr as orthogonal
+        assert_allclose(z_pteqr @ np.conj(z_pteqr).T, np.identity(n),
+                        atol=atol)
+        # verify that z_pteqr recombines to A
+        assert_allclose(z_pteqr @ np.diag(d_pteqr) @ np.conj(z_pteqr).T,
+                        A, atol=atol)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_error_non_spd(dtype, realtype, compute_z):
+    seed(42)
+    pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+
+    n = 10
+    d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+
+    # test with non-spd matrix
+    d_pteqr, e_pteqr, z_pteqr, info = pteqr(d - 4, e, z=z, compute_z=compute_z)
+    assert info > 0
+
+
+@pytest.mark.parametrize("dtype,realtype",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_raise_error_wrong_shape(dtype, realtype, compute_z):
+    seed(42)
+    pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+    n = 10
+    d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+    # test with incorrect/incompatible array sizes
+    assert_raises(ValueError, pteqr, d[:-1], e, z=z, compute_z=compute_z)
+    assert_raises(ValueError, pteqr, d, e[:-1], z=z, compute_z=compute_z)
+    if compute_z:
+        assert_raises(ValueError, pteqr, d, e, z=z[:-1], compute_z=compute_z)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_error_singular(dtype, realtype, compute_z):
+    seed(42)
+    pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+    n = 10
+    d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+    # test with singular matrix
+    d[0] = 0
+    e[0] = 0
+    d_pteqr, e_pteqr, z_pteqr, info = pteqr(d, e, z=z, compute_z=compute_z)
+    assert info > 0
+
+
+@pytest.mark.parametrize("compute_z,d,e,d_expect,z_expect",
+                         [(2,  # "I"
+                           np.array([4.16, 5.25, 1.09, .62]),
+                           np.array([3.17, -.97, .55]),
+                           np.array([8.0023, 1.9926, 1.0014, 0.1237]),
+                           np.array([[0.6326, 0.6245, -0.4191, 0.1847],
+                                     [0.7668, -0.4270, 0.4176, -0.2352],
+                                     [-0.1082, 0.6071, 0.4594, -0.6393],
+                                     [-0.0081, 0.2432, 0.6625, 0.7084]])),
+                          ])
+def test_pteqr_NAG_f08jgf(compute_z, d, e, d_expect, z_expect):
+    '''
+    Implements real (f08jgf) example from NAG Manual Mark 26.
+    Tests for correct outputs.
+    '''
+    # the NAG manual has 4 decimals accuracy
+    atol = 1e-4
+    pteqr = get_lapack_funcs(('pteqr'), dtype=d.dtype)
+
+    z = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+    _d, _e, _z, info = pteqr(d=d, e=e, z=z, compute_z=compute_z)
+    assert_allclose(_d, d_expect, atol=atol)
+    assert_allclose(np.abs(_z), np.abs(z_expect), atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('matrix_size', [(3, 4), (7, 6), (6, 6)])
+def test_geqrfp(dtype, matrix_size):
+    # Tests for all dytpes, tall, wide, and square matrices.
+    # Using the routine with random matrix A, Q and R are obtained and then
+    # tested such that R is upper triangular and non-negative on the diagonal,
+    # and Q is an orthogonal matrix. Verifies that A=Q@R. It also
+    # tests against a matrix that for which the  linalg.qr method returns
+    # negative diagonals, and for error messaging.
+
+    # set test tolerance appropriate for dtype
+    rng = np.random.RandomState(42)
+    rtol = 250*np.finfo(dtype).eps
+    atol = 100*np.finfo(dtype).eps
+    # get appropriate ?geqrfp for dtype
+    geqrfp = get_lapack_funcs(('geqrfp'), dtype=dtype)
+    gqr = get_lapack_funcs(("orgqr"), dtype=dtype)
+
+    m, n = matrix_size
+
+    # create random matrix of dimensions m x n
+    A = generate_random_dtype_array((m, n), dtype=dtype, rng=rng)
+    # create qr matrix using geqrfp
+    qr_A, tau, info = geqrfp(A)
+
+    # obtain r from the upper triangular area
+    r = np.triu(qr_A)
+
+    # obtain q from the orgqr lapack routine
+    # based on linalg.qr's extraction strategy of q with orgqr
+
+    if m > n:
+        # this adds an extra column to the end of qr_A
+        # let qqr be an empty m x m matrix
+        qqr = np.zeros((m, m), dtype=dtype)
+        # set first n columns of qqr to qr_A
+        qqr[:, :n] = qr_A
+        # determine q from this qqr
+        # note that m is a sufficient for lwork based on LAPACK documentation
+        q = gqr(qqr, tau=tau, lwork=m)[0]
+    else:
+        q = gqr(qr_A[:, :m], tau=tau, lwork=m)[0]
+
+    # test that q and r still make A
+    assert_allclose(q@r, A, rtol=rtol)
+    # ensure that q is orthogonal (that q @ transposed q is the identity)
+    assert_allclose(np.eye(q.shape[0]), q@(q.conj().T), rtol=rtol,
+                    atol=atol)
+    # ensure r is upper tri by comparing original r to r as upper triangular
+    assert_allclose(r, np.triu(r), rtol=rtol)
+    # make sure diagonals of r are positive for this random solution
+    assert_(np.all(np.diag(r) > np.zeros(len(np.diag(r)))))
+    # ensure that info is zero for this success
+    assert_(info == 0)
+
+    # test that this routine gives r diagonals that are positive for a
+    # matrix that returns negatives in the diagonal with scipy.linalg.rq
+    A_negative = generate_random_dtype_array((n, m), dtype=dtype, rng=rng) * -1
+    r_rq_neg, q_rq_neg = qr(A_negative)
+    rq_A_neg, tau_neg, info_neg = geqrfp(A_negative)
+    # assert that any of the entries on the diagonal from linalg.qr
+    #   are negative and that all of geqrfp are positive.
+    assert_(np.any(np.diag(r_rq_neg) < 0) and
+            np.all(np.diag(r) > 0))
+
+
+def test_geqrfp_errors_with_empty_array():
+    # check that empty array raises good error message
+    A_empty = np.array([])
+    geqrfp = get_lapack_funcs('geqrfp', dtype=A_empty.dtype)
+    assert_raises(Exception, geqrfp, A_empty)
+
+
+@pytest.mark.parametrize("driver", ['ev', 'evd', 'evr', 'evx'])
+@pytest.mark.parametrize("pfx", ['sy', 'he'])
+def test_standard_eigh_lworks(pfx, driver):
+    n = 1200  # Some sufficiently big arbitrary number
+    dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES
+    sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0])
+    dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1])
+    try:
+        _compute_lwork(sc_dlw, n, lower=1)
+        _compute_lwork(dz_dlw, n, lower=1)
+    except Exception as e:
+        pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}")
+
+
+@pytest.mark.parametrize("driver", ['gv', 'gvx'])
+@pytest.mark.parametrize("pfx", ['sy', 'he'])
+def test_generalized_eigh_lworks(pfx, driver):
+    n = 1200  # Some sufficiently big arbitrary number
+    dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES
+    sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0])
+    dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1])
+    # Shouldn't raise any exceptions
+    try:
+        _compute_lwork(sc_dlw, n, uplo="L")
+        _compute_lwork(dz_dlw, n, uplo="L")
+    except Exception as e:
+        pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}")
+
+
+@pytest.mark.parametrize("dtype_", DTYPES)
+@pytest.mark.parametrize("m", [1, 10, 100, 1000])
+def test_orcsd_uncsd_lwork(dtype_, m):
+    seed(1234)
+    p = randint(0, m)
+    q = m - p
+    pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
+    dlw = pfx + 'csd_lwork'
+    lw = get_lapack_funcs(dlw, dtype=dtype_)
+    lwval = _compute_lwork(lw, m, p, q)
+    lwval = lwval if pfx == 'un' else (lwval,)
+    assert all([x > 0 for x in lwval])
+
+
+@pytest.mark.parametrize("dtype_", DTYPES)
+def test_orcsd_uncsd(dtype_):
+    m, p, q = 250, 80, 170
+
+    pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
+    X = ortho_group.rvs(m) if pfx == 'or' else unitary_group.rvs(m)
+
+    drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), dtype=dtype_)
+    lwval = _compute_lwork(dlw, m, p, q)
+    lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork',
+                                                            'lrwork'], lwval))
+
+    cs11, cs12, cs21, cs22, theta, u1, u2, v1t, v2t, info =\
+        drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals)
+
+    assert info == 0
+
+    U = block_diag(u1, u2)
+    VH = block_diag(v1t, v2t)
+    r = min(min(p, q), min(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
+
+    S = np.zeros((m, m), dtype=dtype_)
+    one = dtype_(1.)
+    for i in range(n11):
+        S[i, i] = one
+    for i in range(n22):
+        S[p+i, q+i] = one
+    for i in range(n12):
+        S[i+n11+r, i+n11+r+n21+n22+r] = -one
+    for i in range(n21):
+        S[p+n22+r+i, n11+r+i] = one
+
+    for i in range(r):
+        S[i+n11, i+n11] = np.cos(theta[i])
+        S[p+n22+i, i+r+n21+n22] = np.cos(theta[i])
+
+        S[i+n11, i+n11+n21+n22+r] = -np.sin(theta[i])
+        S[p+n22+i, i+n11] = np.sin(theta[i])
+
+    Xc = U @ S @ VH
+    assert_allclose(X, Xc, rtol=0., atol=1e4*np.finfo(dtype_).eps)
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("trans_bool", [False, True])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx(dtype, trans_bool, fact):
+    """
+    These tests uses ?gtsvx to solve a random Ax=b system for each dtype.
+    It tests that the outputs define an LU matrix, that inputs are unmodified,
+    transposal options, incompatible shapes, singular matrices, and
+    singular factorizations. It parametrizes DTYPES and the 'fact' value along
+    with the fact related inputs.
+    """
+    rng = np.random.RandomState(42)
+    # set test tolerance appropriate for dtype
+    atol = 100 * np.finfo(dtype).eps
+    # obtain routine
+    gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+    # Generate random tridiagonal matrix A
+    n = 10
+    dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+    du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+    # generate random solution x
+    x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    # create b from x for equation Ax=b
+    trans = ("T" if dtype in REAL_DTYPES else "C") if trans_bool else "N"
+    b = (A.conj().T if trans_bool else A) @ x
+
+    # store a copy of the inputs to check they haven't been modified later
+    inputs_cpy = [dl.copy(), d.copy(), du.copy(), b.copy()]
+
+    # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+    dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+        gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+    gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+    dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+    assert_(info == 0, f"?gtsvx info = {info}, should be zero")
+
+    # assure that inputs are unmodified
+    assert_array_equal(dl, inputs_cpy[0])
+    assert_array_equal(d, inputs_cpy[1])
+    assert_array_equal(du, inputs_cpy[2])
+    assert_array_equal(b, inputs_cpy[3])
+
+    # test that x_soln matches the expected x
+    assert_allclose(x, x_soln, atol=atol)
+
+    # assert that the outputs are of correct type or shape
+    # rcond should be a scalar
+    assert_(hasattr(rcond, "__len__") is not True,
+            f"rcond should be scalar but is {rcond}")
+    # ferr should be length of # of cols in x
+    assert_(ferr.shape[0] == b.shape[1], (f"ferr.shape is {ferr.shape[0]} but should"
+                                          f" be {b.shape[1]}"))
+    # berr should be length of # of cols in x
+    assert_(berr.shape[0] == b.shape[1], (f"berr.shape is {berr.shape[0]} but should"
+                                          f" be {b.shape[1]}"))
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("trans_bool", [0, 1])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx_error_singular(dtype, trans_bool, fact):
+    rng = np.random.RandomState(42)
+    # obtain routine
+    gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+    # Generate random tridiagonal matrix A
+    n = 10
+    dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+    du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+    # generate random solution x
+    x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    # create b from x for equation Ax=b
+    trans = "T" if dtype in REAL_DTYPES else "C"
+    b = (A.conj().T if trans_bool else A) @ x
+
+    # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+    dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+        gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+    gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+    dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+    # test with singular matrix
+    # no need to test inputs with fact "F" since ?gttrf already does.
+    if fact == "N":
+        # Construct a singular example manually
+        d[-1] = 0
+        dl[-1] = 0
+        # solve using routine
+        gtsvx_out = gtsvx(dl, d, du, b)
+        dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+        # test for the singular matrix.
+        assert info > 0, "info should be > 0 for singular matrix"
+
+    elif fact == 'F':
+        # assuming that a singular factorization is input
+        df_[-1] = 0
+        duf_[-1] = 0
+        du2f_[-1] = 0
+
+        gtsvx_out = gtsvx(dl, d, du, b, fact=fact, dlf=dlf_, df=df_, duf=duf_,
+                          du2=du2f_, ipiv=ipiv_)
+        dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+        # info should not be zero and should provide index of illegal value
+        assert info > 0, "info should be > 0 for singular matrix"
+
+
+@pytest.mark.parametrize("dtype", DTYPES*2)
+@pytest.mark.parametrize("trans_bool", [False, True])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx_error_incompatible_size(dtype, trans_bool, fact):
+    rng = np.random.RandomState(42)
+    # obtain routine
+    gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+    # Generate random tridiagonal matrix A
+    n = 10
+    dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+    du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+    # generate random solution x
+    x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    # create b from x for equation Ax=b
+    trans = "T" if dtype in REAL_DTYPES else "C"
+    b = (A.conj().T if trans_bool else A) @ x
+
+    # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+    dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+        gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+    if fact == "N":
+        assert_raises(ValueError, gtsvx, dl[:-1], d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d[:-1], du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d, du[:-1], b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(Exception, gtsvx, dl, d, du, b[:-1],
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+    else:
+        assert_raises(ValueError, gtsvx, dl, d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_[:-1], df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_[:-1],
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_[:-1], du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_[:-1], ipiv=ipiv_)
+
+
+@pytest.mark.parametrize("du,d,dl,b,x",
+                         [(np.array([2.1, -1.0, 1.9, 8.0]),
+                           np.array([3.0, 2.3, -5.0, -0.9, 7.1]),
+                           np.array([3.4, 3.6, 7.0, -6.0]),
+                           np.array([[2.7, 6.6], [-.5, 10.8], [2.6, -3.2],
+                                     [.6, -11.2], [2.7, 19.1]]),
+                           np.array([[-4, 5], [7, -4], [3, -3], [-4, -2],
+                                     [-3, 1]])),
+                          (np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]),
+                           np.array([-1.3 + 1.3j, -1.3 + 1.3j, -1.3 + 3.3j,
+                                     -.3 + 4.3j, -3.3 + 1.3j]),
+                           np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]),
+                           np.array([[2.4 - 5j, 2.7 + 6.9j],
+                                     [3.4 + 18.2j, -6.9 - 5.3j],
+                                     [-14.7 + 9.7j, -6 - .6j],
+                                     [31.9 - 7.7j, -3.9 + 9.3j],
+                                     [-1 + 1.6j, -3 + 12.2j]]),
+                           np.array([[1 + 1j, 2 - 1j], [3 - 1j, 1 + 2j],
+                                     [4 + 5j, -1 + 1j], [-1 - 2j, 2 + 1j],
+                                     [1 - 1j, 2 - 2j]]))])
+def test_gtsvx_NAG(du, d, dl, b, x):
+    # Test to ensure wrapper is consistent with NAG Manual Mark 26
+    # example problems: real (f07cbf) and complex (f07cpf)
+    gtsvx = get_lapack_funcs('gtsvx', dtype=d.dtype)
+
+    gtsvx_out = gtsvx(dl, d, du, b)
+    dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+
+    assert_array_almost_equal(x, x_soln)
+
+
+@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
+                                               + REAL_DTYPES))
+@pytest.mark.parametrize("fact,df_de_lambda",
+                         [("F",
+                           lambda d, e: get_lapack_funcs('pttrf',
+                                                         dtype=e.dtype)(d, e)),
+                          ("N", lambda d, e: (None, None, None))])
+def test_ptsvx(dtype, realtype, fact, df_de_lambda):
+    '''
+    This tests the ?ptsvx lapack routine wrapper to solve a random system
+    Ax = b for all dtypes and input variations. Tests for: unmodified
+    input parameters, fact options, incompatible matrix shapes raise an error,
+    and singular matrices return info of illegal value.
+    '''
+    rng = np.random.RandomState(42)
+    # set test tolerance appropriate for dtype
+    atol = 100 * np.finfo(dtype).eps
+    ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+    n = 5
+    # create diagonals according to size and dtype
+    d = generate_random_dtype_array((n,), realtype, rng) + 4
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+    x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    b = A @ x_soln
+
+    # use lambda to determine what df, ef are
+    df, ef, info = df_de_lambda(d, e)
+
+    # create copy to later test that they are unmodified
+    diag_cpy = [d.copy(), e.copy(), b.copy()]
+
+    # solve using routine
+    df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact,
+                                               df=df, ef=ef)
+    # d, e, and b should be unmodified
+    assert_array_equal(d, diag_cpy[0])
+    assert_array_equal(e, diag_cpy[1])
+    assert_array_equal(b, diag_cpy[2])
+    assert_(info == 0, f"info should be 0 but is {info}.")
+    assert_array_almost_equal(x_soln, x)
+
+    # test that the factors from ptsvx can be recombined to make A
+    L = np.diag(ef, -1) + np.diag(np.ones(n))
+    D = np.diag(df)
+    assert_allclose(A, L@D@(np.conj(L).T), atol=atol)
+
+    # assert that the outputs are of correct type or shape
+    # rcond should be a scalar
+    assert not hasattr(rcond, "__len__"), \
+        f"rcond should be scalar but is {rcond}"
+    # ferr should be length of # of cols in x
+    assert_(ferr.shape == (2,), (f"ferr.shape is {ferr.shape} but should be "
+                                 "({x_soln.shape[1]},)"))
+    # berr should be length of # of cols in x
+    assert_(berr.shape == (2,), (f"berr.shape is {berr.shape} but should be "
+                                 "({x_soln.shape[1]},)"))
+
+
+@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
+                                               + REAL_DTYPES))
+@pytest.mark.parametrize("fact,df_de_lambda",
+                         [("F",
+                           lambda d, e: get_lapack_funcs('pttrf',
+                                                         dtype=e.dtype)(d, e)),
+                          ("N", lambda d, e: (None, None, None))])
+def test_ptsvx_error_raise_errors(dtype, realtype, fact, df_de_lambda):
+    rng = np.random.RandomState(42)
+    ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+    n = 5
+    # create diagonals according to size and dtype
+    d = generate_random_dtype_array((n,), realtype, rng) + 4
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+    x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    b = A @ x_soln
+
+    # use lambda to determine what df, ef are
+    df, ef, info = df_de_lambda(d, e)
+
+    # test with malformatted array sizes
+    assert_raises(ValueError, ptsvx, d[:-1], e, b, fact=fact, df=df, ef=ef)
+    assert_raises(ValueError, ptsvx, d, e[:-1], b, fact=fact, df=df, ef=ef)
+    assert_raises(Exception, ptsvx, d, e, b[:-1], fact=fact, df=df, ef=ef)
+
+
+@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
+                                               + REAL_DTYPES))
+@pytest.mark.parametrize("fact,df_de_lambda",
+                         [("F",
+                           lambda d, e: get_lapack_funcs('pttrf',
+                                                         dtype=e.dtype)(d, e)),
+                          ("N", lambda d, e: (None, None, None))])
+def test_ptsvx_non_SPD_singular(dtype, realtype, fact, df_de_lambda):
+    rng = np.random.RandomState(42)
+    ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+    n = 5
+    # create diagonals according to size and dtype
+    d = generate_random_dtype_array((n,), realtype, rng) + 4
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+    x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    b = A @ x_soln
+
+    # use lambda to determine what df, ef are
+    df, ef, info = df_de_lambda(d, e)
+
+    if fact == "N":
+        d[3] = 0
+        # obtain new df, ef
+        df, ef, info = df_de_lambda(d, e)
+        # solve using routine
+        df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b)
+        # test for the singular matrix.
+        assert info > 0 and info <= n
+
+        # non SPD matrix
+        d = generate_random_dtype_array((n,), realtype, rng)
+        df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b)
+        assert info > 0 and info <= n
+    else:
+        # assuming that someone is using a singular factorization
+        df, ef, info = df_de_lambda(d, e)
+        df[0] = 0
+        ef[0] = 0
+        df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact,
+                                                   df=df, ef=ef)
+        assert info > 0
+
+
+@pytest.mark.parametrize('d,e,b,x',
+                         [(np.array([4, 10, 29, 25, 5]),
+                           np.array([-2, -6, 15, 8]),
+                           np.array([[6, 10], [9, 4], [2, 9], [14, 65],
+                                     [7, 23]]),
+                           np.array([[2.5, 2], [2, -1], [1, -3],
+                                     [-1, 6], [3, -5]])),
+                          (np.array([16, 41, 46, 21]),
+                           np.array([16 + 16j, 18 - 9j, 1 - 4j]),
+                           np.array([[64 + 16j, -16 - 32j],
+                                     [93 + 62j, 61 - 66j],
+                                     [78 - 80j, 71 - 74j],
+                                     [14 - 27j, 35 + 15j]]),
+                           np.array([[2 + 1j, -3 - 2j],
+                                     [1 + 1j, 1 + 1j],
+                                     [1 - 2j, 1 - 2j],
+                                     [1 - 1j, 2 + 1j]]))])
+def test_ptsvx_NAG(d, e, b, x):
+    # test to assure that wrapper is consistent with NAG Manual Mark 26
+    # example problems: f07jbf, f07jpf
+    # (Links expire, so please search for "NAG Library Manual Mark 26" online)
+
+    # obtain routine with correct type based on e.dtype
+    ptsvx = get_lapack_funcs('ptsvx', dtype=e.dtype)
+    # solve using routine
+    df, ef, x_ptsvx, rcond, ferr, berr, info = ptsvx(d, e, b)
+    # determine ptsvx's solution and x are the same.
+    assert_array_almost_equal(x, x_ptsvx)
+
+
+@pytest.mark.parametrize('lower', [False, True])
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_pptrs_pptri_pptrf_ppsv_ppcon(dtype, lower):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+    # Manual conversion to/from packed format is feasible here.
+    n, nrhs = 10, 4
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+    b = generate_random_dtype_array([n, nrhs], dtype=dtype, rng=rng)
+
+    a = a.conj().T + a + np.eye(n, dtype=dtype) * dtype(5.)
+    if lower:
+        inds = ([x for y in range(n) for x in range(y, n)],
+                [y for y in range(n) for x in range(y, n)])
+    else:
+        inds = ([x for y in range(1, n+1) for x in range(y)],
+                [y-1 for y in range(1, n+1) for x in range(y)])
+    ap = a[inds]
+    ppsv, pptrf, pptrs, pptri, ppcon = get_lapack_funcs(
+        ('ppsv', 'pptrf', 'pptrs', 'pptri', 'ppcon'),
+        dtype=dtype,
+        ilp64="preferred")
+
+    ul, info = pptrf(n, ap, lower=lower)
+    assert_equal(info, 0)
+    aul = cholesky(a, lower=lower)[inds]
+    assert_allclose(ul, aul, rtol=0, atol=atol)
+
+    uli, info = pptri(n, ul, lower=lower)
+    assert_equal(info, 0)
+    auli = inv(a)[inds]
+    assert_allclose(uli, auli, rtol=0, atol=atol)
+
+    x, info = pptrs(n, ul, b, lower=lower)
+    assert_equal(info, 0)
+    bx = solve(a, b)
+    assert_allclose(x, bx, rtol=0, atol=atol)
+
+    xv, info = ppsv(n, ap, b, lower=lower)
+    assert_equal(info, 0)
+    assert_allclose(xv, bx, rtol=0, atol=atol)
+
+    anorm = np.linalg.norm(a, 1)
+    rcond, info = ppcon(n, ap, anorm=anorm, lower=lower)
+    assert_equal(info, 0)
+    assert_(abs(1/rcond - np.linalg.cond(a, p=1))*rcond < 1)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gees_trexc(dtype):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+
+    n = 10
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+    gees, trexc = get_lapack_funcs(('gees', 'trexc'), dtype=dtype)
+
+    result = gees(lambda x: None, a, overwrite_a=False)
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    z = result[-3]
+
+    d2 = t[6, 6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+    result = trexc(t, z, 7, 1)
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    z = result[-2]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+    assert_allclose(t[0, 0], d2, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+    "t, expect, ifst, ilst",
+    [(np.array([[0.80, -0.11, 0.01, 0.03],
+                [0.00, -0.10, 0.25, 0.35],
+                [0.00, -0.65, -0.10, 0.20],
+                [0.00, 0.00, 0.00, -0.10]]),
+      np.array([[-0.1000, -0.6463, 0.0874, 0.2010],
+                [0.2514, -0.1000, 0.0927, 0.3505],
+                [0.0000, 0.0000, 0.8000, -0.0117],
+                [0.0000, 0.0000, 0.0000, -0.1000]]),
+      2, 1),
+     (np.array([[-6.00 - 7.00j, 0.36 - 0.36j, -0.19 + 0.48j, 0.88 - 0.25j],
+                [0.00 + 0.00j, -5.00 + 2.00j, -0.03 - 0.72j, -0.23 + 0.13j],
+                [0.00 + 0.00j, 0.00 + 0.00j, 8.00 - 1.00j, 0.94 + 0.53j],
+                [0.00 + 0.00j, 0.00 + 0.00j, 0.00 + 0.00j, 3.00 - 4.00j]]),
+      np.array([[-5.0000 + 2.0000j, -0.1574 + 0.7143j,
+                 0.1781 - 0.1913j, 0.3950 + 0.3861j],
+                [0.0000 + 0.0000j, 8.0000 - 1.0000j,
+                 1.0742 + 0.1447j, 0.2515 - 0.3397j],
+                [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+                 3.0000 - 4.0000j, 0.2264 + 0.8962j],
+                [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+                 0.0000 + 0.0000j, -6.0000 - 7.0000j]]),
+      1, 4)])
+def test_trexc_NAG(t, ifst, ilst, expect):
+    """
+    This test implements the example found in the NAG manual,
+    f08qfc, f08qtc, f08qgc, f08quc.
+    """
+    # NAG manual provides accuracy up to 4 decimals
+    atol = 1e-4
+    trexc = get_lapack_funcs('trexc', dtype=t.dtype)
+
+    result = trexc(t, t, ifst, ilst, wantq=0)
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    assert_allclose(expect, t, atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gges_tgexc(dtype):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+
+    n = 10
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+    b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+    gges, tgexc = get_lapack_funcs(('gges', 'tgexc'), dtype=dtype)
+
+    result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False)
+    assert_equal(result[-1], 0)
+
+    s = result[0]
+    t = result[1]
+    q = result[-4]
+    z = result[-3]
+
+    d1 = s[0, 0] / t[0, 0]
+    d2 = s[6, 6] / t[6, 6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+    assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+    result = tgexc(s, t, q, z, 7, 1)
+    assert_equal(result[-1], 0)
+
+    s = result[0]
+    t = result[1]
+    q = result[2]
+    z = result[3]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+    assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+    assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol)
+    assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gees_trsen(dtype):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+
+    n = 10
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+    gees, trsen, trsen_lwork = get_lapack_funcs(
+        ('gees', 'trsen', 'trsen_lwork'), dtype=dtype)
+
+    result = gees(lambda x: None, a, overwrite_a=False)
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    z = result[-3]
+
+    d2 = t[6, 6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+    select = np.zeros(n)
+    select[6] = 1
+
+    lwork = _compute_lwork(trsen_lwork, select, t)
+
+    if dtype in COMPLEX_DTYPES:
+        result = trsen(select, t, z, lwork=lwork)
+    else:
+        result = trsen(select, t, z, lwork=lwork, liwork=lwork[1])
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    z = result[1]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+    assert_allclose(t[0, 0], d2, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+    "t, q, expect, select, expect_s, expect_sep",
+    [(np.array([[0.7995, -0.1144, 0.0060, 0.0336],
+                [0.0000, -0.0994, 0.2478, 0.3474],
+                [0.0000, -0.6483, -0.0994, 0.2026],
+                [0.0000, 0.0000, 0.0000, -0.1007]]),
+      np.array([[0.6551, 0.1037, 0.3450, 0.6641],
+                [0.5236, -0.5807, -0.6141, -0.1068],
+                [-0.5362, -0.3073, -0.2935, 0.7293],
+                [0.0956, 0.7467, -0.6463, 0.1249]]),
+      np.array([[0.3500, 0.4500, -0.1400, -0.1700],
+                [0.0900, 0.0700, -0.5399, 0.3500],
+                [-0.4400, -0.3300, -0.0300, 0.1700],
+                [0.2500, -0.3200, -0.1300, 0.1100]]),
+      np.array([1, 0, 0, 1]),
+      1.75e+00, 3.22e+00),
+     (np.array([[-6.0004 - 6.9999j, 0.3637 - 0.3656j,
+                 -0.1880 + 0.4787j, 0.8785 - 0.2539j],
+                [0.0000 + 0.0000j, -5.0000 + 2.0060j,
+                 -0.0307 - 0.7217j, -0.2290 + 0.1313j],
+                [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+                 7.9982 - 0.9964j, 0.9357 + 0.5359j],
+                [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+                 0.0000 + 0.0000j, 3.0023 - 3.9998j]]),
+      np.array([[-0.8347 - 0.1364j, -0.0628 + 0.3806j,
+                 0.2765 - 0.0846j, 0.0633 - 0.2199j],
+                [0.0664 - 0.2968j, 0.2365 + 0.5240j,
+                 -0.5877 - 0.4208j, 0.0835 + 0.2183j],
+                [-0.0362 - 0.3215j, 0.3143 - 0.5473j,
+                 0.0576 - 0.5736j, 0.0057 - 0.4058j],
+                [0.0086 + 0.2958j, -0.3416 - 0.0757j,
+                 -0.1900 - 0.1600j, 0.8327 - 0.1868j]]),
+      np.array([[-3.9702 - 5.0406j, -4.1108 + 3.7002j,
+                 -0.3403 + 1.0098j, 1.2899 - 0.8590j],
+                [0.3397 - 1.5006j, 1.5201 - 0.4301j,
+                 1.8797 - 5.3804j, 3.3606 + 0.6498j],
+                [3.3101 - 3.8506j, 2.4996 + 3.4504j,
+                 0.8802 - 1.0802j, 0.6401 - 1.4800j],
+                [-1.0999 + 0.8199j, 1.8103 - 1.5905j,
+                 3.2502 + 1.3297j, 1.5701 - 3.4397j]]),
+      np.array([1, 0, 0, 1]),
+      1.02e+00, 1.82e-01)])
+def test_trsen_NAG(t, q, select, expect, expect_s, expect_sep):
+    """
+    This test implements the example found in the NAG manual,
+    f08qgc, f08quc.
+    """
+    # NAG manual provides accuracy up to 4 and 2 decimals
+    atol = 1e-4
+    atol2 = 1e-2
+    trsen, trsen_lwork = get_lapack_funcs(
+        ('trsen', 'trsen_lwork'), dtype=t.dtype)
+
+    lwork = _compute_lwork(trsen_lwork, select, t)
+
+    if t.dtype in COMPLEX_DTYPES:
+        result = trsen(select, t, q, lwork=lwork)
+    else:
+        result = trsen(select, t, q, lwork=lwork, liwork=lwork[1])
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    q = result[1]
+    if t.dtype in COMPLEX_DTYPES:
+        s = result[4]
+        sep = result[5]
+    else:
+        s = result[5]
+        sep = result[6]
+
+    assert_allclose(expect, q @ t @ q.conj().T, atol=atol)
+    assert_allclose(expect_s, 1 / s, atol=atol2)
+    assert_allclose(expect_sep, 1 / sep, atol=atol2)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gges_tgsen(dtype):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+
+    n = 10
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+    b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+    gges, tgsen, tgsen_lwork = get_lapack_funcs(
+        ('gges', 'tgsen', 'tgsen_lwork'), dtype=dtype)
+
+    result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False)
+    assert_equal(result[-1], 0)
+
+    s = result[0]
+    t = result[1]
+    q = result[-4]
+    z = result[-3]
+
+    d1 = s[0, 0] / t[0, 0]
+    d2 = s[6, 6] / t[6, 6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+    assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+    select = np.zeros(n)
+    select[6] = 1
+
+    lwork = _compute_lwork(tgsen_lwork, select, s, t)
+
+    # off-by-one error in LAPACK, see gh-issue #13397
+    lwork = (lwork[0]+1, lwork[1])
+
+    result = tgsen(select, s, t, q, z, lwork=lwork)
+    assert_equal(result[-1], 0)
+
+    s = result[0]
+    t = result[1]
+    q = result[-7]
+    z = result[-6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+    assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+    assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol)
+    assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+    "a, b, c, d, e, f, rans, lans",
+    [(np.array([[4.0,   1.0,  1.0,  2.0],
+                [0.0,   3.0,  4.0,  1.0],
+                [0.0,   1.0,  3.0,  1.0],
+                [0.0,   0.0,  0.0,  6.0]]),
+      np.array([[1.0,   1.0,  1.0,  1.0],
+                [0.0,   3.0,  4.0,  1.0],
+                [0.0,   1.0,  3.0,  1.0],
+                [0.0,   0.0,  0.0,  4.0]]),
+      np.array([[-4.0,  7.0,  1.0, 12.0],
+                [-9.0,  2.0, -2.0, -2.0],
+                [-4.0,  2.0, -2.0,  8.0],
+                [-7.0,  7.0, -6.0, 19.0]]),
+      np.array([[2.0,   1.0,  1.0,  3.0],
+                [0.0,   1.0,  2.0,  1.0],
+                [0.0,   0.0,  1.0,  1.0],
+                [0.0,   0.0,  0.0,  2.0]]),
+      np.array([[1.0,   1.0,  1.0,  2.0],
+                [0.0,   1.0,  4.0,  1.0],
+                [0.0,   0.0,  1.0,  1.0],
+                [0.0,   0.0,  0.0,  1.0]]),
+      np.array([[-7.0,  5.0,  0.0,  7.0],
+                [-5.0,  1.0, -8.0,  0.0],
+                [-1.0,  2.0, -3.0,  5.0],
+                [-3.0,  2.0,  0.0,  5.0]]),
+      np.array([[1.0,   1.0,  1.0,  1.0],
+                [-1.0,  2.0, -1.0, -1.0],
+                [-1.0,  1.0,  3.0,  1.0],
+                [-1.0,  1.0, -1.0,  4.0]]),
+      np.array([[4.0,  -1.0,  1.0, -1.0],
+                [1.0,   3.0, -1.0,  1.0],
+                [-1.0,  1.0,  2.0, -1.0],
+                [1.0,  -1.0,  1.0,  1.0]]))])
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+def test_tgsyl_NAG(a, b, c, d, e, f, rans, lans, dtype):
+    atol = 1e-4
+
+    tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype)
+    rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f)
+
+    assert_equal(info, 0)
+    assert_allclose(scale, 1.0, rtol=0, atol=np.finfo(dtype).eps*100,
+                    err_msg="SCALE must be 1.0")
+    assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100,
+                    err_msg="DIF must be nearly 0")
+    assert_allclose(rout, rans, atol=atol,
+                    err_msg="Solution for R is incorrect")
+    assert_allclose(lout, lans, atol=atol,
+                    err_msg="Solution for L is incorrect")
+
+
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+@pytest.mark.parametrize('trans', ('N', 'T'))
+@pytest.mark.parametrize('ijob', [0, 1, 2, 3, 4])
+def test_tgsyl(dtype, trans, ijob):
+
+    atol = 1e-3 if dtype == np.float32 else 1e-10
+    rng = np.random.default_rng(1685779866898198)
+    m, n = 10, 15
+
+    a, d, *_ = qz(rng.uniform(-10, 10, [m, m]).astype(dtype),
+                  rng.uniform(-10, 10, [m, m]).astype(dtype),
+                  output='real')
+
+    b, e, *_ = qz(rng.uniform(-10, 10, [n, n]).astype(dtype),
+                  rng.uniform(-10, 10, [n, n]).astype(dtype),
+                  output='real')
+
+    c = rng.uniform(-2, 2, [m, n]).astype(dtype)
+    f = rng.uniform(-2, 2, [m, n]).astype(dtype)
+
+    tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype)
+    rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f,
+                                         trans=trans, ijob=ijob)
+
+    assert info == 0, "INFO is non-zero"
+    assert scale >= 0.0, "SCALE must be non-negative"
+    if ijob == 0:
+        assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100,
+                        err_msg="DIF must be 0 for ijob =0")
+    else:
+        assert dif >= 0.0, "DIF must be non-negative"
+
+    # Only DIF is calculated for ijob = 3/4
+    if ijob <= 2:
+        if trans == 'N':
+            lhs1 = a @ rout - lout @ b
+            rhs1 = scale*c
+            lhs2 = d @ rout - lout @ e
+            rhs2 = scale*f
+        elif trans == 'T':
+            lhs1 = np.transpose(a) @ rout + np.transpose(d) @ lout
+            rhs1 = scale*c
+            lhs2 = rout @ np.transpose(b) + lout @ np.transpose(e)
+            rhs2 = -1.0*scale*f
+
+        assert_allclose(lhs1, rhs1, atol=atol, rtol=0.,
+                        err_msg='lhs1 and rhs1 do not match')
+        assert_allclose(lhs2, rhs2, atol=atol, rtol=0.,
+                        err_msg='lhs2 and rhs2 do not match')
+
+
+@pytest.mark.parametrize('mtype', ['sy', 'he'])  # matrix type
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('lower', (0, 1))
+def test_sy_hetrs(mtype, dtype, lower):
+    if mtype == 'he' and dtype in REAL_DTYPES:
+        pytest.skip("hetrs not for real dtypes.")
+    rng = np.random.default_rng(1723059677121834)
+    n, nrhs = 20, 5
+    if dtype in COMPLEX_DTYPES:
+        A = (rng.uniform(size=(n, n)) + rng.uniform(size=(n, n))*1j).astype(dtype)
+    else:
+        A = rng.uniform(size=(n, n)).astype(dtype)
+
+    A = A + A.T if mtype == 'sy' else A + A.conj().T
+    b = rng.uniform(size=(n, nrhs)).astype(dtype)
+    names = f'{mtype}trf', f'{mtype}trf_lwork', f'{mtype}trs'
+    trf, trf_lwork, trs = get_lapack_funcs(names, dtype=dtype)
+    lwork = trf_lwork(n, lower=lower)
+    ldu, ipiv, info = trf(A, lwork=lwork)
+    assert info == 0
+    x, info = trs(a=ldu, ipiv=ipiv, b=b)
+    assert info == 0
+    eps = np.finfo(dtype).eps
+    assert_allclose(A@x, b, atol=100*n*eps)
+
+
+@pytest.mark.parametrize('norm', list('Mm1OoIiFfEe'))
+@pytest.mark.parametrize('uplo, m, n', [('U', 5, 10), ('U', 10, 10),
+                                        ('L', 10, 5), ('L', 10, 10)])
+@pytest.mark.parametrize('diag', ['N', 'U'])
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_lantr(norm, uplo, m, n, diag, dtype):
+    rng = np.random.default_rng(98426598246982456)
+    A = rng.random(size=(m, n)).astype(dtype)
+    lantr, lange = get_lapack_funcs(('lantr', 'lange'), (A,))
+    res = lantr(norm, A, uplo=uplo, diag=diag)
+
+    # now modify the matrix according to assumptions made by `lantr`
+    A = np.triu(A) if uplo == 'U' else np.tril(A)
+    if diag == 'U':
+        i = np.arange(min(m, n))
+        A[i, i] = 1
+    ref = lange(norm, A)
+
+    assert_allclose(res, ref, rtol=2e-6)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e87333c40b64d3f54024779dfb959be7a599178
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py
@@ -0,0 +1,1063 @@
+#
+# Created by: Pearu Peterson, March 2002
+#
+""" Test functions for linalg.matfuncs module
+
+"""
+import functools
+
+import numpy as np
+from numpy import array, identity, dot, sqrt
+from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_,
+                           assert_array_less, assert_array_equal, assert_warns)
+import pytest
+
+import scipy.linalg
+from scipy.linalg import (funm, signm, logm, sqrtm, fractional_matrix_power,
+                          expm, expm_frechet, expm_cond, norm, khatri_rao,
+                          cosm, sinm, tanm, coshm, sinhm, tanhm)
+from scipy.linalg import _matfuncs_inv_ssq
+from scipy.linalg._matfuncs import pick_pade_structure
+from scipy.linalg._matfuncs_inv_ssq import LogmExactlySingularWarning
+import scipy.linalg._expm_frechet
+
+from scipy.optimize import minimize
+
+
+def _get_al_mohy_higham_2012_experiment_1():
+    """
+    Return the test matrix from Experiment (1) of [1]_.
+
+    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
+
+    """
+    A = np.array([
+        [3.2346e-1, 3e4, 3e4, 3e4],
+        [0, 3.0089e-1, 3e4, 3e4],
+        [0, 0, 3.2210e-1, 3e4],
+        [0, 0, 0, 3.0744e-1]], dtype=float)
+    return A
+
+
+class TestSignM:
+
+    def test_nils(self):
+        a = array([[29.2, -24.2, 69.5, 49.8, 7.],
+                   [-9.2, 5.2, -18., -16.8, -2.],
+                   [-10., 6., -20., -18., -2.],
+                   [-9.6, 9.6, -25.5, -15.4, -2.],
+                   [9.8, -4.8, 18., 18.2, 2.]])
+        cr = array([[11.94933333,-2.24533333,15.31733333,21.65333333,-2.24533333],
+                    [-3.84266667,0.49866667,-4.59066667,-7.18666667,0.49866667],
+                    [-4.08,0.56,-4.92,-7.6,0.56],
+                    [-4.03466667,1.04266667,-5.59866667,-7.02666667,1.04266667],
+                    [4.15733333,-0.50133333,4.90933333,7.81333333,-0.50133333]])
+        r = signm(a)
+        assert_array_almost_equal(r,cr)
+
+    def test_defective1(self):
+        a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]])
+        signm(a, disp=False)
+        #XXX: what would be the correct result?
+
+    def test_defective2(self):
+        a = array((
+            [29.2,-24.2,69.5,49.8,7.0],
+            [-9.2,5.2,-18.0,-16.8,-2.0],
+            [-10.0,6.0,-20.0,-18.0,-2.0],
+            [-9.6,9.6,-25.5,-15.4,-2.0],
+            [9.8,-4.8,18.0,18.2,2.0]))
+        signm(a, disp=False)
+        #XXX: what would be the correct result?
+
+    def test_defective3(self):
+        a = array([[-2., 25., 0., 0., 0., 0., 0.],
+                   [0., -3., 10., 3., 3., 3., 0.],
+                   [0., 0., 2., 15., 3., 3., 0.],
+                   [0., 0., 0., 0., 15., 3., 0.],
+                   [0., 0., 0., 0., 3., 10., 0.],
+                   [0., 0., 0., 0., 0., -2., 25.],
+                   [0., 0., 0., 0., 0., 0., -3.]])
+        signm(a, disp=False)
+        #XXX: what would be the correct result?
+
+
+class TestLogM:
+
+    def test_nils(self):
+        a = array([[-2., 25., 0., 0., 0., 0., 0.],
+                   [0., -3., 10., 3., 3., 3., 0.],
+                   [0., 0., 2., 15., 3., 3., 0.],
+                   [0., 0., 0., 0., 15., 3., 0.],
+                   [0., 0., 0., 0., 3., 10., 0.],
+                   [0., 0., 0., 0., 0., -2., 25.],
+                   [0., 0., 0., 0., 0., 0., -3.]])
+        m = (identity(7)*3.1+0j)-a
+        logm(m, disp=False)
+        #XXX: what would be the correct result?
+
+    def test_al_mohy_higham_2012_experiment_1_logm(self):
+        # The logm completes the round trip successfully.
+        # Note that the expm leg of the round trip is badly conditioned.
+        A = _get_al_mohy_higham_2012_experiment_1()
+        A_logm, info = logm(A, disp=False)
+        A_round_trip = expm(A_logm)
+        assert_allclose(A_round_trip, A, rtol=5e-5, atol=1e-14)
+
+    def test_al_mohy_higham_2012_experiment_1_funm_log(self):
+        # The raw funm with np.log does not complete the round trip.
+        # Note that the expm leg of the round trip is badly conditioned.
+        A = _get_al_mohy_higham_2012_experiment_1()
+        A_funm_log, info = funm(A, np.log, disp=False)
+        A_round_trip = expm(A_funm_log)
+        assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14))
+
+    def test_round_trip_random_float(self):
+        np.random.seed(1234)
+        for n in range(1, 6):
+            M_unscaled = np.random.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+
+                # Eigenvalues are related to the branch cut.
+                W = np.linalg.eigvals(M)
+                err_msg = f'M:{M} eivals:{W}'
+
+                # Check sqrtm round trip because it is used within logm.
+                M_sqrtm, info = sqrtm(M, disp=False)
+                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+                assert_allclose(M_sqrtm_round_trip, M)
+
+                # Check logm round trip.
+                M_logm, info = logm(M, disp=False)
+                M_logm_round_trip = expm(M_logm)
+                assert_allclose(M_logm_round_trip, M, err_msg=err_msg)
+
+    def test_round_trip_random_complex(self):
+        np.random.seed(1234)
+        for n in range(1, 6):
+            M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_logm, info = logm(M, disp=False)
+                M_round_trip = expm(M_logm)
+                assert_allclose(M_round_trip, M)
+
+    def test_logm_type_preservation_and_conversion(self):
+        # The logm matrix function should preserve the type of a matrix
+        # whose eigenvalues are positive with zero imaginary part.
+        # Test this preservation for variously structured matrices.
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, 1]],
+                [[1, 0], [1, 1]],
+                [[2, 1], [1, 1]],
+                [[2, 3], [1, 2]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(not any(w.imag or w.real < 0 for w in W))
+
+            # check float type preservation
+            A = np.array(matrix_as_list, dtype=float)
+            A_logm, info = logm(A, disp=False)
+            assert_(A_logm.dtype.char not in complex_dtype_chars)
+
+            # check complex type preservation
+            A = np.array(matrix_as_list, dtype=complex)
+            A_logm, info = logm(A, disp=False)
+            assert_(A_logm.dtype.char in complex_dtype_chars)
+
+            # check float->complex type conversion for the matrix negation
+            A = -np.array(matrix_as_list, dtype=float)
+            A_logm, info = logm(A, disp=False)
+            assert_(A_logm.dtype.char in complex_dtype_chars)
+
+    def test_complex_spectrum_real_logm(self):
+        # This matrix has complex eigenvalues and real logm.
+        # Its output dtype depends on its input dtype.
+        M = [[1, 1, 2], [2, 1, 1], [1, 2, 1]]
+        for dt in float, complex:
+            X = np.array(M, dtype=dt)
+            w = scipy.linalg.eigvals(X)
+            assert_(1e-2 < np.absolute(w.imag).sum())
+            Y, info = logm(X, disp=False)
+            assert_(np.issubdtype(Y.dtype, np.inexact))
+            assert_allclose(expm(Y), X)
+
+    def test_real_mixed_sign_spectrum(self):
+        # These matrices have real eigenvalues with mixed signs.
+        # The output logm dtype is complex, regardless of input dtype.
+        for M in (
+                [[1, 0], [0, -1]],
+                [[0, 1], [1, 0]]):
+            for dt in float, complex:
+                A = np.array(M, dtype=dt)
+                A_logm, info = logm(A, disp=False)
+                assert_(np.issubdtype(A_logm.dtype, np.complexfloating))
+
+    @pytest.mark.thread_unsafe
+    def test_exactly_singular(self):
+        A = np.array([[0, 0], [1j, 1j]])
+        B = np.asarray([[1, 1], [0, 0]])
+        for M in A, A.T, B, B.T:
+            expected_warning = _matfuncs_inv_ssq.LogmExactlySingularWarning
+            L, info = assert_warns(expected_warning, logm, M, disp=False)
+            E = expm(L)
+            assert_allclose(E, M, atol=1e-14)
+
+    @pytest.mark.thread_unsafe
+    def test_nearly_singular(self):
+        M = np.array([[1e-100]])
+        expected_warning = _matfuncs_inv_ssq.LogmNearlySingularWarning
+        L, info = assert_warns(expected_warning, logm, M, disp=False)
+        E = expm(L)
+        assert_allclose(E, M, atol=1e-14)
+
+    def test_opposite_sign_complex_eigenvalues(self):
+        # See gh-6113
+        E = [[0, 1], [-1, 0]]
+        L = [[0, np.pi*0.5], [-np.pi*0.5, 0]]
+        assert_allclose(expm(L), E, atol=1e-14)
+        assert_allclose(logm(E), L, atol=1e-14)
+        E = [[1j, 4], [0, -1j]]
+        L = [[1j*np.pi*0.5, 2*np.pi], [0, -1j*np.pi*0.5]]
+        assert_allclose(expm(L), E, atol=1e-14)
+        assert_allclose(logm(E), L, atol=1e-14)
+        E = [[1j, 0], [0, -1j]]
+        L = [[1j*np.pi*0.5, 0], [0, -1j*np.pi*0.5]]
+        assert_allclose(expm(L), E, atol=1e-14)
+        assert_allclose(logm(E), L, atol=1e-14)
+
+    def test_readonly(self):
+        n = 5
+        a = np.ones((n, n)) + np.identity(n)
+        a.flags.writeable = False
+        logm(a)
+
+    @pytest.mark.xfail(reason="ValueError: attempt to get argmax of an empty sequence")
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        log_a = logm(a)
+        a0 = np.eye(2, dtype=dt)
+        log_a0 = logm(a0)
+
+        assert log_a.shape == (0, 0)
+        assert log_a.dtype == log_a0.dtype
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize('dtype', [int, float, np.float32, complex, np.complex64])
+    def test_no_ZeroDivisionError(self, dtype):
+        # gh-17136 reported inconsistent behavior in `logm` depending on input dtype:
+        # sometimes it raised an error, and sometimes it printed a warning message.
+        # check that this is resolved and that the warning is emitted properly.
+        with (pytest.warns(RuntimeWarning, match="logm result may be inaccurate"),
+              pytest.warns(LogmExactlySingularWarning)):
+            logm(np.zeros((2, 2), dtype=dtype))
+
+
+class TestSqrtM:
+    def test_round_trip_random_float(self):
+        rng = np.random.RandomState(1234)
+        for n in range(1, 6):
+            M_unscaled = rng.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_sqrtm, info = sqrtm(M, disp=False)
+                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+                assert_allclose(M_sqrtm_round_trip, M)
+
+    def test_round_trip_random_complex(self):
+        rng = np.random.RandomState(1234)
+        for n in range(1, 6):
+            M_unscaled = rng.randn(n, n) + 1j * rng.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_sqrtm, info = sqrtm(M, disp=False)
+                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+                assert_allclose(M_sqrtm_round_trip, M)
+
+    def test_bad(self):
+        # See https://web.archive.org/web/20051220232650/http://www.maths.man.ac.uk/~nareports/narep336.ps.gz
+        e = 2**-5
+        se = sqrt(e)
+        a = array([[1.0,0,0,1],
+                   [0,e,0,0],
+                   [0,0,e,0],
+                   [0,0,0,1]])
+        sa = array([[1,0,0,0.5],
+                    [0,se,0,0],
+                    [0,0,se,0],
+                    [0,0,0,1]])
+        n = a.shape[0]
+        assert_array_almost_equal(dot(sa,sa),a)
+        # Check default sqrtm.
+        esa = sqrtm(a, disp=False, blocksize=n)[0]
+        assert_array_almost_equal(dot(esa,esa),a)
+        # Check sqrtm with 2x2 blocks.
+        esa = sqrtm(a, disp=False, blocksize=2)[0]
+        assert_array_almost_equal(dot(esa,esa),a)
+
+    def test_sqrtm_type_preservation_and_conversion(self):
+        # The sqrtm matrix function should preserve the type of a matrix
+        # whose eigenvalues are nonnegative with zero imaginary part.
+        # Test this preservation for variously structured matrices.
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, 1]],
+                [[1, 0], [1, 1]],
+                [[2, 1], [1, 1]],
+                [[2, 3], [1, 2]],
+                [[1, 1], [1, 1]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(not any(w.imag or w.real < 0 for w in W))
+
+            # check float type preservation
+            A = np.array(matrix_as_list, dtype=float)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char not in complex_dtype_chars)
+
+            # check complex type preservation
+            A = np.array(matrix_as_list, dtype=complex)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+            # check float->complex type conversion for the matrix negation
+            A = -np.array(matrix_as_list, dtype=float)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+    def test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum(self):
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, -1]],
+                [[0, 1], [1, 0]],
+                [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(any(w.imag or w.real < 0 for w in W))
+
+            # check complex->complex
+            A = np.array(matrix_as_list, dtype=complex)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+            # check float->complex
+            A = np.array(matrix_as_list, dtype=float)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+    def test_blocksizes(self):
+        # Make sure I do not goof up the blocksizes when they do not divide n.
+        np.random.seed(1234)
+        for n in range(1, 8):
+            A = np.random.rand(n, n) + 1j*np.random.randn(n, n)
+            A_sqrtm_default, info = sqrtm(A, disp=False, blocksize=n)
+            assert_allclose(A, np.linalg.matrix_power(A_sqrtm_default, 2))
+            for blocksize in range(1, 10):
+                A_sqrtm_new, info = sqrtm(A, disp=False, blocksize=blocksize)
+                assert_allclose(A_sqrtm_default, A_sqrtm_new)
+
+    def test_al_mohy_higham_2012_experiment_1(self):
+        # Matrix square root of a tricky upper triangular matrix.
+        A = _get_al_mohy_higham_2012_experiment_1()
+        A_sqrtm, info = sqrtm(A, disp=False)
+        A_round_trip = A_sqrtm.dot(A_sqrtm)
+        assert_allclose(A_round_trip, A, rtol=1e-5)
+        assert_allclose(np.tril(A_round_trip), np.tril(A))
+
+    def test_strict_upper_triangular(self):
+        # This matrix has no square root.
+        for dt in int, float:
+            A = np.array([
+                [0, 3, 0, 0],
+                [0, 0, 3, 0],
+                [0, 0, 0, 3],
+                [0, 0, 0, 0]], dtype=dt)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(np.isnan(A_sqrtm).all())
+
+    def test_weird_matrix(self):
+        # The square root of matrix B exists.
+        for dt in int, float:
+            A = np.array([
+                [0, 0, 1],
+                [0, 0, 0],
+                [0, 1, 0]], dtype=dt)
+            B = np.array([
+                [0, 1, 0],
+                [0, 0, 0],
+                [0, 0, 0]], dtype=dt)
+            assert_array_equal(B, A.dot(A))
+
+            # But scipy sqrtm is not clever enough to find it.
+            B_sqrtm, info = sqrtm(B, disp=False)
+            assert_(np.isnan(B_sqrtm).all())
+
+    def test_disp(self):
+        np.random.seed(1234)
+
+        A = np.random.rand(3, 3)
+        B = sqrtm(A, disp=True)
+        assert_allclose(B.dot(B), A)
+
+    def test_opposite_sign_complex_eigenvalues(self):
+        M = [[2j, 4], [0, -2j]]
+        R = [[1+1j, 2], [0, 1-1j]]
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    def test_gh4866(self):
+        M = np.array([[1, 0, 0, 1],
+                      [0, 0, 0, 0],
+                      [0, 0, 0, 0],
+                      [1, 0, 0, 1]])
+        R = np.array([[sqrt(0.5), 0, 0, sqrt(0.5)],
+                      [0, 0, 0, 0],
+                      [0, 0, 0, 0],
+                      [sqrt(0.5), 0, 0, sqrt(0.5)]])
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    def test_gh5336(self):
+        M = np.diag([2, 1, 0])
+        R = np.diag([sqrt(2), 1, 0])
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    def test_gh7839(self):
+        M = np.zeros((2, 2))
+        R = np.zeros((2, 2))
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    @pytest.mark.xfail(reason="failing on macOS after gh-20212")
+    def test_gh17918(self):
+        M = np.empty((19, 19))
+        M.fill(0.94)
+        np.fill_diagonal(M, 1)
+        assert np.isrealobj(sqrtm(M))
+
+    def test_data_size_preservation_uint_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.uint8)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint16)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint32)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint64)
+        assert sqrtm(M).dtype == np.float64
+
+    def test_data_size_preservation_int_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.int8)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.int16)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.int32)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.int64)
+        assert sqrtm(M).dtype == np.float64
+
+    def test_data_size_preservation_int_in_comp_out(self):
+        M = np.array([[2, 4], [0, -2]], dtype=np.int8)
+        assert sqrtm(M).dtype == np.complex128
+        M = np.array([[2, 4], [0, -2]], dtype=np.int16)
+        assert sqrtm(M).dtype == np.complex128
+        M = np.array([[2, 4], [0, -2]], dtype=np.int32)
+        assert sqrtm(M).dtype == np.complex128
+        M = np.array([[2, 4], [0, -2]], dtype=np.int64)
+        assert sqrtm(M).dtype == np.complex128
+
+    def test_data_size_preservation_float_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.float16)
+        assert sqrtm(M).dtype == np.float32
+        M = np.zeros((10, 10), dtype=np.float32)
+        assert sqrtm(M).dtype == np.float32
+        M = np.zeros((10, 10), dtype=np.float64)
+        assert sqrtm(M).dtype == np.float64
+        if hasattr(np, 'float128'):
+            M = np.zeros((10, 10), dtype=np.float128)
+            assert sqrtm(M).dtype == np.float64
+
+    def test_data_size_preservation_float_in_comp_out(self):
+        M = np.array([[2, 4], [0, -2]], dtype=np.float16)
+        assert sqrtm(M).dtype == np.complex64
+        M = np.array([[2, 4], [0, -2]], dtype=np.float32)
+        assert sqrtm(M).dtype == np.complex64
+        M = np.array([[2, 4], [0, -2]], dtype=np.float64)
+        assert sqrtm(M).dtype == np.complex128
+        if hasattr(np, 'float128') and hasattr(np, 'complex256'):
+            M = np.array([[2, 4], [0, -2]], dtype=np.float128)
+            assert sqrtm(M).dtype == np.complex128
+
+    def test_data_size_preservation_comp_in_comp_out(self):
+        M = np.array([[2j, 4], [0, -2j]], dtype=np.complex64)
+        assert sqrtm(M).dtype == np.complex64
+        M = np.array([[2j, 4], [0, -2j]], dtype=np.complex128)
+        assert sqrtm(M).dtype == np.complex128
+        if hasattr(np, 'complex256'):
+            M = np.array([[2j, 4], [0, -2j]], dtype=np.complex256)
+            assert sqrtm(M).dtype == np.complex128
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        s = sqrtm(a)
+        a0 = np.eye(2, dtype=dt)
+        s0 = sqrtm(a0)
+
+        assert s.shape == (0, 0)
+        assert s.dtype == s0.dtype
+
+
+class TestFractionalMatrixPower:
+    def test_round_trip_random_complex(self):
+        np.random.seed(1234)
+        for p in range(1, 5):
+            for n in range(1, 5):
+                M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n)
+                for scale in np.logspace(-4, 4, 9):
+                    M = M_unscaled * scale
+                    M_root = fractional_matrix_power(M, 1/p)
+                    M_round_trip = np.linalg.matrix_power(M_root, p)
+                    assert_allclose(M_round_trip, M)
+
+    def test_round_trip_random_float(self):
+        # This test is more annoying because it can hit the branch cut;
+        # this happens when the matrix has an eigenvalue
+        # with no imaginary component and with a real negative component,
+        # and it means that the principal branch does not exist.
+        np.random.seed(1234)
+        for p in range(1, 5):
+            for n in range(1, 5):
+                M_unscaled = np.random.randn(n, n)
+                for scale in np.logspace(-4, 4, 9):
+                    M = M_unscaled * scale
+                    M_root = fractional_matrix_power(M, 1/p)
+                    M_round_trip = np.linalg.matrix_power(M_root, p)
+                    assert_allclose(M_round_trip, M)
+
+    def test_larger_abs_fractional_matrix_powers(self):
+        np.random.seed(1234)
+        for n in (2, 3, 5):
+            for i in range(10):
+                M = np.random.randn(n, n) + 1j * np.random.randn(n, n)
+                M_one_fifth = fractional_matrix_power(M, 0.2)
+                # Test the round trip.
+                M_round_trip = np.linalg.matrix_power(M_one_fifth, 5)
+                assert_allclose(M, M_round_trip)
+                # Test a large abs fractional power.
+                X = fractional_matrix_power(M, -5.4)
+                Y = np.linalg.matrix_power(M_one_fifth, -27)
+                assert_allclose(X, Y)
+                # Test another large abs fractional power.
+                X = fractional_matrix_power(M, 3.8)
+                Y = np.linalg.matrix_power(M_one_fifth, 19)
+                assert_allclose(X, Y)
+
+    def test_random_matrices_and_powers(self):
+        # Each independent iteration of this fuzz test picks random parameters.
+        # It tries to hit some edge cases.
+        rng = np.random.default_rng(1726500458620605)
+        nsamples = 20
+        for i in range(nsamples):
+            # Sample a matrix size and a random real power.
+            n = rng.integers(1, 5)
+            p = rng.random()
+
+            # Sample a random real or complex matrix.
+            matrix_scale = np.exp(rng.integers(-4, 5))
+            A = rng.random(size=[n, n])
+            if [True, False][rng.choice(2)]:
+                A = A + 1j * rng.random(size=[n, n])
+            A = A * matrix_scale
+
+            # Check a couple of analytically equivalent ways
+            # to compute the fractional matrix power.
+            # These can be compared because they both use the principal branch.
+            A_power = fractional_matrix_power(A, p)
+            A_logm, info = logm(A, disp=False)
+            A_power_expm_logm = expm(A_logm * p)
+            assert_allclose(A_power, A_power_expm_logm)
+
+    def test_al_mohy_higham_2012_experiment_1(self):
+        # Fractional powers of a tricky upper triangular matrix.
+        A = _get_al_mohy_higham_2012_experiment_1()
+
+        # Test remainder matrix power.
+        A_funm_sqrt, info = funm(A, np.sqrt, disp=False)
+        A_sqrtm, info = sqrtm(A, disp=False)
+        A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5)
+        A_power = fractional_matrix_power(A, 0.5)
+        assert_allclose(A_rem_power, A_power, rtol=1e-11)
+        assert_allclose(A_sqrtm, A_power)
+        assert_allclose(A_sqrtm, A_funm_sqrt)
+
+        # Test more fractional powers.
+        for p in (1/2, 5/3):
+            A_power = fractional_matrix_power(A, p)
+            A_round_trip = fractional_matrix_power(A_power, 1/p)
+            assert_allclose(A_round_trip, A, rtol=1e-2)
+            assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1))
+
+    def test_briggs_helper_function(self):
+        np.random.seed(1234)
+        for a in np.random.randn(10) + 1j * np.random.randn(10):
+            for k in range(5):
+                x_observed = _matfuncs_inv_ssq._briggs_helper_function(a, k)
+                x_expected = a ** np.exp2(-k) - 1
+                assert_allclose(x_observed, x_expected)
+
+    def test_type_preservation_and_conversion(self):
+        # The fractional_matrix_power matrix function should preserve
+        # the type of a matrix whose eigenvalues
+        # are positive with zero imaginary part.
+        # Test this preservation for variously structured matrices.
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, 1]],
+                [[1, 0], [1, 1]],
+                [[2, 1], [1, 1]],
+                [[2, 3], [1, 2]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(not any(w.imag or w.real < 0 for w in W))
+
+            # Check various positive and negative powers
+            # with absolute values bigger and smaller than 1.
+            for p in (-2.4, -0.9, 0.2, 3.3):
+
+                # check float type preservation
+                A = np.array(matrix_as_list, dtype=float)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char not in complex_dtype_chars)
+
+                # check complex type preservation
+                A = np.array(matrix_as_list, dtype=complex)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char in complex_dtype_chars)
+
+                # check float->complex for the matrix negation
+                A = -np.array(matrix_as_list, dtype=float)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char in complex_dtype_chars)
+
+    def test_type_conversion_mixed_sign_or_complex_spectrum(self):
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, -1]],
+                [[0, 1], [1, 0]],
+                [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(any(w.imag or w.real < 0 for w in W))
+
+            # Check various positive and negative powers
+            # with absolute values bigger and smaller than 1.
+            for p in (-2.4, -0.9, 0.2, 3.3):
+
+                # check complex->complex
+                A = np.array(matrix_as_list, dtype=complex)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char in complex_dtype_chars)
+
+                # check float->complex
+                A = np.array(matrix_as_list, dtype=float)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char in complex_dtype_chars)
+
+    @pytest.mark.xfail(reason='Too unstable across LAPACKs.')
+    def test_singular(self):
+        # Negative fractional powers do not work with singular matrices.
+        for matrix_as_list in (
+                [[0, 0], [0, 0]],
+                [[1, 1], [1, 1]],
+                [[1, 2], [3, 6]],
+                [[0, 0, 0], [0, 1, 1], [0, -1, 1]]):
+
+            # Check fractional powers both for float and for complex types.
+            for newtype in (float, complex):
+                A = np.array(matrix_as_list, dtype=newtype)
+                for p in (-0.7, -0.9, -2.4, -1.3):
+                    A_power = fractional_matrix_power(A, p)
+                    assert_(np.isnan(A_power).all())
+                for p in (0.2, 1.43):
+                    A_power = fractional_matrix_power(A, p)
+                    A_round_trip = fractional_matrix_power(A_power, 1/p)
+                    assert_allclose(A_round_trip, A)
+
+    def test_opposite_sign_complex_eigenvalues(self):
+        M = [[2j, 4], [0, -2j]]
+        R = [[1+1j, 2], [0, 1-1j]]
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(fractional_matrix_power(M, 0.5), R, atol=1e-14)
+
+
+class TestExpM:
+    def test_zero(self):
+        a = array([[0.,0],[0,0]])
+        assert_array_almost_equal(expm(a),[[1,0],[0,1]])
+
+    def test_single_elt(self):
+        elt = expm(1)
+        assert_allclose(elt, np.array([[np.e]]))
+
+    @pytest.mark.parametrize('func', [expm, cosm, sinm, tanm, coshm, sinhm, tanhm])
+    @pytest.mark.parametrize('dt',[int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('shape', [(0, 0), (1, 1)])
+    def test_small_empty_matrix_input(self, func, dt, shape):
+        # regression test for gh-11082 / gh-20372 - test behavior of expm
+        # and related functions for small and zero-sized arrays.
+        A = np.zeros(shape, dtype=dt)
+        A0 = np.zeros((10, 10), dtype=dt)
+        result = func(A)
+        result0 = func(A0)
+        assert result.shape == shape
+        assert result.dtype == result0.dtype
+
+    def test_2x2_input(self):
+        E = np.e
+        a = array([[1, 4], [1, 1]])
+        aa = (E**4 + 1)/(2*E)
+        bb = (E**4 - 1)/E
+        assert_allclose(expm(a), array([[aa, bb], [bb/4, aa]]))
+        assert expm(a.astype(np.complex64)).dtype.char == 'F'
+        assert expm(a.astype(np.float32)).dtype.char == 'f'
+
+    def test_nx2x2_input(self):
+        E = np.e
+        # These are integer matrices with integer eigenvalues
+        a = np.array([[[1, 4], [1, 1]],
+                      [[1, 3], [1, -1]],
+                      [[1, 3], [4, 5]],
+                      [[1, 3], [5, 3]],
+                      [[4, 5], [-3, -4]]], order='F')
+        # Exact results are computed symbolically
+        a_res = np.array([
+                          [[(E**4+1)/(2*E), (E**4-1)/E],
+                           [(E**4-1)/4/E, (E**4+1)/(2*E)]],
+                          [[1/(4*E**2)+(3*E**2)/4, (3*E**2)/4-3/(4*E**2)],
+                           [E**2/4-1/(4*E**2), 3/(4*E**2)+E**2/4]],
+                          [[3/(4*E)+E**7/4, -3/(8*E)+(3*E**7)/8],
+                           [-1/(2*E)+E**7/2, 1/(4*E)+(3*E**7)/4]],
+                          [[5/(8*E**2)+(3*E**6)/8, -3/(8*E**2)+(3*E**6)/8],
+                           [-5/(8*E**2)+(5*E**6)/8, 3/(8*E**2)+(5*E**6)/8]],
+                          [[-3/(2*E)+(5*E)/2, -5/(2*E)+(5*E)/2],
+                           [3/(2*E)-(3*E)/2, 5/(2*E)-(3*E)/2]]
+                         ])
+        assert_allclose(expm(a), a_res)
+
+    def test_readonly(self):
+        n = 7
+        a = np.ones((n, n))
+        a.flags.writeable = False
+        expm(a)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.fail_slow(5)
+    def test_gh18086(self):
+        A = np.zeros((400, 400), dtype=float)
+        rng = np.random.default_rng(100)
+        i = rng.integers(0, 399, 500)
+        j = rng.integers(0, 399, 500)
+        A[i, j] = rng.random(500)
+        # Problem appears when m = 9
+        Am = np.empty((5, 400, 400), dtype=float)
+        Am[0] = A.copy()
+        m, s = pick_pade_structure(Am)
+        assert m == 9
+        # Check that result is accurate
+        first_res = expm(A)
+        np.testing.assert_array_almost_equal(logm(first_res), A)
+        # Check that result is consistent
+        for i in range(5):
+            next_res = expm(A)
+            np.testing.assert_array_almost_equal(first_res, next_res)
+
+
+class TestExpmFrechet:
+
+    def test_expm_frechet(self):
+        # a test of the basic functionality
+        M = np.array([
+            [1, 2, 3, 4],
+            [5, 6, 7, 8],
+            [0, 0, 1, 2],
+            [0, 0, 5, 6],
+            ], dtype=float)
+        A = np.array([
+            [1, 2],
+            [5, 6],
+            ], dtype=float)
+        E = np.array([
+            [3, 4],
+            [7, 8],
+            ], dtype=float)
+        expected_expm = scipy.linalg.expm(A)
+        expected_frechet = scipy.linalg.expm(M)[:2, 2:]
+        for kwargs in ({}, {'method':'SPS'}, {'method':'blockEnlarge'}):
+            observed_expm, observed_frechet = expm_frechet(A, E, **kwargs)
+            assert_allclose(expected_expm, observed_expm)
+            assert_allclose(expected_frechet, observed_frechet)
+
+    def test_small_norm_expm_frechet(self):
+        # methodically test matrices with a range of norms, for better coverage
+        M_original = np.array([
+            [1, 2, 3, 4],
+            [5, 6, 7, 8],
+            [0, 0, 1, 2],
+            [0, 0, 5, 6],
+            ], dtype=float)
+        A_original = np.array([
+            [1, 2],
+            [5, 6],
+            ], dtype=float)
+        E_original = np.array([
+            [3, 4],
+            [7, 8],
+            ], dtype=float)
+        A_original_norm_1 = scipy.linalg.norm(A_original, 1)
+        selected_m_list = [1, 3, 5, 7, 9, 11, 13, 15]
+        m_neighbor_pairs = zip(selected_m_list[:-1], selected_m_list[1:])
+        for ma, mb in m_neighbor_pairs:
+            ell_a = scipy.linalg._expm_frechet.ell_table_61[ma]
+            ell_b = scipy.linalg._expm_frechet.ell_table_61[mb]
+            target_norm_1 = 0.5 * (ell_a + ell_b)
+            scale = target_norm_1 / A_original_norm_1
+            M = scale * M_original
+            A = scale * A_original
+            E = scale * E_original
+            expected_expm = scipy.linalg.expm(A)
+            expected_frechet = scipy.linalg.expm(M)[:2, 2:]
+            observed_expm, observed_frechet = expm_frechet(A, E)
+            assert_allclose(expected_expm, observed_expm)
+            assert_allclose(expected_frechet, observed_frechet)
+
+    def test_fuzz(self):
+        rng = np.random.default_rng(1726500908359153)
+        # try a bunch of crazy inputs
+        rfuncs = (
+                np.random.uniform,
+                np.random.normal,
+                np.random.standard_cauchy,
+                np.random.exponential)
+        ntests = 100
+        for i in range(ntests):
+            rfunc = rfuncs[rng.choice(4)]
+            target_norm_1 = rng.exponential()
+            n = rng.integers(2, 16)
+            A_original = rfunc(size=(n,n))
+            E_original = rfunc(size=(n,n))
+            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
+            scale = target_norm_1 / A_original_norm_1
+            A = scale * A_original
+            E = scale * E_original
+            M = np.vstack([
+                np.hstack([A, E]),
+                np.hstack([np.zeros_like(A), A])])
+            expected_expm = scipy.linalg.expm(A)
+            expected_frechet = scipy.linalg.expm(M)[:n, n:]
+            observed_expm, observed_frechet = expm_frechet(A, E)
+            assert_allclose(expected_expm, observed_expm, atol=5e-8)
+            assert_allclose(expected_frechet, observed_frechet, atol=1e-7)
+
+    def test_problematic_matrix(self):
+        # this test case uncovered a bug which has since been fixed
+        A = np.array([
+                [1.50591997, 1.93537998],
+                [0.41203263, 0.23443516],
+                ], dtype=float)
+        E = np.array([
+                [1.87864034, 2.07055038],
+                [1.34102727, 0.67341123],
+                ], dtype=float)
+        scipy.linalg.norm(A, 1)
+        sps_expm, sps_frechet = expm_frechet(
+                A, E, method='SPS')
+        blockEnlarge_expm, blockEnlarge_frechet = expm_frechet(
+                A, E, method='blockEnlarge')
+        assert_allclose(sps_expm, blockEnlarge_expm)
+        assert_allclose(sps_frechet, blockEnlarge_frechet)
+
+    @pytest.mark.slow
+    @pytest.mark.skip(reason='this test is deliberately slow')
+    def test_medium_matrix(self):
+        # profile this to see the speed difference
+        n = 1000
+        A = np.random.exponential(size=(n, n))
+        E = np.random.exponential(size=(n, n))
+        sps_expm, sps_frechet = expm_frechet(
+                A, E, method='SPS')
+        blockEnlarge_expm, blockEnlarge_frechet = expm_frechet(
+                A, E, method='blockEnlarge')
+        assert_allclose(sps_expm, blockEnlarge_expm)
+        assert_allclose(sps_frechet, blockEnlarge_frechet)
+
+
+def _help_expm_cond_search(A, A_norm, X, X_norm, eps, p):
+    p = np.reshape(p, A.shape)
+    p_norm = norm(p)
+    perturbation = eps * p * (A_norm / p_norm)
+    X_prime = expm(A + perturbation)
+    scaled_relative_error = norm(X_prime - X) / (X_norm * eps)
+    return -scaled_relative_error
+
+
+def _normalized_like(A, B):
+    return A * (scipy.linalg.norm(B) / scipy.linalg.norm(A))
+
+
+def _relative_error(f, A, perturbation):
+    X = f(A)
+    X_prime = f(A + perturbation)
+    return norm(X_prime - X) / norm(X)
+
+
+class TestExpmConditionNumber:
+    def test_expm_cond_smoke(self):
+        np.random.seed(1234)
+        for n in range(1, 4):
+            A = np.random.randn(n, n)
+            kappa = expm_cond(A)
+            assert_array_less(0, kappa)
+
+    def test_expm_bad_condition_number(self):
+        A = np.array([
+            [-1.128679820, 9.614183771e4, -4.524855739e9, 2.924969411e14],
+            [0, -1.201010529, 9.634696872e4, -4.681048289e9],
+            [0, 0, -1.132893222, 9.532491830e4],
+            [0, 0, 0, -1.179475332],
+            ])
+        kappa = expm_cond(A)
+        assert_array_less(1e36, kappa)
+
+    def test_univariate(self):
+        np.random.seed(12345)
+        for x in np.linspace(-5, 5, num=11):
+            A = np.array([[x]])
+            assert_allclose(expm_cond(A), abs(x))
+        for x in np.logspace(-2, 2, num=11):
+            A = np.array([[x]])
+            assert_allclose(expm_cond(A), abs(x))
+        for i in range(10):
+            A = np.random.randn(1, 1)
+            assert_allclose(expm_cond(A), np.absolute(A)[0, 0])
+
+    @pytest.mark.slow
+    def test_expm_cond_fuzz(self):
+        rng = np.random.RandomState(12345)
+        eps = 1e-5
+        nsamples = 10
+        for i in range(nsamples):
+            n = rng.randint(2, 5)
+            A = rng.randn(n, n)
+            A_norm = scipy.linalg.norm(A)
+            X = expm(A)
+            X_norm = scipy.linalg.norm(X)
+            kappa = expm_cond(A)
+
+            # Look for the small perturbation that gives the greatest
+            # relative error.
+            f = functools.partial(_help_expm_cond_search,
+                    A, A_norm, X, X_norm, eps)
+            guess = np.ones(n*n)
+            out = minimize(f, guess, method='L-BFGS-B')
+            xopt = out.x
+            yopt = f(xopt)
+            p_best = eps * _normalized_like(np.reshape(xopt, A.shape), A)
+            p_best_relerr = _relative_error(expm, A, p_best)
+            assert_allclose(p_best_relerr, -yopt * eps)
+
+            # Check that the identified perturbation indeed gives greater
+            # relative error than random perturbations with similar norms.
+            for j in range(5):
+                p_rand = eps * _normalized_like(rng.randn(*A.shape), A)
+                assert_allclose(norm(p_best), norm(p_rand))
+                p_rand_relerr = _relative_error(expm, A, p_rand)
+                assert_array_less(p_rand_relerr, p_best_relerr)
+
+            # The greatest relative error should not be much greater than
+            # eps times the condition number kappa.
+            # In the limit as eps approaches zero it should never be greater.
+            assert_array_less(p_best_relerr, (1 + 2*eps) * eps * kappa)
+
+
+class TestKhatriRao:
+
+    def test_basic(self):
+        a = khatri_rao(array([[1, 2], [3, 4]]),
+                       array([[5, 6], [7, 8]]))
+
+        assert_array_equal(a, array([[5, 12],
+                                     [7, 16],
+                                     [15, 24],
+                                     [21, 32]]))
+
+        b = khatri_rao(np.empty([2, 2]), np.empty([2, 2]))
+        assert_array_equal(b.shape, (4, 2))
+
+    def test_number_of_columns_equality(self):
+        with pytest.raises(ValueError):
+            a = array([[1, 2, 3],
+                       [4, 5, 6]])
+            b = array([[1, 2],
+                       [3, 4]])
+            khatri_rao(a, b)
+
+    def test_to_assure_2d_array(self):
+        with pytest.raises(ValueError):
+            # both arrays are 1-D
+            a = array([1, 2, 3])
+            b = array([4, 5, 6])
+            khatri_rao(a, b)
+
+        with pytest.raises(ValueError):
+            # first array is 1-D
+            a = array([1, 2, 3])
+            b = array([
+                [1, 2, 3],
+                [4, 5, 6]
+            ])
+            khatri_rao(a, b)
+
+        with pytest.raises(ValueError):
+            # second array is 1-D
+            a = array([
+                [1, 2, 3],
+                [7, 8, 9]
+            ])
+            b = array([4, 5, 6])
+            khatri_rao(a, b)
+
+    def test_equality_of_two_equations(self):
+        a = array([[1, 2], [3, 4]])
+        b = array([[5, 6], [7, 8]])
+
+        res1 = khatri_rao(a, b)
+        res2 = np.vstack([np.kron(a[:, k], b[:, k])
+                          for k in range(b.shape[1])]).T
+
+        assert_array_equal(res1, res2)
+
+    def test_empty(self):
+        a = np.empty((0, 2))
+        b = np.empty((3, 2))
+        res = khatri_rao(a, b)
+        assert_allclose(res, np.empty((0, 2)))
+
+        a = np.empty((3, 0))
+        b = np.empty((5, 0))
+        res = khatri_rao(a, b)
+        assert_allclose(res, np.empty((15, 0)))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f8f94fd10a5404d4013adf995bba54f76ff803
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py
@@ -0,0 +1,136 @@
+"""Test functions for linalg.matmul_toeplitz function
+"""
+
+import numpy as np
+from scipy.linalg import toeplitz, matmul_toeplitz
+
+from pytest import raises as assert_raises
+from numpy.testing import assert_allclose
+
+
+class TestMatmulToeplitz:
+
+    def setup_method(self):
+        self.rng = np.random.RandomState(42)
+        self.tolerance = 1.5e-13
+
+    def test_real(self):
+        cases = []
+
+        n = 1
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, 1))
+        cases.append((x, c, r, False))
+
+        n = 2
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, 1))
+        cases.append((x, c, r, False))
+
+        n = 101
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, 1))
+        cases.append((x, c, r, True))
+
+        n = 1000
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, 1))
+        cases.append((x, c, r, False))
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+        cases.append((x, c, r, False))
+
+        n = 100
+        c = self.rng.normal(size=(n, 1))
+        r = self.rng.normal(size=(n, 1))
+        x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+        cases.append((x, c, r, True))
+
+        n = 100
+        c = self.rng.normal(size=(n, 1))
+        r = None
+        x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+        cases.append((x, c, r, True, -1))
+
+        n = 100
+        c = self.rng.normal(size=(n, 1))
+        r = None
+        x = self.rng.normal(size=n)
+        cases.append((x, c, r, False))
+
+        n = 101
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n-27)
+        x = self.rng.normal(size=(n-27, 1))
+        cases.append((x, c, r, True))
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n//4)
+        x = self.rng.normal(size=(n//4, self.rng.randint(1, 10)))
+        cases.append((x, c, r, True))
+
+        [self.do(*i) for i in cases]
+
+    def test_complex(self):
+        n = 127
+        c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+        r = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+        x = self.rng.normal(size=(n, 3)) + self.rng.normal(size=(n, 3))*1j
+        self.do(x, c, r, False)
+
+        n = 100
+        c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+        r = self.rng.normal(size=(n//2, 1)) +\
+            self.rng.normal(size=(n//2, 1))*1j
+        x = self.rng.normal(size=(n//2, 3)) +\
+            self.rng.normal(size=(n//2, 3))*1j
+        self.do(x, c, r, False)
+
+    def test_empty(self):
+        c = []
+        r = []
+        x = []
+        self.do(x, c, r, False)
+
+        x = np.empty((0, 0))
+        self.do(x, c, r, False)
+
+    def test_exceptions(self):
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=2*n)
+        x = self.rng.normal(size=n)
+        assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=n-1)
+        assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n//2)
+        x = self.rng.normal(size=n//2-1)
+        assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+    # For toeplitz matrices, matmul_toeplitz() should be equivalent to @.
+    def do(self, x, c, r=None, check_finite=False, workers=None):
+        c = np.ravel(c)
+        if r is None:
+            actual = matmul_toeplitz(c, x, check_finite, workers)
+        else:
+            r = np.ravel(r)
+            actual = matmul_toeplitz((c, r), x, check_finite)
+        desired = toeplitz(c, r) @ x
+        assert_allclose(actual, desired,
+            rtol=self.tolerance, atol=self.tolerance)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..4efa433c2cab01a4f77ef1c4f1bde3ab4d5c421b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py
@@ -0,0 +1,221 @@
+from itertools import product, permutations
+
+import numpy as np
+import pytest
+from numpy.testing import assert_array_less, assert_allclose
+from pytest import raises as assert_raises
+
+from scipy.linalg import inv, eigh, norm, svd
+from scipy.linalg import orthogonal_procrustes
+from scipy.sparse._sputils import matrix
+
+
+def test_orthogonal_procrustes_ndim_too_large():
+    rng = np.random.RandomState(1234)
+    A = rng.randn(3, 4, 5)
+    B = rng.randn(3, 4, 5)
+    assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_ndim_too_small():
+    rng = np.random.RandomState(1234)
+    A = rng.randn(3)
+    B = rng.randn(3)
+    assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_shape_mismatch():
+    rng = np.random.RandomState(1234)
+    shapes = ((3, 3), (3, 4), (4, 3), (4, 4))
+    for a, b in permutations(shapes, 2):
+        A = rng.randn(*a)
+        B = rng.randn(*b)
+        assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_checkfinite_exception():
+    rng = np.random.RandomState(1234)
+    m, n = 2, 3
+    A_good = rng.randn(m, n)
+    B_good = rng.randn(m, n)
+    for bad_value in np.inf, -np.inf, np.nan:
+        A_bad = A_good.copy()
+        A_bad[1, 2] = bad_value
+        B_bad = B_good.copy()
+        B_bad[1, 2] = bad_value
+        for A, B in ((A_good, B_bad), (A_bad, B_good), (A_bad, B_bad)):
+            assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_scale_invariance():
+    rng = np.random.RandomState(1234)
+    m, n = 4, 3
+    for i in range(3):
+        A_orig = rng.randn(m, n)
+        B_orig = rng.randn(m, n)
+        R_orig, s = orthogonal_procrustes(A_orig, B_orig)
+        for A_scale in np.square(rng.randn(3)):
+            for B_scale in np.square(rng.randn(3)):
+                R, s = orthogonal_procrustes(A_orig * A_scale, B_orig * B_scale)
+                assert_allclose(R, R_orig)
+
+
+def test_orthogonal_procrustes_array_conversion():
+    rng = np.random.RandomState(1234)
+    for m, n in ((6, 4), (4, 4), (4, 6)):
+        A_arr = rng.randn(m, n)
+        B_arr = rng.randn(m, n)
+        As = (A_arr, A_arr.tolist(), matrix(A_arr))
+        Bs = (B_arr, B_arr.tolist(), matrix(B_arr))
+        R_arr, s = orthogonal_procrustes(A_arr, B_arr)
+        AR_arr = A_arr.dot(R_arr)
+        for A, B in product(As, Bs):
+            R, s = orthogonal_procrustes(A, B)
+            AR = A_arr.dot(R)
+            assert_allclose(AR, AR_arr)
+
+
+def test_orthogonal_procrustes():
+    rng = np.random.RandomState(1234)
+    for m, n in ((6, 4), (4, 4), (4, 6)):
+        # Sample a random target matrix.
+        B = rng.randn(m, n)
+        # Sample a random orthogonal matrix
+        # by computing eigh of a sampled symmetric matrix.
+        X = rng.randn(n, n)
+        w, V = eigh(X.T + X)
+        assert_allclose(inv(V), V.T)
+        # Compute a matrix with a known orthogonal transformation that gives B.
+        A = np.dot(B, V.T)
+        # Check that an orthogonal transformation from A to B can be recovered.
+        R, s = orthogonal_procrustes(A, B)
+        assert_allclose(inv(R), R.T)
+        assert_allclose(A.dot(R), B)
+        # Create a perturbed input matrix.
+        A_perturbed = A + 1e-2 * rng.randn(m, n)
+        # Check that the orthogonal procrustes function can find an orthogonal
+        # transformation that is better than the orthogonal transformation
+        # computed from the original input matrix.
+        R_prime, s = orthogonal_procrustes(A_perturbed, B)
+        assert_allclose(inv(R_prime), R_prime.T)
+        # Compute the naive and optimal transformations of the perturbed input.
+        naive_approx = A_perturbed.dot(R)
+        optim_approx = A_perturbed.dot(R_prime)
+        # Compute the Frobenius norm errors of the matrix approximations.
+        naive_approx_error = norm(naive_approx - B, ord='fro')
+        optim_approx_error = norm(optim_approx - B, ord='fro')
+        # Check that the orthogonal Procrustes approximation is better.
+        assert_array_less(optim_approx_error, naive_approx_error)
+
+
+def _centered(A):
+    mu = A.mean(axis=0)
+    return A - mu, mu
+
+
+def test_orthogonal_procrustes_exact_example():
+    # Check a small application.
+    # It uses translation, scaling, reflection, and rotation.
+    #
+    #         |
+    #   a  b  |
+    #         |
+    #   d  c  |        w
+    #         |
+    # --------+--- x ----- z ---
+    #         |
+    #         |        y
+    #         |
+    #
+    A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float)
+    B_orig = np.array([[3, 2], [1, 0], [3, -2], [5, 0]], dtype=float)
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    assert_allclose(B_approx, B_orig, atol=1e-8)
+
+
+def test_orthogonal_procrustes_stretched_example():
+    # Try again with a target with a stretched y axis.
+    A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float)
+    B_orig = np.array([[3, 40], [1, 0], [3, -40], [5, 0]], dtype=float)
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    expected = np.array([[3, 21], [-18, 0], [3, -21], [24, 0]], dtype=float)
+    assert_allclose(B_approx, expected, atol=1e-8)
+    # Check disparity symmetry.
+    expected_disparity = 0.4501246882793018
+    AB_disparity = np.square(norm(B_approx - B_orig) / norm(B))
+    assert_allclose(AB_disparity, expected_disparity)
+    R, s = orthogonal_procrustes(B, A)
+    scale = s / np.square(norm(B))
+    A_approx = scale * np.dot(B, R) + A_mu
+    BA_disparity = np.square(norm(A_approx - A_orig) / norm(A))
+    assert_allclose(BA_disparity, expected_disparity)
+
+
+def test_orthogonal_procrustes_skbio_example():
+    # This transformation is also exact.
+    # It uses translation, scaling, and reflection.
+    #
+    #   |
+    #   | a
+    #   | b
+    #   | c d
+    # --+---------
+    #   |
+    #   |       w
+    #   |
+    #   |       x
+    #   |
+    #   |   z   y
+    #   |
+    #
+    A_orig = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], dtype=float)
+    B_orig = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], dtype=float)
+    B_standardized = np.array([
+        [-0.13363062, 0.6681531],
+        [-0.13363062, 0.13363062],
+        [-0.13363062, -0.40089186],
+        [0.40089186, -0.40089186]])
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    assert_allclose(B_approx, B_orig)
+    assert_allclose(B / norm(B), B_standardized)
+
+
+def test_empty():
+    a = np.empty((0, 0))
+    r, s = orthogonal_procrustes(a, a)
+    assert_allclose(r, np.empty((0, 0)))
+
+    a = np.empty((0, 3))
+    r, s = orthogonal_procrustes(a, a)
+    assert_allclose(r, np.identity(3))
+
+
+@pytest.mark.parametrize('shape', [(4, 5), (5, 5), (5, 4)])
+def test_unitary(shape):
+    # gh-12071 added support for unitary matrices; check that it
+    # works as intended.
+    m, n = shape
+    rng = np.random.default_rng(589234981235)
+    A = rng.random(shape) + rng.random(shape) * 1j
+    Q = rng.random((n, n)) + rng.random((n, n)) * 1j
+    Q, _ = np.linalg.qr(Q)
+    B = A @ Q
+    R, scale = orthogonal_procrustes(A, B)
+    assert_allclose(R @ R.conj().T, np.eye(n), atol=1e-14)
+    assert_allclose(A @ Q, B)
+    if shape != (4, 5):  # solution is unique
+        assert_allclose(R, Q)
+    _, s, _ = svd(A.conj().T @ B)
+    assert_allclose(scale, np.sum(s))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fc5a8540510f57a2b00334b5e190d4ddd474d09
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py
@@ -0,0 +1,118 @@
+"""Tests for _sketches.py."""
+
+import numpy as np
+from numpy.testing import assert_, assert_equal
+from scipy.linalg import clarkson_woodruff_transform
+from scipy.linalg._sketches import cwt_matrix
+from scipy.sparse import issparse, rand
+from scipy.sparse.linalg import norm
+
+
+class TestClarksonWoodruffTransform:
+    """
+    Testing the Clarkson Woodruff Transform
+    """
+    # set seed for generating test matrices
+    rng = np.random.default_rng(1179103485)
+
+    # Test matrix parameters
+    n_rows = 2000
+    n_cols = 100
+    density = 0.1
+
+    # Sketch matrix dimensions
+    n_sketch_rows = 200
+
+    # Seeds to test with
+    seeds = [1755490010, 934377150, 1391612830, 1752708722, 2008891431,
+             1302443994, 1521083269, 1501189312, 1126232505, 1533465685]
+
+    A_dense = rng.random((n_rows, n_cols))
+    A_csc = rand(
+        n_rows, n_cols, density=density, format='csc', random_state=rng,
+    )
+    A_csr = rand(
+        n_rows, n_cols, density=density, format='csr', random_state=rng,
+    )
+    A_coo = rand(
+        n_rows, n_cols, density=density, format='coo', random_state=rng,
+    )
+
+    # Collect the test matrices
+    test_matrices = [
+        A_dense, A_csc, A_csr, A_coo,
+    ]
+
+    # Test vector with norm ~1
+    x = rng.random((n_rows, 1)) / np.sqrt(n_rows)
+
+    def test_sketch_dimensions(self):
+        for A in self.test_matrices:
+            for seed in self.seeds:
+                # seed to ensure backwards compatibility post SPEC7
+                sketch = clarkson_woodruff_transform(
+                    A, self.n_sketch_rows, seed=seed
+                )
+                assert_(sketch.shape == (self.n_sketch_rows, self.n_cols))
+
+    def test_seed_returns_identical_transform_matrix(self):
+        for seed in self.seeds:
+            S1 = cwt_matrix(
+                self.n_sketch_rows, self.n_rows, rng=seed
+            ).toarray()
+            S2 = cwt_matrix(
+                self.n_sketch_rows, self.n_rows, rng=seed
+            ).toarray()
+            assert_equal(S1, S2)
+
+    def test_seed_returns_identically(self):
+        for A in self.test_matrices:
+            for seed in self.seeds:
+                sketch1 = clarkson_woodruff_transform(
+                    A, self.n_sketch_rows, rng=seed
+                )
+                sketch2 = clarkson_woodruff_transform(
+                    A, self.n_sketch_rows, rng=seed
+                )
+                if issparse(sketch1):
+                    sketch1 = sketch1.toarray()
+                if issparse(sketch2):
+                    sketch2 = sketch2.toarray()
+                assert_equal(sketch1, sketch2)
+
+    def test_sketch_preserves_frobenius_norm(self):
+        # Given the probabilistic nature of the sketches
+        # we run the test multiple times and check that
+        # we pass all/almost all the tries.
+        n_errors = 0
+        for A in self.test_matrices:
+            if issparse(A):
+                true_norm = norm(A)
+            else:
+                true_norm = np.linalg.norm(A)
+            for seed in self.seeds:
+                sketch = clarkson_woodruff_transform(
+                    A, self.n_sketch_rows, rng=seed,
+                )
+                if issparse(sketch):
+                    sketch_norm = norm(sketch)
+                else:
+                    sketch_norm = np.linalg.norm(sketch)
+
+                if np.abs(true_norm - sketch_norm) > 0.1 * true_norm:
+                    n_errors += 1
+        assert_(n_errors == 0)
+
+    def test_sketch_preserves_vector_norm(self):
+        n_errors = 0
+        n_sketch_rows = int(np.ceil(2. / (0.01 * 0.5**2)))
+        true_norm = np.linalg.norm(self.x)
+        for seed in self.seeds:
+            sketch = clarkson_woodruff_transform(
+                self.x, n_sketch_rows, rng=seed,
+            )
+            sketch_norm = np.linalg.norm(sketch)
+
+            if np.abs(true_norm - sketch_norm) > 0.5 * true_norm:
+                n_errors += 1
+        assert_(n_errors == 0)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
new file mode 100644
index 0000000000000000000000000000000000000000..440a73abc8c83bc32887c37c75577b790f3f1be9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
@@ -0,0 +1,150 @@
+"""Test functions for linalg._solve_toeplitz module
+"""
+import numpy as np
+from scipy.linalg._solve_toeplitz import levinson
+from scipy.linalg import solve, toeplitz, solve_toeplitz, matmul_toeplitz
+from numpy.testing import assert_equal, assert_allclose
+
+import pytest
+from pytest import raises as assert_raises
+
+
+def test_solve_equivalence():
+    # For toeplitz matrices, solve_toeplitz() should be equivalent to solve().
+    random = np.random.RandomState(1234)
+    for n in (1, 2, 3, 10):
+        c = random.randn(n)
+        if random.rand() < 0.5:
+            c = c + 1j * random.randn(n)
+        r = random.randn(n)
+        if random.rand() < 0.5:
+            r = r + 1j * random.randn(n)
+        y = random.randn(n)
+        if random.rand() < 0.5:
+            y = y + 1j * random.randn(n)
+
+        # Check equivalence when both the column and row are provided.
+        actual = solve_toeplitz((c,r), y)
+        desired = solve(toeplitz(c, r=r), y)
+        assert_allclose(actual, desired)
+
+        # Check equivalence when the column is provided but not the row.
+        actual = solve_toeplitz(c, b=y)
+        desired = solve(toeplitz(c), y)
+        assert_allclose(actual, desired)
+
+
+def test_multiple_rhs():
+    random = np.random.RandomState(1234)
+    c = random.randn(4)
+    r = random.randn(4)
+    for offset in [0, 1j]:
+        for yshape in ((4,), (4, 3), (4, 3, 2)):
+            y = random.randn(*yshape) + offset
+            actual = solve_toeplitz((c,r), b=y)
+            desired = solve(toeplitz(c, r=r), y)
+            assert_equal(actual.shape, yshape)
+            assert_equal(desired.shape, yshape)
+            assert_allclose(actual, desired)
+
+
+def test_native_list_arguments():
+    c = [1,2,4,7]
+    r = [1,3,9,12]
+    y = [5,1,4,2]
+    actual = solve_toeplitz((c,r), y)
+    desired = solve(toeplitz(c, r=r), y)
+    assert_allclose(actual, desired)
+
+
+def test_zero_diag_error():
+    # The Levinson-Durbin implementation fails when the diagonal is zero.
+    random = np.random.RandomState(1234)
+    n = 4
+    c = random.randn(n)
+    r = random.randn(n)
+    y = random.randn(n)
+    c[0] = 0
+    assert_raises(np.linalg.LinAlgError,
+        solve_toeplitz, (c, r), b=y)
+
+
+def test_wikipedia_counterexample():
+    # The Levinson-Durbin implementation also fails in other cases.
+    # This example is from the talk page of the wikipedia article.
+    random = np.random.RandomState(1234)
+    c = [2, 2, 1]
+    y = random.randn(3)
+    assert_raises(np.linalg.LinAlgError, solve_toeplitz, c, b=y)
+
+
+def test_reflection_coeffs():
+    # check that the partial solutions are given by the reflection
+    # coefficients
+
+    random = np.random.RandomState(1234)
+    y_d = random.randn(10)
+    y_z = random.randn(10) + 1j
+    reflection_coeffs_d = [1]
+    reflection_coeffs_z = [1]
+    for i in range(2, 10):
+        reflection_coeffs_d.append(solve_toeplitz(y_d[:(i-1)], b=y_d[1:i])[-1])
+        reflection_coeffs_z.append(solve_toeplitz(y_z[:(i-1)], b=y_z[1:i])[-1])
+
+    y_d_concat = np.concatenate((y_d[-2:0:-1], y_d[:-1]))
+    y_z_concat = np.concatenate((y_z[-2:0:-1].conj(), y_z[:-1]))
+    _, ref_d = levinson(y_d_concat, b=y_d[1:])
+    _, ref_z = levinson(y_z_concat, b=y_z[1:])
+
+    assert_allclose(reflection_coeffs_d, ref_d[:-1])
+    assert_allclose(reflection_coeffs_z, ref_z[:-1])
+
+
+@pytest.mark.xfail(reason='Instability of Levinson iteration')
+def test_unstable():
+    # this is a "Gaussian Toeplitz matrix", as mentioned in Example 2 of
+    # I. Gohbert, T. Kailath and V. Olshevsky "Fast Gaussian Elimination with
+    # Partial Pivoting for Matrices with Displacement Structure"
+    # Mathematics of Computation, 64, 212 (1995), pp 1557-1576
+    # which can be unstable for levinson recursion.
+
+    # other fast toeplitz solvers such as GKO or Burg should be better.
+    random = np.random.RandomState(1234)
+    n = 100
+    c = 0.9 ** (np.arange(n)**2)
+    y = random.randn(n)
+
+    solution1 = solve_toeplitz(c, b=y)
+    solution2 = solve(toeplitz(c), y)
+
+    assert_allclose(solution1, solution2)
+
+
+@pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64])
+@pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+def test_empty(dt_c, dt_b):
+    c = np.array([], dtype=dt_c)
+    b = np.array([], dtype=dt_b)
+    x = solve_toeplitz(c, b)
+    assert x.shape == (0,)
+    assert x.dtype == solve_toeplitz(np.array([2, 1], dtype=dt_c),
+                                      np.ones(2, dtype=dt_b)).dtype
+
+    b = np.empty((0, 0), dtype=dt_b)
+    x1 = solve_toeplitz(c, b)
+    assert x1.shape == (0, 0)
+    assert x1.dtype == x.dtype
+
+
+@pytest.mark.parametrize('fun', [solve_toeplitz, matmul_toeplitz])
+def test_nd_FutureWarning(fun):
+    # Test future warnings with n-D `c`/`r`
+    rng = np.random.default_rng(283592436523456)
+    c = rng.random((2, 3, 4))
+    r = rng.random((2, 3, 4))
+    b_or_x = rng.random(24)
+    message = "Beginning in SciPy 1.17, multidimensional input will be..."
+    with pytest.warns(FutureWarning, match=message):
+         fun(c, b_or_x)
+    with pytest.warns(FutureWarning, match=message):
+         fun((c, r), b_or_x)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4a39c5e86939bddabafaaf87c643c0a4ad570fe
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py
@@ -0,0 +1,844 @@
+import os
+import numpy as np
+
+from numpy.testing import assert_array_almost_equal, assert_allclose
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import solve_sylvester
+from scipy.linalg import solve_continuous_lyapunov, solve_discrete_lyapunov
+from scipy.linalg import solve_continuous_are, solve_discrete_are
+from scipy.linalg import block_diag, solve, LinAlgError
+from scipy.sparse._sputils import matrix
+
+
+# dtypes for testing size-0 case following precedent set in gh-20295
+dtypes = [int, float, np.float32, complex, np.complex64]
+
+
+def _load_data(name):
+    """
+    Load npz data file under data/
+    Returns a copy of the data, rather than keeping the npz file open.
+    """
+    filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
+                            'data', name)
+    with np.load(filename) as f:
+        return dict(f.items())
+
+
+class TestSolveLyapunov:
+
+    cases = [
+        # empty case
+        (np.empty((0, 0)),
+         np.empty((0, 0))),
+        (np.array([[1, 2], [3, 4]]),
+         np.array([[9, 10], [11, 12]])),
+        # a, q all complex.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a real; q complex.
+        (np.array([[1.0, 2.0], [3.0, 5.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a complex; q real.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[2.0, 2.0], [-1.0, 2.0]])),
+        # An example from Kitagawa, 1977
+        (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3],
+                   [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]),
+         np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3],
+                   [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])),
+        # Companion matrix example. a complex; q real; a.shape[0] = 11
+        (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j,
+                    0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j,
+                    0.010+0.j],
+                   [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,
+                    0.000+0.j]]),
+         np.eye(11)),
+        # https://github.com/scipy/scipy/issues/4176
+        (matrix([[0, 1], [-1/2, -1]]),
+         (matrix([0, 3]).T @ matrix([0, 3]).T.T)),
+        # https://github.com/scipy/scipy/issues/4176
+        (matrix([[0, 1], [-1/2, -1]]),
+         (np.array(matrix([0, 3]).T @ matrix([0, 3]).T.T))),
+        ]
+
+    def test_continuous_squareness_and_shape(self):
+        nsq = np.ones((3, 2))
+        sq = np.eye(3)
+        assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq)
+        assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq)
+        assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2))
+
+    def check_continuous_case(self, a, q):
+        x = solve_continuous_lyapunov(a, q)
+        assert_array_almost_equal(
+                          np.dot(a, x) + np.dot(x, a.conj().transpose()), q)
+
+    def check_discrete_case(self, a, q, method=None):
+        x = solve_discrete_lyapunov(a, q, method=method)
+        assert_array_almost_equal(
+                      np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q)
+
+    def test_cases(self):
+        for case in self.cases:
+            self.check_continuous_case(case[0], case[1])
+            self.check_discrete_case(case[0], case[1])
+            self.check_discrete_case(case[0], case[1], method='direct')
+            self.check_discrete_case(case[0], case[1], method='bilinear')
+
+    @pytest.mark.parametrize("dtype_a", dtypes)
+    @pytest.mark.parametrize("dtype_q", dtypes)
+    def test_size_0(self, dtype_a, dtype_q):
+        rng = np.random.default_rng(234598235)
+
+        a = np.zeros((0, 0), dtype=dtype_a)
+        q = np.zeros((0, 0), dtype=dtype_q)
+        res = solve_continuous_lyapunov(a, q)
+
+        a = (rng.random((5, 5))*100).astype(dtype_a)
+        q = (rng.random((5, 5))*100).astype(dtype_q)
+        ref = solve_continuous_lyapunov(a, q)
+
+        assert res.shape == (0, 0)
+        assert res.dtype == ref.dtype
+
+
+class TestSolveContinuousAre:
+    mat6 = _load_data('carex_6_data.npz')
+    mat15 = _load_data('carex_15_data.npz')
+    mat18 = _load_data('carex_18_data.npz')
+    mat19 = _load_data('carex_19_data.npz')
+    mat20 = _load_data('carex_20_data.npz')
+    cases = [
+        # Carex examples taken from (with default parameters):
+        # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark
+        #     Examples for the Numerical Solution of Algebraic Riccati
+        #     Equations II: Continuous-Time Case', Tech. Report SPC 95_23,
+        #     Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.
+        #
+        # The format of the data is (a, b, q, r, knownfailure), where
+        # knownfailure is None if the test passes or a string
+        # indicating the reason for failure.
+        #
+        # Test Case 0: carex #1
+        (np.diag([1.], 1),
+         np.array([[0], [1]]),
+         block_diag(1., 2.),
+         1,
+         None),
+        # Test Case 1: carex #2
+        (np.array([[4, 3], [-4.5, -3.5]]),
+         np.array([[1], [-1]]),
+         np.array([[9, 6], [6, 4.]]),
+         1,
+         None),
+        # Test Case 2: carex #3
+        (np.array([[0, 1, 0, 0],
+                   [0, -1.89, 0.39, -5.53],
+                   [0, -0.034, -2.98, 2.43],
+                   [0.034, -0.0011, -0.99, -0.21]]),
+         np.array([[0, 0], [0.36, -1.6], [-0.95, -0.032], [0.03, 0]]),
+         np.array([[2.313, 2.727, 0.688, 0.023],
+                   [2.727, 4.271, 1.148, 0.323],
+                   [0.688, 1.148, 0.313, 0.102],
+                   [0.023, 0.323, 0.102, 0.083]]),
+         np.eye(2),
+         None),
+        # Test Case 3: carex #4
+        (np.array([[-0.991, 0.529, 0, 0, 0, 0, 0, 0],
+                   [0.522, -1.051, 0.596, 0, 0, 0, 0, 0],
+                   [0, 0.522, -1.118, 0.596, 0, 0, 0, 0],
+                   [0, 0, 0.522, -1.548, 0.718, 0, 0, 0],
+                   [0, 0, 0, 0.922, -1.64, 0.799, 0, 0],
+                   [0, 0, 0, 0, 0.922, -1.721, 0.901, 0],
+                   [0, 0, 0, 0, 0, 0.922, -1.823, 1.021],
+                   [0, 0, 0, 0, 0, 0, 0.922, -1.943]]),
+         np.array([[3.84, 4.00, 37.60, 3.08, 2.36, 2.88, 3.08, 3.00],
+                   [-2.88, -3.04, -2.80, -2.32, -3.32, -3.82, -4.12, -3.96]]
+                  ).T * 0.001,
+         np.array([[1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.1],
+                   [0.0, 1.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],
+                   [0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0],
+                   [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+                   [0.5, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],
+                   [0.0, 0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0],
+                   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0],
+                   [0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1]]),
+         np.eye(2),
+         None),
+        # Test Case 4: carex #5
+        (np.array(
+          [[-4.019, 5.120, 0., 0., -2.082, 0., 0., 0., 0.870],
+           [-0.346, 0.986, 0., 0., -2.340, 0., 0., 0., 0.970],
+           [-7.909, 15.407, -4.069, 0., -6.450, 0., 0., 0., 2.680],
+           [-21.816, 35.606, -0.339, -3.870, -17.800, 0., 0., 0., 7.390],
+           [-60.196, 98.188, -7.907, 0.340, -53.008, 0., 0., 0., 20.400],
+           [0, 0, 0, 0, 94.000, -147.200, 0., 53.200, 0.],
+           [0, 0, 0, 0, 0, 94.000, -147.200, 0, 0],
+           [0, 0, 0, 0, 0, 12.800, 0.000, -31.600, 0],
+           [0, 0, 0, 0, 12.800, 0.000, 0.000, 18.800, -31.600]]),
+         np.array([[0.010, -0.011, -0.151],
+                   [0.003, -0.021, 0.000],
+                   [0.009, -0.059, 0.000],
+                   [0.024, -0.162, 0.000],
+                   [0.068, -0.445, 0.000],
+                   [0.000, 0.000, 0.000],
+                   [0.000, 0.000, 0.000],
+                   [0.000, 0.000, 0.000],
+                   [0.000, 0.000, 0.000]]),
+         np.eye(9),
+         np.eye(3),
+         None),
+        # Test Case 5: carex #6
+        (mat6['A'], mat6['B'], mat6['Q'], mat6['R'], None),
+        # Test Case 6: carex #7
+        (np.array([[1, 0], [0, -2.]]),
+         np.array([[1e-6], [0]]),
+         np.ones((2, 2)),
+         1.,
+         'Bad residual accuracy'),
+        # Test Case 7: carex #8
+        (block_diag(-0.1, -0.02),
+         np.array([[0.100, 0.000], [0.001, 0.010]]),
+         np.array([[100, 1000], [1000, 10000]]),
+         np.ones((2, 2)) + block_diag(1e-6, 0),
+         None),
+        # Test Case 8: carex #9
+        (np.array([[0, 1e6], [0, 0]]),
+         np.array([[0], [1.]]),
+         np.eye(2),
+         1.,
+         None),
+        # Test Case 9: carex #10
+        (np.array([[1.0000001, 1], [1., 1.0000001]]),
+         np.eye(2),
+         np.eye(2),
+         np.eye(2),
+         None),
+        # Test Case 10: carex #11
+        (np.array([[3, 1.], [4, 2]]),
+         np.array([[1], [1]]),
+         np.array([[-11, -5], [-5, -2.]]),
+         1.,
+         None),
+        # Test Case 11: carex #12
+        (np.array([[7000000., 2000000., -0.],
+                   [2000000., 6000000., -2000000.],
+                   [0., -2000000., 5000000.]]) / 3,
+         np.eye(3),
+         np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]]).dot(
+                np.diag([1e-6, 1, 1e6])).dot(
+            np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]])) / 9,
+         np.eye(3) * 1e6,
+         'Bad Residual Accuracy'),
+        # Test Case 12: carex #13
+        (np.array([[0, 0.4, 0, 0],
+                   [0, 0, 0.345, 0],
+                   [0, -0.524e6, -0.465e6, 0.262e6],
+                   [0, 0, 0, -1e6]]),
+         np.array([[0, 0, 0, 1e6]]).T,
+         np.diag([1, 0, 1, 0]),
+         1.,
+         None),
+        # Test Case 13: carex #14
+        (np.array([[-1e-6, 1, 0, 0],
+                   [-1, -1e-6, 0, 0],
+                   [0, 0, 1e-6, 1],
+                   [0, 0, -1, 1e-6]]),
+         np.ones((4, 1)),
+         np.ones((4, 4)),
+         1.,
+         None),
+        # Test Case 14: carex #15
+        (mat15['A'], mat15['B'], mat15['Q'], mat15['R'], None),
+        # Test Case 15: carex #16
+        (np.eye(64, 64, k=-1) + np.eye(64, 64)*(-2.) + np.rot90(
+                 block_diag(1, np.zeros((62, 62)), 1)) + np.eye(64, 64, k=1),
+         np.eye(64),
+         np.eye(64),
+         np.eye(64),
+         None),
+        # Test Case 16: carex #17
+        (np.diag(np.ones((20, )), 1),
+         np.flipud(np.eye(21, 1)),
+         np.eye(21, 1) * np.eye(21, 1).T,
+         1,
+         'Bad Residual Accuracy'),
+        # Test Case 17: carex #18
+        (mat18['A'], mat18['B'], mat18['Q'], mat18['R'], None),
+        # Test Case 18: carex #19
+        (mat19['A'], mat19['B'], mat19['Q'], mat19['R'],
+         'Bad Residual Accuracy'),
+        # Test Case 19: carex #20
+        (mat20['A'], mat20['B'], mat20['Q'], mat20['R'],
+         'Bad Residual Accuracy')
+        ]
+    # Makes the minimum precision requirements customized to the test.
+    # Here numbers represent the number of decimals that agrees with zero
+    # matrix when the solution x is plugged in to the equation.
+    #
+    # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2
+    #
+    # If the test is failing use "None" for that entry.
+    #
+    min_decimal = (14, 12, 13, 14, 11, 6, None, 5, 7, 14, 14,
+                   None, 9, 14, 13, 14, None, 12, None, None)
+
+    @pytest.mark.parametrize("j, case", enumerate(cases))
+    def test_solve_continuous_are(self, j, case):
+        """Checks if 0 = XA + A'X - XB(R)^{-1} B'X + Q is true"""
+        a, b, q, r, knownfailure = case
+        if knownfailure:
+            pytest.xfail(reason=knownfailure)
+
+        dec = self.min_decimal[j]
+        x = solve_continuous_are(a, b, q, r)
+        res = x @ a + a.conj().T @ x + q
+        out_fact = x @ b
+        res -= out_fact @ solve(np.atleast_2d(r), out_fact.conj().T)
+        assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+
+
+class TestSolveDiscreteAre:
+    cases = [
+        # Darex examples taken from (with default parameters):
+        # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark
+        #     Examples for the Numerical Solution of Algebraic Riccati
+        #     Equations II: Discrete-Time Case', Tech. Report SPC 95_23,
+        #     Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.
+        # [2] T. GUDMUNDSSON, C. KENNEY, A.J. LAUB: 'Scaling of the
+        #     Discrete-Time Algebraic Riccati Equation to Enhance Stability
+        #     of the Schur Solution Method', IEEE Trans.Aut.Cont., vol.37(4)
+        #
+        # The format of the data is (a, b, q, r, knownfailure), where
+        # knownfailure is None if the test passes or a string
+        # indicating the reason for failure.
+        #
+        # TEST CASE 0 : Complex a; real b, q, r
+        (np.array([[2, 1-2j], [0, -3j]]),
+         np.array([[0], [1]]),
+         np.array([[1, 0], [0, 2]]),
+         np.array([[1]]),
+         None),
+        # TEST CASE 1 :Real a, q, r; complex b
+        (np.array([[2, 1], [0, -1]]),
+         np.array([[-2j], [1j]]),
+         np.array([[1, 0], [0, 2]]),
+         np.array([[1]]),
+         None),
+        # TEST CASE 2 : Real a, b; complex q, r
+        (np.array([[3, 1], [0, -1]]),
+         np.array([[1, 2], [1, 3]]),
+         np.array([[1, 1+1j], [1-1j, 2]]),
+         np.array([[2, -2j], [2j, 3]]),
+         None),
+        # TEST CASE 3 : User-reported gh-2251 (Trac #1732)
+        (np.array([[0.63399379, 0.54906824, 0.76253406],
+                   [0.5404729, 0.53745766, 0.08731853],
+                   [0.27524045, 0.84922129, 0.4681622]]),
+         np.array([[0.96861695], [0.05532739], [0.78934047]]),
+         np.eye(3),
+         np.eye(1),
+         None),
+        # TEST CASE 4 : darex #1
+        (np.array([[4, 3], [-4.5, -3.5]]),
+         np.array([[1], [-1]]),
+         np.array([[9, 6], [6, 4]]),
+         np.array([[1]]),
+         None),
+        # TEST CASE 5 : darex #2
+        (np.array([[0.9512, 0], [0, 0.9048]]),
+         np.array([[4.877, 4.877], [-1.1895, 3.569]]),
+         np.array([[0.005, 0], [0, 0.02]]),
+         np.array([[1/3, 0], [0, 3]]),
+         None),
+        # TEST CASE 6 : darex #3
+        (np.array([[2, -1], [1, 0]]),
+         np.array([[1], [0]]),
+         np.array([[0, 0], [0, 1]]),
+         np.array([[0]]),
+         None),
+        # TEST CASE 7 : darex #4 (skipped the gen. Ric. term S)
+        (np.array([[0, 1], [0, -1]]),
+         np.array([[1, 0], [2, 1]]),
+         np.array([[-4, -4], [-4, 7]]) * (1/11),
+         np.array([[9, 3], [3, 1]]),
+         None),
+        # TEST CASE 8 : darex #5
+        (np.array([[0, 1], [0, 0]]),
+         np.array([[0], [1]]),
+         np.array([[1, 2], [2, 4]]),
+         np.array([[1]]),
+         None),
+        # TEST CASE 9 : darex #6
+        (np.array([[0.998, 0.067, 0, 0],
+                   [-.067, 0.998, 0, 0],
+                   [0, 0, 0.998, 0.153],
+                   [0, 0, -.153, 0.998]]),
+         np.array([[0.0033, 0.0200],
+                   [0.1000, -.0007],
+                   [0.0400, 0.0073],
+                   [-.0028, 0.1000]]),
+         np.array([[1.87, 0, 0, -0.244],
+                   [0, 0.744, 0.205, 0],
+                   [0, 0.205, 0.589, 0],
+                   [-0.244, 0, 0, 1.048]]),
+         np.eye(2),
+         None),
+        # TEST CASE 10 : darex #7
+        (np.array([[0.984750, -.079903, 0.0009054, -.0010765],
+                   [0.041588, 0.998990, -.0358550, 0.0126840],
+                   [-.546620, 0.044916, -.3299100, 0.1931800],
+                   [2.662400, -.100450, -.9245500, -.2632500]]),
+         np.array([[0.0037112, 0.0007361],
+                   [-.0870510, 9.3411e-6],
+                   [-1.198440, -4.1378e-4],
+                   [-3.192700, 9.2535e-4]]),
+         np.eye(4)*1e-2,
+         np.eye(2),
+         None),
+        # TEST CASE 11 : darex #8
+        (np.array([[-0.6000000, -2.2000000, -3.6000000, -5.4000180],
+                   [1.0000000, 0.6000000, 0.8000000, 3.3999820],
+                   [0.0000000, 1.0000000, 1.8000000, 3.7999820],
+                   [0.0000000, 0.0000000, 0.0000000, -0.9999820]]),
+         np.array([[1.0, -1.0, -1.0, -1.0],
+                   [0.0, 1.0, -1.0, -1.0],
+                   [0.0, 0.0, 1.0, -1.0],
+                   [0.0, 0.0, 0.0, 1.0]]),
+         np.array([[2, 1, 3, 6],
+                   [1, 2, 2, 5],
+                   [3, 2, 6, 11],
+                   [6, 5, 11, 22]]),
+         np.eye(4),
+         None),
+        # TEST CASE 12 : darex #9
+        (np.array([[95.4070, 1.9643, 0.3597, 0.0673, 0.0190],
+                   [40.8490, 41.3170, 16.0840, 4.4679, 1.1971],
+                   [12.2170, 26.3260, 36.1490, 15.9300, 12.3830],
+                   [4.1118, 12.8580, 27.2090, 21.4420, 40.9760],
+                   [0.1305, 0.5808, 1.8750, 3.6162, 94.2800]]) * 0.01,
+         np.array([[0.0434, -0.0122],
+                   [2.6606, -1.0453],
+                   [3.7530, -5.5100],
+                   [3.6076, -6.6000],
+                   [0.4617, -0.9148]]) * 0.01,
+         np.eye(5),
+         np.eye(2),
+         None),
+        # TEST CASE 13 : darex #10
+        (np.kron(np.eye(2), np.diag([1, 1], k=1)),
+         np.kron(np.eye(2), np.array([[0], [0], [1]])),
+         np.array([[1, 1, 0, 0, 0, 0],
+                   [1, 1, 0, 0, 0, 0],
+                   [0, 0, 0, 0, 0, 0],
+                   [0, 0, 0, 1, -1, 0],
+                   [0, 0, 0, -1, 1, 0],
+                   [0, 0, 0, 0, 0, 0]]),
+         np.array([[3, 0], [0, 1]]),
+         None),
+        # TEST CASE 14 : darex #11
+        (0.001 * np.array(
+         [[870.1, 135.0, 11.59, .5014, -37.22, .3484, 0, 4.242, 7.249],
+          [76.55, 897.4, 12.72, 0.5504, -40.16, .3743, 0, 4.53, 7.499],
+          [-127.2, 357.5, 817, 1.455, -102.8, .987, 0, 11.85, 18.72],
+          [-363.5, 633.9, 74.91, 796.6, -273.5, 2.653, 0, 31.72, 48.82],
+          [-960, 1645.9, -128.9, -5.597, 71.42, 7.108, 0, 84.52, 125.9],
+          [-664.4, 112.96, -88.89, -3.854, 84.47, 13.6, 0, 144.3, 101.6],
+          [-410.2, 693, -54.71, -2.371, 66.49, 12.49, .1063, 99.97, 69.67],
+          [-179.9, 301.7, -23.93, -1.035, 60.59, 22.16, 0, 213.9, 35.54],
+          [-345.1, 580.4, -45.96, -1.989, 105.6, 19.86, 0, 219.1, 215.2]]),
+         np.array([[4.7600, -0.5701, -83.6800],
+                   [0.8790, -4.7730, -2.7300],
+                   [1.4820, -13.1200, 8.8760],
+                   [3.8920, -35.1300, 24.8000],
+                   [10.3400, -92.7500, 66.8000],
+                   [7.2030, -61.5900, 38.3400],
+                   [4.4540, -36.8300, 20.2900],
+                   [1.9710, -15.5400, 6.9370],
+                   [3.7730, -30.2800, 14.6900]]) * 0.001,
+         np.diag([50, 0, 0, 0, 50, 0, 0, 0, 0]),
+         np.eye(3),
+         None),
+        # TEST CASE 15 : darex #12 - numerically least accurate example
+        (np.array([[0, 1e6], [0, 0]]),
+         np.array([[0], [1]]),
+         np.eye(2),
+         np.array([[1]]),
+        None),
+        # TEST CASE 16 : darex #13
+        (np.array([[16, 10, -2],
+                  [10, 13, -8],
+                  [-2, -8, 7]]) * (1/9),
+         np.eye(3),
+         1e6 * np.eye(3),
+         1e6 * np.eye(3),
+        None),
+        # TEST CASE 17 : darex #14
+        (np.array([[1 - 1/1e8, 0, 0, 0],
+                  [1, 0, 0, 0],
+                  [0, 1, 0, 0],
+                  [0, 0, 1, 0]]),
+         np.array([[1e-08], [0], [0], [0]]),
+         np.diag([0, 0, 0, 1]),
+         np.array([[0.25]]),
+         None),
+        # TEST CASE 18 : darex #15
+        (np.eye(100, k=1),
+         np.flipud(np.eye(100, 1)),
+         np.eye(100),
+         np.array([[1]]),
+         None)
+        ]
+
+    # Makes the minimum precision requirements customized to the test.
+    # Here numbers represent the number of decimals that agrees with zero
+    # matrix when the solution x is plugged in to the equation.
+    #
+    # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2
+    #
+    # If the test is failing use "None" for that entry.
+    #
+    min_decimal = (12, 14, 13, 14, 13, 16, 18, 14, 14, 13,
+                   14, 13, 13, 14, 12, 2, 4, 6, 10)
+    max_tol = [1.5 * 10**-ind for ind in min_decimal]
+    # relaxed tolerance in gh-18012 after bump to OpenBLAS
+    max_tol[11] = 2.5e-13
+
+    # relaxed tolerance in gh-20335 for linux-aarch64 build on Cirrus
+    # with OpenBLAS from ubuntu jammy
+    max_tol[15] = 2.0e-2
+
+    # relaxed tolerance in gh-20335 for OpenBLAS 3.20 on ubuntu jammy
+    # bump not needed for OpenBLAS 3.26
+    max_tol[16] = 2.0e-4
+
+    @pytest.mark.parametrize("j, case", enumerate(cases))
+    def test_solve_discrete_are(self, j, case):
+        """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+        a, b, q, r, knownfailure = case
+        if knownfailure:
+            pytest.xfail(reason=knownfailure)
+
+        atol = self.max_tol[j]
+
+        x = solve_discrete_are(a, b, q, r)
+        bH = b.conj().T
+        xa, xb = x @ a, x @ b
+
+        res = a.conj().T @ xa - x + q
+        res -= a.conj().T @ xb @ (solve(r + bH @ xb, bH) @ xa)
+
+        # changed from
+        # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+        # in gh-18012 as it's easier to relax a tolerance and allclose is
+        # preferred
+        assert_allclose(res, np.zeros_like(res), atol=atol)
+
+    def test_infeasible(self):
+        # An infeasible example taken from https://arxiv.org/abs/1505.04861v1
+        A = np.triu(np.ones((3, 3)))
+        A[0, 1] = -1
+        B = np.array([[1, 1, 0], [0, 0, 1]]).T
+        Q = np.full_like(A, -2) + np.diag([8, -1, -1.9])
+        R = np.diag([-10, 0.1])
+        assert_raises(LinAlgError, solve_continuous_are, A, B, Q, R)
+
+
+def test_solve_generalized_continuous_are():
+    cases = [
+        # Two random examples differ by s term
+        # in the absence of any literature for demanding examples.
+        (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+                   [4.617139e-02, 6.948286e-01, 3.444608e-02],
+                   [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+         np.array([[3.815585e-01, 1.868726e-01],
+                   [7.655168e-01, 4.897644e-01],
+                   [7.951999e-01, 4.455862e-01]]),
+         np.eye(3),
+         np.eye(2),
+         np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+                   [7.093648e-01, 6.797027e-01, 1.189977e-01],
+                   [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+         np.zeros((3, 2)),
+         None),
+        (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+                   [4.617139e-02, 6.948286e-01, 3.444608e-02],
+                   [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+         np.array([[3.815585e-01, 1.868726e-01],
+                   [7.655168e-01, 4.897644e-01],
+                   [7.951999e-01, 4.455862e-01]]),
+         np.eye(3),
+         np.eye(2),
+         np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+                   [7.093648e-01, 6.797027e-01, 1.189977e-01],
+                   [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+         np.ones((3, 2)),
+         None)
+        ]
+
+    min_decimal = (10, 10)
+
+    def _test_factory(case, dec):
+        """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+        a, b, q, r, e, s, knownfailure = case
+        if knownfailure:
+            pytest.xfail(reason=knownfailure)
+
+        x = solve_continuous_are(a, b, q, r, e, s)
+        res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q
+        out_fact = e.conj().T.dot(x).dot(b) + s
+        res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T))
+        assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+
+    for ind, case in enumerate(cases):
+        _test_factory(case, min_decimal[ind])
+
+
+def test_solve_generalized_discrete_are():
+    mat20170120 = _load_data('gendare_20170120_data.npz')
+
+    cases = [
+        # Two random examples differ by s term
+        # in the absence of any literature for demanding examples.
+        (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+                   [4.617139e-02, 6.948286e-01, 3.444608e-02],
+                   [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+         np.array([[3.815585e-01, 1.868726e-01],
+                   [7.655168e-01, 4.897644e-01],
+                   [7.951999e-01, 4.455862e-01]]),
+         np.eye(3),
+         np.eye(2),
+         np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+                   [7.093648e-01, 6.797027e-01, 1.189977e-01],
+                   [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+         np.zeros((3, 2)),
+         None),
+        (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+                   [4.617139e-02, 6.948286e-01, 3.444608e-02],
+                   [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+         np.array([[3.815585e-01, 1.868726e-01],
+                   [7.655168e-01, 4.897644e-01],
+                   [7.951999e-01, 4.455862e-01]]),
+         np.eye(3),
+         np.eye(2),
+         np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+                   [7.093648e-01, 6.797027e-01, 1.189977e-01],
+                   [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+         np.ones((3, 2)),
+         None),
+        # user-reported (under PR-6616) 20-Jan-2017
+        # tests against the case where E is None but S is provided
+        (mat20170120['A'],
+         mat20170120['B'],
+         mat20170120['Q'],
+         mat20170120['R'],
+         None,
+         mat20170120['S'],
+         None),
+        ]
+
+    max_atol = (1.5e-11, 1.5e-11, 3.5e-16)
+
+    def _test_factory(case, atol):
+        """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+        a, b, q, r, e, s, knownfailure = case
+        if knownfailure:
+            pytest.xfail(reason=knownfailure)
+
+        x = solve_discrete_are(a, b, q, r, e, s)
+        if e is None:
+            e = np.eye(a.shape[0])
+        if s is None:
+            s = np.zeros_like(b)
+        res = a.conj().T.dot(x.dot(a)) - e.conj().T.dot(x.dot(e)) + q
+        res -= (a.conj().T.dot(x.dot(b)) + s).dot(
+                    solve(r+b.conj().T.dot(x.dot(b)),
+                          (b.conj().T.dot(x.dot(a)) + s.conj().T)
+                          )
+                )
+        # changed from:
+        # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+        # in gh-17950 because of a Linux 32 bit fail.
+        assert_allclose(res, np.zeros_like(res), atol=atol)
+
+    for ind, case in enumerate(cases):
+        _test_factory(case, max_atol[ind])
+
+
+def test_are_validate_args():
+
+    def test_square_shape():
+        nsq = np.ones((3, 2))
+        sq = np.eye(3)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, nsq, 1, 1, 1)
+            assert_raises(ValueError, x, sq, sq, nsq, 1)
+            assert_raises(ValueError, x, sq, sq, sq, nsq)
+            assert_raises(ValueError, x, sq, sq, sq, sq, nsq)
+
+    def test_compatible_sizes():
+        nsq = np.ones((3, 2))
+        sq = np.eye(4)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, sq, nsq, 1, 1)
+            assert_raises(ValueError, x, sq, sq, sq, sq, sq, nsq)
+            assert_raises(ValueError, x, sq, sq, np.eye(3), sq)
+            assert_raises(ValueError, x, sq, sq, sq, np.eye(3))
+            assert_raises(ValueError, x, sq, sq, sq, sq, np.eye(3))
+
+    def test_symmetry():
+        nsym = np.arange(9).reshape(3, 3)
+        sym = np.eye(3)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, sym, sym, nsym, sym)
+            assert_raises(ValueError, x, sym, sym, sym, nsym)
+
+    def test_singularity():
+        sing = np.full((3, 3), 1e12)
+        sing[2, 2] -= 1
+        sq = np.eye(3)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, sq, sq, sq, sq, sing)
+
+        assert_raises(ValueError, solve_continuous_are, sq, sq, sq, sing)
+
+    def test_finiteness():
+        nm = np.full((2, 2), np.nan)
+        sq = np.eye(2)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, nm, sq, sq, sq)
+            assert_raises(ValueError, x, sq, nm, sq, sq)
+            assert_raises(ValueError, x, sq, sq, nm, sq)
+            assert_raises(ValueError, x, sq, sq, sq, nm)
+            assert_raises(ValueError, x, sq, sq, sq, sq, nm)
+            assert_raises(ValueError, x, sq, sq, sq, sq, sq, nm)
+
+
+class TestSolveSylvester:
+    cases = [
+        # empty cases
+        (np.empty((0, 0)),
+         np.empty((0, 0)),
+         np.empty((0, 0))),
+         (np.empty((0, 0)),
+         np.empty((2, 2)),
+         np.empty((0, 2))),
+         (np.empty((2, 2)),
+         np.empty((0, 0)),
+         np.empty((2, 0))),
+        # a, b, c all real.
+        (np.array([[1, 2], [0, 4]]),
+         np.array([[5, 6], [0, 8]]),
+         np.array([[9, 10], [11, 12]])),
+        # a, b, c all real, 4x4. a and b have non-trivial 2x2 blocks in their
+        # quasi-triangular form.
+        (np.array([[1.0, 0, 0, 0],
+                   [0, 1.0, 2.0, 0.0],
+                   [0, 0, 3.0, -4],
+                   [0, 0, 2, 5]]),
+         np.array([[2.0, 0, 0, 1.0],
+                   [0, 1.0, 0.0, 0.0],
+                   [0, 0, 1.0, -1],
+                   [0, 0, 1, 1]]),
+         np.array([[1.0, 0, 0, 0],
+                   [0, 1.0, 0, 0],
+                   [0, 0, 1.0, 0],
+                   [0, 0, 0, 1.0]])),
+        # a, b, c all complex.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[-1.0, 2j], [3.0, 4.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a and b real; c complex.
+        (np.array([[1.0, 2.0], [3.0, 5.0]]),
+         np.array([[-1.0, 0], [3.0, 4.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a and c complex; b real.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[-1.0, 0], [3.0, 4.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a complex; b and c real.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[-1.0, 0], [3.0, 4.0]]),
+         np.array([[2.0, 2.0], [-1.0, 2.0]])),
+        # not square matrices, real
+        (np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]]),
+         np.array([[2, 3], [4, 5]]),
+         np.array([[1, 2], [3, 4], [5, 6]])),
+        # not square matrices, complex
+        (np.array([[8, 1j, 6+2j], [3, 5, 7], [4, 9, 2]]),
+         np.array([[2, 3], [4, 5-1j]]),
+         np.array([[1, 2j], [3, 4j], [5j, 6+7j]])),
+    ]
+
+    def check_case(self, a, b, c):
+        x = solve_sylvester(a, b, c)
+        assert_array_almost_equal(np.dot(a, x) + np.dot(x, b), c)
+
+    def test_cases(self):
+        for case in self.cases:
+            self.check_case(case[0], case[1], case[2])
+
+    def test_trivial(self):
+        a = np.array([[1.0, 0.0], [0.0, 1.0]])
+        b = np.array([[1.0]])
+        c = np.array([2.0, 2.0]).reshape(-1, 1)
+        x = solve_sylvester(a, b, c)
+        assert_array_almost_equal(x, np.array([1.0, 1.0]).reshape(-1, 1))
+
+    # Feel free to adjust this to test fewer dtypes or random selections rather than
+    # the Cartesian product. It doesn't take very long to test all combinations,
+    # though, so we'll start there and trim it down as we see fit.
+    @pytest.mark.parametrize("dtype_a", dtypes)
+    @pytest.mark.parametrize("dtype_b", dtypes)
+    @pytest.mark.parametrize("dtype_q", dtypes)
+    @pytest.mark.parametrize("m", [0, 3])
+    @pytest.mark.parametrize("n", [0, 3])
+    def test_size_0(self, m, n, dtype_a, dtype_b, dtype_q):
+        if m == n != 0:
+            pytest.skip('m = n != 0 is not a case that needs to be tested here.')
+
+        rng = np.random.default_rng(598435298262546)
+
+        a = np.zeros((m, m), dtype=dtype_a)
+        b = np.zeros((n, n), dtype=dtype_b)
+        q = np.zeros((m, n), dtype=dtype_q)
+        res = solve_sylvester(a, b, q)
+
+        a = (rng.random((5, 5))*100).astype(dtype_a)
+        b = (rng.random((6, 6))*100).astype(dtype_b)
+        q = (rng.random((5, 6))*100).astype(dtype_q)
+        ref = solve_sylvester(a, b, q)
+
+        assert res.shape == (m, n)
+        assert res.dtype == ref.dtype
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..d32e7ed4b4016924c60b3ed6287888a0372e8791
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py
@@ -0,0 +1,640 @@
+import pytest
+import numpy as np
+from numpy import arange, array, eye, copy, sqrt
+from numpy.testing import (assert_equal, assert_array_equal,
+                           assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+
+from scipy.fft import fft
+from scipy.special import comb
+from scipy.linalg import (toeplitz, hankel, circulant, hadamard, leslie, dft,
+                          companion, kron, block_diag,
+                          helmert, hilbert, invhilbert, pascal, invpascal,
+                          fiedler, fiedler_companion, eigvals,
+                          convolution_matrix)
+from numpy.linalg import cond
+
+
+class TestToeplitz:
+
+    def test_basic(self):
+        y = toeplitz([1, 2, 3])
+        assert_array_equal(y, [[1, 2, 3], [2, 1, 2], [3, 2, 1]])
+        y = toeplitz([1, 2, 3], [1, 4, 5])
+        assert_array_equal(y, [[1, 4, 5], [2, 1, 4], [3, 2, 1]])
+
+    def test_complex_01(self):
+        data = (1.0 + arange(3.0)) * (1.0 + 1.0j)
+        x = copy(data)
+        t = toeplitz(x)
+        # Calling toeplitz should not change x.
+        assert_array_equal(x, data)
+        # According to the docstring, x should be the first column of t.
+        col0 = t[:, 0]
+        assert_array_equal(col0, data)
+        assert_array_equal(t[0, 1:], data[1:].conj())
+
+    def test_scalar_00(self):
+        """Scalar arguments still produce a 2D array."""
+        t = toeplitz(10)
+        assert_array_equal(t, [[10]])
+        t = toeplitz(10, 20)
+        assert_array_equal(t, [[10]])
+
+    def test_scalar_01(self):
+        c = array([1, 2, 3])
+        t = toeplitz(c, 1)
+        assert_array_equal(t, [[1], [2], [3]])
+
+    def test_scalar_02(self):
+        c = array([1, 2, 3])
+        t = toeplitz(c, array(1))
+        assert_array_equal(t, [[1], [2], [3]])
+
+    def test_scalar_03(self):
+        c = array([1, 2, 3])
+        t = toeplitz(c, array([1]))
+        assert_array_equal(t, [[1], [2], [3]])
+
+    def test_scalar_04(self):
+        r = array([10, 2, 3])
+        t = toeplitz(1, r)
+        assert_array_equal(t, [[1, 2, 3]])
+
+
+class TestHankel:
+    def test_basic(self):
+        y = hankel([1, 2, 3])
+        assert_array_equal(y, [[1, 2, 3], [2, 3, 0], [3, 0, 0]])
+        y = hankel([1, 2, 3], [3, 4, 5])
+        assert_array_equal(y, [[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+
+
+class TestCirculant:
+    def test_basic(self):
+        y = circulant([1, 2, 3])
+        assert_array_equal(y, [[1, 3, 2], [2, 1, 3], [3, 2, 1]])
+
+
+class TestHadamard:
+
+    def test_basic(self):
+
+        y = hadamard(1)
+        assert_array_equal(y, [[1]])
+
+        y = hadamard(2, dtype=float)
+        assert_array_equal(y, [[1.0, 1.0], [1.0, -1.0]])
+
+        y = hadamard(4)
+        assert_array_equal(y, [[1, 1, 1, 1],
+                               [1, -1, 1, -1],
+                               [1, 1, -1, -1],
+                               [1, -1, -1, 1]])
+
+        assert_raises(ValueError, hadamard, 0)
+        assert_raises(ValueError, hadamard, 5)
+
+
+class TestLeslie:
+
+    def test_bad_shapes(self):
+        assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5])
+        assert_raises(ValueError, leslie, [1, 2], [1, 2])
+        assert_raises(ValueError, leslie, [1], [])
+
+    def test_basic(self):
+        a = leslie([1, 2, 3], [0.25, 0.5])
+        expected = array([[1.0, 2.0, 3.0],
+                          [0.25, 0.0, 0.0],
+                          [0.0, 0.5, 0.0]])
+        assert_array_equal(a, expected)
+
+
+class TestCompanion:
+
+    def test_bad_shapes(self):
+        assert_raises(ValueError, companion, [0, 4, 5])
+        assert_raises(ValueError, companion, [1])
+        assert_raises(ValueError, companion, [])
+
+    def test_basic(self):
+        c = companion([1, 2, 3])
+        expected = array([
+            [-2.0, -3.0],
+            [1.0, 0.0]])
+        assert_array_equal(c, expected)
+
+        c = companion([2.0, 5.0, -10.0])
+        expected = array([
+            [-2.5, 5.0],
+            [1.0, 0.0]])
+        assert_array_equal(c, expected)
+
+        c = companion([(1.0, 2.0, 3.0),
+                       (4.0, 5.0, 6.0)])
+        expected = array([
+            ([-2.00, -3.00],
+             [+1.00, +0.00]),
+            ([-1.25, -1.50],
+             [+1.00, +0.00])
+        ])
+        assert_array_equal(c, expected)
+
+
+class TestBlockDiag:
+    def test_basic(self):
+        x = block_diag(eye(2), [[1, 2], [3, 4], [5, 6]], [[1, 2, 3]])
+        assert_array_equal(x, [[1, 0, 0, 0, 0, 0, 0],
+                               [0, 1, 0, 0, 0, 0, 0],
+                               [0, 0, 1, 2, 0, 0, 0],
+                               [0, 0, 3, 4, 0, 0, 0],
+                               [0, 0, 5, 6, 0, 0, 0],
+                               [0, 0, 0, 0, 1, 2, 3]])
+
+    def test_dtype(self):
+        x = block_diag([[1.5]])
+        assert_equal(x.dtype, float)
+
+        x = block_diag([[True]])
+        assert_equal(x.dtype, bool)
+
+    def test_mixed_dtypes(self):
+        actual = block_diag([[1]], [[1j]])
+        desired = np.array([[1, 0], [0, 1j]])
+        assert_array_equal(actual, desired)
+
+    def test_scalar_and_1d_args(self):
+        a = block_diag(1)
+        assert_equal(a.shape, (1, 1))
+        assert_array_equal(a, [[1]])
+
+        a = block_diag([2, 3], 4)
+        assert_array_equal(a, [[2, 3, 0], [0, 0, 4]])
+
+    def test_bad_arg(self):
+        assert_raises(ValueError, block_diag, [[[1]]])
+
+    def test_no_args(self):
+        a = block_diag()
+        assert_equal(a.ndim, 2)
+        assert_equal(a.nbytes, 0)
+
+    def test_empty_matrix_arg(self):
+        # regression test for gh-4596: check the shape of the result
+        # for empty matrix inputs. Empty matrices are no longer ignored
+        # (gh-4908) it is viewed as a shape (1, 0) matrix.
+        a = block_diag([[1, 0], [0, 1]],
+                       [],
+                       [[2, 3], [4, 5], [6, 7]])
+        assert_array_equal(a, [[1, 0, 0, 0],
+                               [0, 1, 0, 0],
+                               [0, 0, 0, 0],
+                               [0, 0, 2, 3],
+                               [0, 0, 4, 5],
+                               [0, 0, 6, 7]])
+
+    def test_zerosized_matrix_arg(self):
+        # test for gh-4908: check the shape of the result for
+        # zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0).
+        # note that [[]] takes shape (1,0)
+        a = block_diag([[1, 0], [0, 1]],
+                       [[]],
+                       [[2, 3], [4, 5], [6, 7]],
+                       np.zeros([0, 2], dtype='int32'))
+        assert_array_equal(a, [[1, 0, 0, 0, 0, 0],
+                               [0, 1, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0],
+                               [0, 0, 2, 3, 0, 0],
+                               [0, 0, 4, 5, 0, 0],
+                               [0, 0, 6, 7, 0, 0]])
+
+
+class TestKron:
+    @pytest.mark.thread_unsafe
+    def test_dep(self):
+        with pytest.deprecated_call(match="`kron`"):
+            kron(np.array([[1, 2],[3, 4]]),np.array([[1, 1, 1]]))
+
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_basic(self):
+
+        a = kron(array([[1, 2], [3, 4]]), array([[1, 1, 1]]))
+        assert_array_equal(a, array([[1, 1, 1, 2, 2, 2],
+                                     [3, 3, 3, 4, 4, 4]]))
+
+        m1 = array([[1, 2], [3, 4]])
+        m2 = array([[10], [11]])
+        a = kron(m1, m2)
+        expected = array([[10, 20],
+                          [11, 22],
+                          [30, 40],
+                          [33, 44]])
+        assert_array_equal(a, expected)
+
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_empty(self):
+        m1 = np.empty((0, 2))
+        m2 = np.empty((1, 3))
+        a = kron(m1, m2)
+        assert_allclose(a, np.empty((0, 6)))
+
+
+class TestHelmert:
+
+    def test_orthogonality(self):
+        for n in range(1, 7):
+            H = helmert(n, full=True)
+            Id = np.eye(n)
+            assert_allclose(H.dot(H.T), Id, atol=1e-12)
+            assert_allclose(H.T.dot(H), Id, atol=1e-12)
+
+    def test_subspace(self):
+        for n in range(2, 7):
+            H_full = helmert(n, full=True)
+            H_partial = helmert(n)
+            for U in H_full[1:, :].T, H_partial.T:
+                C = np.eye(n) - np.full((n, n), 1 / n)
+                assert_allclose(U.dot(U.T), C)
+                assert_allclose(U.T.dot(U), np.eye(n-1), atol=1e-12)
+
+
+class TestHilbert:
+
+    def test_basic(self):
+        h3 = array([[1.0, 1/2., 1/3.],
+                    [1/2., 1/3., 1/4.],
+                    [1/3., 1/4., 1/5.]])
+        assert_array_almost_equal(hilbert(3), h3)
+
+        assert_array_equal(hilbert(1), [[1.0]])
+
+        h0 = hilbert(0)
+        assert_equal(h0.shape, (0, 0))
+
+
+class TestInvHilbert:
+
+    def test_basic(self):
+        invh1 = array([[1]])
+        assert_array_equal(invhilbert(1, exact=True), invh1)
+        assert_array_equal(invhilbert(1), invh1)
+
+        invh2 = array([[4, -6],
+                       [-6, 12]])
+        assert_array_equal(invhilbert(2, exact=True), invh2)
+        assert_array_almost_equal(invhilbert(2), invh2)
+
+        invh3 = array([[9, -36, 30],
+                       [-36, 192, -180],
+                       [30, -180, 180]])
+        assert_array_equal(invhilbert(3, exact=True), invh3)
+        assert_array_almost_equal(invhilbert(3), invh3)
+
+        invh4 = array([[16, -120, 240, -140],
+                       [-120, 1200, -2700, 1680],
+                       [240, -2700, 6480, -4200],
+                       [-140, 1680, -4200, 2800]])
+        assert_array_equal(invhilbert(4, exact=True), invh4)
+        assert_array_almost_equal(invhilbert(4), invh4)
+
+        invh5 = array([[25, -300, 1050, -1400, 630],
+                       [-300, 4800, -18900, 26880, -12600],
+                       [1050, -18900, 79380, -117600, 56700],
+                       [-1400, 26880, -117600, 179200, -88200],
+                       [630, -12600, 56700, -88200, 44100]])
+        assert_array_equal(invhilbert(5, exact=True), invh5)
+        assert_array_almost_equal(invhilbert(5), invh5)
+
+        invh17 = array([
+            [289, -41616, 1976760, -46124400, 629598060, -5540462928,
+             33374693352, -143034400080, 446982500250, -1033026222800,
+             1774926873720, -2258997839280, 2099709530100, -1384423866000,
+             613101997800, -163493866080, 19835652870],
+            [-41616, 7990272, -426980160, 10627061760, -151103534400,
+             1367702848512, -8410422724704, 36616806420480, -115857864064800,
+             270465047424000, -468580694662080, 600545887119360,
+             -561522320049600, 372133135180800, -165537539406000,
+             44316454993920, -5395297580640],
+            [1976760, -426980160, 24337869120, -630981792000, 9228108708000,
+             -85267724461920, 532660105897920, -2348052711713280,
+             7504429831470000, -17664748409880000, 30818191841236800,
+             -39732544853164800, 37341234283298400, -24857330514030000,
+             11100752642520000, -2982128117299200, 364182586693200],
+            [-46124400, 10627061760, -630981792000, 16826181120000,
+             -251209625940000, 2358021022156800, -14914482965141760,
+             66409571644416000, -214015221119700000, 507295338950400000,
+             -890303319857952000, 1153715376477081600, -1089119333262870000,
+             727848632044800000, -326170262829600000, 87894302404608000,
+             -10763618673376800],
+            [629598060, -151103534400, 9228108708000,
+             -251209625940000, 3810012660090000, -36210360321495360,
+             231343968720664800, -1038687206500944000, 3370739732635275000,
+             -8037460526495400000, 14178080368737885600, -18454939322943942000,
+             17489975175339030000, -11728977435138600000, 5272370630081100000,
+             -1424711708039692800, 174908803442373000],
+            [-5540462928, 1367702848512, -85267724461920, 2358021022156800,
+             -36210360321495360, 347619459086355456, -2239409617216035264,
+             10124803292907663360, -33052510749726468000,
+             79217210949138662400, -140362995650505067440,
+             183420385176741672960, -174433352415381259200,
+             117339159519533952000, -52892422160973595200,
+             14328529177999196160, -1763080738699119840],
+            [33374693352, -8410422724704, 532660105897920,
+             -14914482965141760, 231343968720664800, -2239409617216035264,
+             14527452132196331328, -66072377044391477760,
+             216799987176909536400, -521925895055522958000,
+             928414062734059661760, -1217424500995626443520,
+             1161358898976091015200, -783401860847777371200,
+             354015418167362952000, -96120549902411274240,
+             11851820521255194480],
+            [-143034400080, 36616806420480, -2348052711713280,
+             66409571644416000, -1038687206500944000, 10124803292907663360,
+             -66072377044391477760, 302045152202932469760,
+             -995510145200094810000, 2405996923185123840000,
+             -4294704507885446054400, 5649058909023744614400,
+             -5403874060541811254400, 3654352703663101440000,
+             -1655137020003255360000, 450325202737117593600,
+             -55630994283442749600],
+            [446982500250, -115857864064800, 7504429831470000,
+             -214015221119700000, 3370739732635275000, -33052510749726468000,
+             216799987176909536400, -995510145200094810000,
+             3293967392206196062500, -7988661659013106500000,
+             14303908928401362270000, -18866974090684772052000,
+             18093328327706957325000, -12263364009096700500000,
+             5565847995255512250000, -1517208935002984080000,
+             187754605706619279900],
+            [-1033026222800, 270465047424000, -17664748409880000,
+             507295338950400000, -8037460526495400000, 79217210949138662400,
+             -521925895055522958000, 2405996923185123840000,
+             -7988661659013106500000, 19434404971634224000000,
+             -34894474126569249192000, 46141453390504792320000,
+             -44349976506971935800000, 30121928988527376000000,
+             -13697025107665828500000, 3740200989399948902400,
+             -463591619028689580000],
+            [1774926873720, -468580694662080,
+             30818191841236800, -890303319857952000, 14178080368737885600,
+             -140362995650505067440, 928414062734059661760,
+             -4294704507885446054400, 14303908928401362270000,
+             -34894474126569249192000, 62810053427824648545600,
+             -83243376594051600326400, 80177044485212743068000,
+             -54558343880470209780000, 24851882355348879230400,
+             -6797096028813368678400, 843736746632215035600],
+            [-2258997839280, 600545887119360, -39732544853164800,
+             1153715376477081600, -18454939322943942000, 183420385176741672960,
+             -1217424500995626443520, 5649058909023744614400,
+             -18866974090684772052000, 46141453390504792320000,
+             -83243376594051600326400, 110552468520163390156800,
+             -106681852579497947388000, 72720410752415168870400,
+             -33177973900974346080000, 9087761081682520473600,
+             -1129631016152221783200],
+            [2099709530100, -561522320049600, 37341234283298400,
+             -1089119333262870000, 17489975175339030000,
+             -174433352415381259200, 1161358898976091015200,
+             -5403874060541811254400, 18093328327706957325000,
+             -44349976506971935800000, 80177044485212743068000,
+             -106681852579497947388000, 103125790826848015808400,
+             -70409051543137015800000, 32171029219823375700000,
+             -8824053728865840192000, 1098252376814660067000],
+            [-1384423866000, 372133135180800,
+             -24857330514030000, 727848632044800000, -11728977435138600000,
+             117339159519533952000, -783401860847777371200,
+             3654352703663101440000, -12263364009096700500000,
+             30121928988527376000000, -54558343880470209780000,
+             72720410752415168870400, -70409051543137015800000,
+             48142941226076592000000, -22027500987368499000000,
+             6049545098753157120000, -753830033789944188000],
+            [613101997800, -165537539406000,
+             11100752642520000, -326170262829600000, 5272370630081100000,
+             -52892422160973595200, 354015418167362952000,
+             -1655137020003255360000, 5565847995255512250000,
+             -13697025107665828500000, 24851882355348879230400,
+             -33177973900974346080000, 32171029219823375700000,
+             -22027500987368499000000, 10091416708498869000000,
+             -2774765838662800128000, 346146444087219270000],
+            [-163493866080, 44316454993920, -2982128117299200,
+             87894302404608000, -1424711708039692800,
+             14328529177999196160, -96120549902411274240,
+             450325202737117593600, -1517208935002984080000,
+             3740200989399948902400, -6797096028813368678400,
+             9087761081682520473600, -8824053728865840192000,
+             6049545098753157120000, -2774765838662800128000,
+             763806510427609497600, -95382575704033754400],
+            [19835652870, -5395297580640, 364182586693200, -10763618673376800,
+             174908803442373000, -1763080738699119840, 11851820521255194480,
+             -55630994283442749600, 187754605706619279900,
+             -463591619028689580000, 843736746632215035600,
+             -1129631016152221783200, 1098252376814660067000,
+             -753830033789944188000, 346146444087219270000,
+             -95382575704033754400, 11922821963004219300]
+        ])
+        assert_array_equal(invhilbert(17, exact=True), invh17)
+        assert_allclose(invhilbert(17), invh17.astype(float), rtol=1e-12)
+
+    def test_inverse(self):
+        for n in range(1, 10):
+            a = hilbert(n)
+            b = invhilbert(n)
+            # The Hilbert matrix is increasingly badly conditioned,
+            # so take that into account in the test
+            c = cond(a)
+            assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c)
+
+
+class TestPascal:
+
+    cases = [
+        (1, array([[1]]), array([[1]])),
+        (2, array([[1, 1],
+                   [1, 2]]),
+            array([[1, 0],
+                   [1, 1]])),
+        (3, array([[1, 1, 1],
+                   [1, 2, 3],
+                   [1, 3, 6]]),
+            array([[1, 0, 0],
+                   [1, 1, 0],
+                   [1, 2, 1]])),
+        (4, array([[1, 1, 1, 1],
+                   [1, 2, 3, 4],
+                   [1, 3, 6, 10],
+                   [1, 4, 10, 20]]),
+            array([[1, 0, 0, 0],
+                   [1, 1, 0, 0],
+                   [1, 2, 1, 0],
+                   [1, 3, 3, 1]])),
+    ]
+
+    def check_case(self, n, sym, low):
+        assert_array_equal(pascal(n), sym)
+        assert_array_equal(pascal(n, kind='lower'), low)
+        assert_array_equal(pascal(n, kind='upper'), low.T)
+        assert_array_almost_equal(pascal(n, exact=False), sym)
+        assert_array_almost_equal(pascal(n, exact=False, kind='lower'), low)
+        assert_array_almost_equal(pascal(n, exact=False, kind='upper'), low.T)
+
+    def test_cases(self):
+        for n, sym, low in self.cases:
+            self.check_case(n, sym, low)
+
+    def test_big(self):
+        p = pascal(50)
+        assert p[-1, -1] == comb(98, 49, exact=True)
+
+    def test_threshold(self):
+        # Regression test.  An early version of `pascal` returned an
+        # array of type np.uint64 for n=35, but that data type is too small
+        # to hold p[-1, -1].  The second assert_equal below would fail
+        # because p[-1, -1] overflowed.
+        p = pascal(34)
+        assert_equal(2*p.item(-1, -2), p.item(-1, -1), err_msg="n = 34")
+        p = pascal(35)
+        assert_equal(2.*p.item(-1, -2), 1.*p.item(-1, -1), err_msg="n = 35")
+
+
+def test_invpascal():
+
+    def check_invpascal(n, kind, exact):
+        ip = invpascal(n, kind=kind, exact=exact)
+        p = pascal(n, kind=kind, exact=exact)
+        # Matrix-multiply ip and p, and check that we get the identity matrix.
+        # We can't use the simple expression e = ip.dot(p), because when
+        # n < 35 and exact is True, p.dtype is np.uint64 and ip.dtype is
+        # np.int64. The product of those dtypes is np.float64, which loses
+        # precision when n is greater than 18.  Instead we'll cast both to
+        # object arrays, and then multiply.
+        e = ip.astype(object).dot(p.astype(object))
+        assert_array_equal(e, eye(n), err_msg="n=%d  kind=%r exact=%r" %
+                                              (n, kind, exact))
+
+    kinds = ['symmetric', 'lower', 'upper']
+
+    ns = [1, 2, 5, 18]
+    for n in ns:
+        for kind in kinds:
+            for exact in [True, False]:
+                check_invpascal(n, kind, exact)
+
+    ns = [19, 34, 35, 50]
+    for n in ns:
+        for kind in kinds:
+            check_invpascal(n, kind, True)
+
+
+def test_dft():
+    m = dft(2)
+    expected = array([[1.0, 1.0], [1.0, -1.0]])
+    assert_array_almost_equal(m, expected)
+    m = dft(2, scale='n')
+    assert_array_almost_equal(m, expected/2.0)
+    m = dft(2, scale='sqrtn')
+    assert_array_almost_equal(m, expected/sqrt(2.0))
+
+    x = array([0, 1, 2, 3, 4, 5, 0, 1])
+    m = dft(8)
+    mx = m.dot(x)
+    fx = fft(x)
+    assert_array_almost_equal(mx, fx)
+
+
+def test_fiedler():
+    f = fiedler([])
+    assert_equal(f.size, 0)
+    f = fiedler([123.])
+    assert_array_equal(f, np.array([[0.]]))
+    f = fiedler(np.arange(1, 7))
+    des = np.array([[0, 1, 2, 3, 4, 5],
+                    [1, 0, 1, 2, 3, 4],
+                    [2, 1, 0, 1, 2, 3],
+                    [3, 2, 1, 0, 1, 2],
+                    [4, 3, 2, 1, 0, 1],
+                    [5, 4, 3, 2, 1, 0]])
+    assert_array_equal(f, des)
+
+
+def test_fiedler_companion():
+    fc = fiedler_companion([])
+    assert_equal(fc.size, 0)
+    fc = fiedler_companion([1.])
+    assert_equal(fc.size, 0)
+    fc = fiedler_companion([1., 2.])
+    assert_array_equal(fc, np.array([[-2.]]))
+    fc = fiedler_companion([1e-12, 2., 3.])
+    assert_array_almost_equal(fc, companion([1e-12, 2., 3.]))
+    with assert_raises(ValueError):
+        fiedler_companion([0, 1, 2])
+    fc = fiedler_companion([1., -16., 86., -176., 105.])
+    assert_array_almost_equal(eigvals(fc),
+                              np.array([7., 5., 3., 1.]))
+
+
+class TestConvolutionMatrix:
+    """
+    Test convolution_matrix vs. numpy.convolve for various parameters.
+    """
+
+    def create_vector(self, n, cpx):
+        """Make a complex or real test vector of length n."""
+        x = np.linspace(-2.5, 2.2, n)
+        if cpx:
+            x = x + 1j*np.linspace(-1.5, 3.1, n)
+        return x
+
+    def test_bad_n(self):
+        # n must be a positive integer
+        with pytest.raises(ValueError, match='n must be a positive integer'):
+            convolution_matrix([1, 2, 3], 0)
+
+    def test_empty_first_arg(self):
+        # first arg must have at least one value
+        with pytest.raises(ValueError, match=r'len\(a\)'):
+            convolution_matrix([], 4)
+
+    def test_bad_mode(self):
+        # mode must be in ('full', 'valid', 'same')
+        with pytest.raises(ValueError, match='mode.*must be one of'):
+            convolution_matrix((1, 1), 4, mode='invalid argument')
+
+    @pytest.mark.parametrize('cpx', [False, True])
+    @pytest.mark.parametrize('na', [1, 2, 9])
+    @pytest.mark.parametrize('nv', [1, 2, 9])
+    @pytest.mark.parametrize('mode', [None, 'full', 'valid', 'same'])
+    def test_against_numpy_convolve(self, cpx, na, nv, mode):
+        a = self.create_vector(na, cpx)
+        v = self.create_vector(nv, cpx)
+        if mode is None:
+            y1 = np.convolve(v, a)
+            A = convolution_matrix(a, nv)
+        else:
+            y1 = np.convolve(v, a, mode)
+            A = convolution_matrix(a, nv, mode)
+        y2 = A @ v
+        assert_array_almost_equal(y1, y2)
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.fail_slow(5)  # `leslie` has an import in the function
+@pytest.mark.parametrize('f, args', [(circulant, ()),
+                                     (companion, ()),
+                                     (convolution_matrix, (5, 'same')),
+                                     (fiedler, ()),
+                                     (fiedler_companion, ()),
+                                     (leslie, (np.arange(9),)),
+                                     (toeplitz, (np.arange(9),)),
+                                     ])
+def test_batch(f, args):
+    rng = np.random.default_rng(283592436523456)
+    batch_shape = (2, 3)
+    m = 10
+    A = rng.random(batch_shape + (m,))
+
+    if f in {toeplitz}:
+        message = "Beginning in SciPy 1.17, multidimensional input will be..."
+        with pytest.warns(FutureWarning, match=message):
+            f(A, *args)
+        return
+
+    res = f(A, *args)
+    ref = np.asarray([f(a, *args) for a in A.reshape(-1, m)])
+    ref = ref.reshape(A.shape[:-1] + ref.shape[-2:])
+    assert_allclose(res, ref)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2eb2f71afd54a67b54d7012347e5d1a983fac7be
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/__init__.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/common.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..e85acca3ac49d1cb84792bdf369cffe69a5d8ad8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/common.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc.common is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/doccer.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..74cabc8c2fd14fe6424b8aad828c329ecdaee4b2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/misc/doccer.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc.doccer is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e9d9f6ff99218088fd9e693aaca00ca8a070040
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__init__.py
@@ -0,0 +1,173 @@
+"""
+=========================================================
+Multidimensional image processing (:mod:`scipy.ndimage`)
+=========================================================
+
+.. currentmodule:: scipy.ndimage
+
+This package contains various functions for multidimensional image
+processing.
+
+
+Filters
+=======
+
+.. autosummary::
+   :toctree: generated/
+
+   convolve - Multidimensional convolution
+   convolve1d - 1-D convolution along the given axis
+   correlate - Multidimensional correlation
+   correlate1d - 1-D correlation along the given axis
+   gaussian_filter
+   gaussian_filter1d
+   gaussian_gradient_magnitude
+   gaussian_laplace
+   generic_filter - Multidimensional filter using a given function
+   generic_filter1d - 1-D generic filter along the given axis
+   generic_gradient_magnitude
+   generic_laplace
+   laplace - N-D Laplace filter based on approximate second derivatives
+   maximum_filter
+   maximum_filter1d
+   median_filter - Calculates a multidimensional median filter
+   minimum_filter
+   minimum_filter1d
+   percentile_filter - Calculates a multidimensional percentile filter
+   prewitt
+   rank_filter - Calculates a multidimensional rank filter
+   sobel
+   uniform_filter - Multidimensional uniform filter
+   uniform_filter1d - 1-D uniform filter along the given axis
+
+Fourier filters
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   fourier_ellipsoid
+   fourier_gaussian
+   fourier_shift
+   fourier_uniform
+
+Interpolation
+=============
+
+.. autosummary::
+   :toctree: generated/
+
+   affine_transform - Apply an affine transformation
+   geometric_transform - Apply an arbitrary geometric transform
+   map_coordinates - Map input array to new coordinates by interpolation
+   rotate - Rotate an array
+   shift - Shift an array
+   spline_filter
+   spline_filter1d
+   zoom - Zoom an array
+
+Measurements
+============
+
+.. autosummary::
+   :toctree: generated/
+
+   center_of_mass - The center of mass of the values of an array at labels
+   extrema - Min's and max's of an array at labels, with their positions
+   find_objects - Find objects in a labeled array
+   histogram - Histogram of the values of an array, optionally at labels
+   label - Label features in an array
+   labeled_comprehension
+   maximum
+   maximum_position
+   mean - Mean of the values of an array at labels
+   median
+   minimum
+   minimum_position
+   standard_deviation - Standard deviation of an N-D image array
+   sum_labels - Sum of the values of the array
+   value_indices - Find indices of each distinct value in given array
+   variance - Variance of the values of an N-D image array
+   watershed_ift
+
+Morphology
+==========
+
+.. autosummary::
+   :toctree: generated/
+
+   binary_closing
+   binary_dilation
+   binary_erosion
+   binary_fill_holes
+   binary_hit_or_miss
+   binary_opening
+   binary_propagation
+   black_tophat
+   distance_transform_bf
+   distance_transform_cdt
+   distance_transform_edt
+   generate_binary_structure
+   grey_closing
+   grey_dilation
+   grey_erosion
+   grey_opening
+   iterate_structure
+   morphological_gradient
+   morphological_laplace
+   white_tophat
+
+"""
+
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# 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.
+
+# bring in the public functionality from private namespaces
+
+# mypy: ignore-errors
+
+from ._support_alternative_backends import *
+
+# adjust __all__ and do not leak implementation details
+from . import _support_alternative_backends
+__all__ = _support_alternative_backends.__all__
+del _support_alternative_backends, _ndimage_api, _delegators  # noqa: F821
+
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import filters
+from . import fourier
+from . import interpolation
+from . import measurements
+from . import morphology
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc121f4b7e562c113622d3d8805ed422dde7c2ac
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76982ed5ea13672facd231260ad3c825366af5d4
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6292b9cfe164b93b9d777580fe9a9bed4b93a6b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63ae6fea1e75cc78558b04a4b780cd4403d07bd1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acbf0ae03340e6183cb258a1b51069557f3d7437
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1bf1023c5410242e23fc8f6dc34793c6025e9ff1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce03f3979f831ebc5c8641a8a51f62433dd8d72f
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5878d808aaa9a8f0f4f20ce6ff56cde6cd40b52
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68f2aa385f493a2ec796abc2e5ca05eedc249a9c
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d2e46f4b6f48a1139e1e1644ab4a1f5a056d510
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27d09f06689992e6b259359013813d7a5859d854
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b8a305d1014664eb6cba88dc75554a3c911162c3
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b2257ee21bffbe00dbbd17b45e0a43498dcd24d6
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f51ef1b537db9e0fe5d0d7ecfea06bcfced8f5ce
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f75ddeccce13121fd132e39f458d83628f53780b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0b0165329a68d563aed36c532109f536bbe19df
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..0d05e123ba1f7f45c1f37795e7ba5cd0257018b4
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..7898248eb4d089b5ffa726ff39de4d0ec4637272
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..9647ea6456426c9a62178ff277b0f35017a8310b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py
@@ -0,0 +1,297 @@
+"""Delegators for alternative backends in scipy.ndimage.
+
+The signature of `func_signature` must match the signature of ndimage.func.
+The job of a `func_signature` is to know which arguments of `ndimage.func`
+are arrays.
+
+* signatures are generated by
+
+--------------
+import inspect
+from scipy import ndimage
+
+names = [x for x in dir(ndimage) if not x.startswith('_')]
+objs = [getattr(ndimage, name) for name in names]
+funcs = [obj for obj in objs if inspect.isroutine(obj)]
+
+for func in funcs:
+    sig = inspect.signature(func)
+    print(f"def {func.__name__}_signature{sig}:\n\tpass\n\n")
+---------------
+
+* which arguments to delegate on: manually trawled the documentation for
+  array-like and array arguments
+
+"""
+import numpy as np
+from scipy._lib._array_api import array_namespace
+from scipy.ndimage._ni_support import _skip_if_dtype, _skip_if_int
+
+
+def affine_transform_signature(
+    input, matrix, offset=0.0, output_shape=None, output=None, *args, **kwds
+):
+    return array_namespace(input, matrix, _skip_if_dtype(output))
+
+
+def binary_closing_signature(
+    input, structure=None, iterations=1, output=None, *args, **kwds
+):
+    return array_namespace(input, structure, _skip_if_dtype(output))
+
+binary_opening_signature = binary_closing_signature
+
+
+def binary_dilation_signature(
+    input, structure=None, iterations=1, mask=None, output=None, *args, **kwds
+):
+    return array_namespace(input, structure, _skip_if_dtype(output), mask)
+
+binary_erosion_signature = binary_dilation_signature
+
+
+def binary_fill_holes_signature(
+    input, structure=None, output=None, origin=0, *args, **kwargs
+):
+    return array_namespace(input, structure, _skip_if_dtype(output))
+
+
+def label_signature(input, structure=None, output=None, origin=0):
+    return array_namespace(input, structure, _skip_if_dtype(output))
+
+
+def binary_hit_or_miss_signature(
+    input, structure1=None, structure2=None, output=None, *args, **kwds
+):
+    return array_namespace(input, structure1, structure2, _skip_if_dtype(output))
+
+
+def binary_propagation_signature(
+    input, structure=None, mask=None, output=None, *args, **kwds
+):
+    return array_namespace(input, structure, mask, _skip_if_dtype(output))
+
+
+def convolve_signature(input, weights, output=None, *args, **kwds):
+    return array_namespace(input, weights, _skip_if_dtype(output))
+
+correlate_signature = convolve_signature
+
+
+def convolve1d_signature(input, weights, axis=-1, output=None, *args, **kwds):
+    return array_namespace(input, weights, _skip_if_dtype(output))
+
+correlate1d_signature = convolve1d_signature
+
+
+def distance_transform_bf_signature(
+    input, metric='euclidean', sampling=None, return_distances=True,
+    return_indices=False, distances=None, indices=None
+):
+    return array_namespace(input, distances, indices)
+
+
+def distance_transform_cdt_signature(
+    input, metric='chessboard', return_distances=True, return_indices=False,
+    distances=None, indices=None
+):
+    return array_namespace(input, distances, indices)
+
+
+def distance_transform_edt_signature(
+    input, sampling=None, return_distances=True, return_indices=False,
+    distances=None, indices=None
+):
+    return array_namespace(input, distances, indices)
+
+
+def find_objects_signature(input, max_label=0):
+    return array_namespace(input)
+
+
+def fourier_ellipsoid_signature(input, size, n=-1, axis=-1, output=None):
+    return array_namespace(input, _skip_if_dtype(output))
+
+fourier_uniform_signature = fourier_ellipsoid_signature
+
+
+def fourier_gaussian_signature(input, sigma, n=-1, axis=-1, output=None):
+    return array_namespace(input, _skip_if_dtype(output))
+
+def fourier_shift_signature(input, shift, n=-1, axis=-1, output=None):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_filter_signature(input, sigma, order=0, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_filter1d_signature(
+    input, sigma, axis=-1, order=0, output=None, *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_gradient_magnitude_signature(input, sigma, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+gaussian_laplace_signature = gaussian_gradient_magnitude_signature
+
+
+def generate_binary_structure_signature(rank, connectivity):
+    # XXX: no input arrays; always return numpy
+    return np
+
+
+def generic_filter_signature(
+    input, function, size=None, footprint=None, output=None, *args, **kwds
+):
+    # XXX: function LowLevelCallable w/backends
+    return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def generic_filter1d_signature(
+    input, function, filter_size, axis=-1, output=None, *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def generic_gradient_magnitude_signature(
+    input, derivative, output=None, *args, **kwds
+):
+    # XXX: function LowLevelCallable w/backends
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def generic_laplace_signature(input, derivative2, output=None, *args, **kwds):
+    # XXX: function LowLevelCallable w/backends
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def geometric_transform_signature(
+    input, mapping, output_shape=None, output=None, *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def histogram_signature(input, min, max, bins, labels=None, index=None):
+    return array_namespace(input, labels)
+
+
+def iterate_structure_signature(structure, iterations, origin=None):
+    return array_namespace(structure)
+
+
+def labeled_comprehension_signature(input, labels, *args, **kwds):
+    return array_namespace(input, labels)
+
+
+def laplace_signature(input, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def map_coordinates_signature(input, coordinates, output=None, *args, **kwds):
+    return array_namespace(input, coordinates, _skip_if_dtype(output))
+
+
+def maximum_filter1d_signature(input, size, axis=-1, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+minimum_filter1d_signature = maximum_filter1d_signature
+uniform_filter1d_signature = maximum_filter1d_signature
+
+
+def maximum_signature(input, labels=None, index=None):
+    return array_namespace(input, labels, _skip_if_int(index))
+
+minimum_signature = maximum_signature
+median_signature = maximum_signature
+mean_signature = maximum_signature
+variance_signature = maximum_signature
+standard_deviation_signature = maximum_signature
+sum_labels_signature = maximum_signature
+sum_signature = maximum_signature  # ndimage.sum is sum_labels
+
+maximum_position_signature = maximum_signature
+minimum_position_signature = maximum_signature
+
+extrema_signature = maximum_signature
+center_of_mass_signature = extrema_signature
+
+
+def median_filter_signature(
+    input, size=None, footprint=None, output=None, *args, **kwds
+):
+    return array_namespace(input, footprint, _skip_if_dtype(output))
+
+minimum_filter_signature = median_filter_signature
+maximum_filter_signature = median_filter_signature
+
+
+def morphological_gradient_signature(
+    input, size=None, footprint=None, structure=None, output=None, *args, **kwds
+):
+    return array_namespace(input, footprint, structure, _skip_if_dtype(output))
+
+morphological_laplace_signature = morphological_gradient_signature
+white_tophat_signature = morphological_gradient_signature
+black_tophat_signature = morphological_gradient_signature
+grey_closing_signature = morphological_gradient_signature
+grey_dilation_signature = morphological_gradient_signature
+grey_erosion_signature = morphological_gradient_signature
+grey_opening_signature = morphological_gradient_signature
+
+
+def percentile_filter_signature(
+    input, percentile, size=None, footprint=None, output=None, *args, **kwds
+):
+    return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def prewitt_signature(input, axis=-1, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+sobel_signature = prewitt_signature
+
+
+def rank_filter_signature(
+    input, rank, size=None, footprint=None, output=None, *args, **kwds
+):
+    return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def rotate_signature(
+    input, angle, axes=(1, 0), reshape=True, output=None , *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def shift_signature(input, shift, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def spline_filter_signature(input, order=3, output=np.float64, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def spline_filter1d_signature(
+    input, order=3, axis=-1, output=np.float64, *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def uniform_filter_signature(input, size=3, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def value_indices_signature(arr, *args, **kwds):
+    return array_namespace(arr)
+
+
+def watershed_ift_signature(input, markers, structure=None, output=None):
+    return array_namespace(input, markers, structure, _skip_if_dtype(output))
+
+
+def zoom_signature(input, zoom, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_filters.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..710ea60c03653cc80ac3bd1eefd425b4268a5246
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_filters.py
@@ -0,0 +1,1965 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# 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.
+
+from collections.abc import Iterable
+import numbers
+import warnings
+import numpy as np
+import operator
+
+from scipy._lib._util import normalize_axis_index
+from . import _ni_support
+from . import _nd_image
+from . import _ni_docstrings
+from . import _rank_filter_1d
+
+__all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter',
+           'prewitt', 'sobel', 'generic_laplace', 'laplace',
+           'gaussian_laplace', 'generic_gradient_magnitude',
+           'gaussian_gradient_magnitude', 'correlate', 'convolve',
+           'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
+           'maximum_filter1d', 'minimum_filter', 'maximum_filter',
+           'rank_filter', 'median_filter', 'percentile_filter',
+           'generic_filter1d', 'generic_filter']
+
+
+def _invalid_origin(origin, lenw):
+    return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2)
+
+
+def _complex_via_real_components(func, input, weights, output, cval, **kwargs):
+    """Complex convolution via a linear combination of real convolutions."""
+    complex_input = input.dtype.kind == 'c'
+    complex_weights = weights.dtype.kind == 'c'
+    if complex_input and complex_weights:
+        # real component of the output
+        func(input.real, weights.real, output=output.real,
+             cval=np.real(cval), **kwargs)
+        output.real -= func(input.imag, weights.imag, output=None,
+                            cval=np.imag(cval), **kwargs)
+        # imaginary component of the output
+        func(input.real, weights.imag, output=output.imag,
+             cval=np.real(cval), **kwargs)
+        output.imag += func(input.imag, weights.real, output=None,
+                            cval=np.imag(cval), **kwargs)
+    elif complex_input:
+        func(input.real, weights, output=output.real, cval=np.real(cval),
+             **kwargs)
+        func(input.imag, weights, output=output.imag, cval=np.imag(cval),
+             **kwargs)
+    else:
+        if np.iscomplexobj(cval):
+            raise ValueError("Cannot provide a complex-valued cval when the "
+                             "input is real.")
+        func(input, weights.real, output=output.real, cval=cval, **kwargs)
+        func(input, weights.imag, output=output.imag, cval=cval, **kwargs)
+    return output
+
+
+def _expand_origin(ndim_image, axes, origin):
+    num_axes = len(axes)
+    origins = _ni_support._normalize_sequence(origin, num_axes)
+    if num_axes < ndim_image:
+        # set origin = 0 for any axes not being filtered
+        origins_temp = [0,] * ndim_image
+        for o, ax in zip(origins, axes):
+            origins_temp[ax] = o
+        origins = origins_temp
+    return origins
+
+
+def _expand_footprint(ndim_image, axes, footprint,
+                      footprint_name="footprint"):
+    num_axes = len(axes)
+    if num_axes < ndim_image:
+        if footprint.ndim != num_axes:
+            raise RuntimeError(f"{footprint_name}.ndim ({footprint.ndim}) "
+                               f"must match len(axes) ({num_axes})")
+
+        footprint = np.expand_dims(
+            footprint,
+            tuple(ax for ax in range(ndim_image) if ax not in axes)
+        )
+    return footprint
+
+
+def _expand_mode(ndim_image, axes, mode):
+    num_axes = len(axes)
+    if not isinstance(mode, str) and isinstance(mode, Iterable):
+        # set mode = 'constant' for any axes not being filtered
+        modes = _ni_support._normalize_sequence(mode, num_axes)
+        modes_temp = ['constant'] * ndim_image
+        for m, ax in zip(modes, axes):
+            modes_temp[ax] = m
+        mode = modes_temp
+    return mode
+
+
+@_ni_docstrings.docfiller
+def correlate1d(input, weights, axis=-1, output=None, mode="reflect",
+                cval=0.0, origin=0):
+    """Calculate a 1-D correlation along the given axis.
+
+    The lines of the array along the given axis are correlated with the
+    given weights.
+
+    Parameters
+    ----------
+    %(input)s
+    weights : array
+        1-D sequence of numbers.
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    result : ndarray
+        Correlation result. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy.ndimage import correlate1d
+    >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
+    array([ 8, 26,  8, 12,  7, 28, 36,  9])
+    """
+    input = np.asarray(input)
+    weights = np.asarray(weights)
+    complex_input = input.dtype.kind == 'c'
+    complex_weights = weights.dtype.kind == 'c'
+    if complex_input or complex_weights:
+        if complex_weights:
+            weights = weights.conj()
+            weights = weights.astype(np.complex128, copy=False)
+        kwargs = dict(axis=axis, mode=mode, origin=origin)
+        output = _ni_support._get_output(output, input, complex_output=True)
+        return _complex_via_real_components(correlate1d, input, weights,
+                                            output, cval, **kwargs)
+
+    output = _ni_support._get_output(output, input)
+    weights = np.asarray(weights, dtype=np.float64)
+    if weights.ndim != 1 or weights.shape[0] < 1:
+        raise RuntimeError('no filter weights given')
+    if not weights.flags.contiguous:
+        weights = weights.copy()
+    axis = normalize_axis_index(axis, input.ndim)
+    if _invalid_origin(origin, len(weights)):
+        raise ValueError('Invalid origin; origin must satisfy '
+                         '-(len(weights) // 2) <= origin <= '
+                         '(len(weights)-1) // 2')
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.correlate1d(input, weights, axis, output, mode, cval,
+                          origin)
+    return output
+
+
+@_ni_docstrings.docfiller
+def convolve1d(input, weights, axis=-1, output=None, mode="reflect",
+               cval=0.0, origin=0):
+    """Calculate a 1-D convolution along the given axis.
+
+    The lines of the array along the given axis are convolved with the
+    given weights.
+
+    Parameters
+    ----------
+    %(input)s
+    weights : ndarray
+        1-D sequence of numbers.
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    convolve1d : ndarray
+        Convolved array with same shape as input
+
+    Examples
+    --------
+    >>> from scipy.ndimage import convolve1d
+    >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
+    array([14, 24,  4, 13, 12, 36, 27,  0])
+    """
+    weights = np.asarray(weights)
+    weights = weights[::-1]
+    origin = -origin
+    if not weights.shape[0] & 1:
+        origin -= 1
+    if weights.dtype.kind == 'c':
+        # pre-conjugate here to counteract the conjugation in correlate1d
+        weights = weights.conj()
+    return correlate1d(input, weights, axis, output, mode, cval, origin)
+
+
+def _gaussian_kernel1d(sigma, order, radius):
+    """
+    Computes a 1-D Gaussian convolution kernel.
+    """
+    if order < 0:
+        raise ValueError('order must be non-negative')
+    exponent_range = np.arange(order + 1)
+    sigma2 = sigma * sigma
+    x = np.arange(-radius, radius+1)
+    phi_x = np.exp(-0.5 / sigma2 * x ** 2)
+    phi_x = phi_x / phi_x.sum()
+
+    if order == 0:
+        return phi_x
+    else:
+        # f(x) = q(x) * phi(x) = q(x) * exp(p(x))
+        # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x)
+        # p'(x) = -1 / sigma ** 2
+        # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the
+        # coefficients of q(x)
+        q = np.zeros(order + 1)
+        q[0] = 1
+        D = np.diag(exponent_range[1:], 1)  # D @ q(x) = q'(x)
+        P = np.diag(np.ones(order)/-sigma2, -1)  # P @ q(x) = q(x) * p'(x)
+        Q_deriv = D + P
+        for _ in range(order):
+            q = Q_deriv.dot(q)
+        q = (x[:, None] ** exponent_range).dot(q)
+        return q * phi_x
+
+
+@_ni_docstrings.docfiller
+def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None,
+                      mode="reflect", cval=0.0, truncate=4.0, *, radius=None):
+    """1-D Gaussian filter.
+
+    Parameters
+    ----------
+    %(input)s
+    sigma : scalar
+        standard deviation for Gaussian kernel
+    %(axis)s
+    order : int, optional
+        An order of 0 corresponds to convolution with a Gaussian
+        kernel. A positive order corresponds to convolution with
+        that derivative of a Gaussian.
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    truncate : float, optional
+        Truncate the filter at this many standard deviations.
+        Default is 4.0.
+    radius : None or int, optional
+        Radius of the Gaussian kernel. If specified, the size of
+        the kernel will be ``2*radius + 1``, and `truncate` is ignored.
+        Default is None.
+
+    Returns
+    -------
+    gaussian_filter1d : ndarray
+
+    Notes
+    -----
+    The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
+    `radius` is None, a default ``radius = round(truncate * sigma)`` will be
+    used.
+
+    Examples
+    --------
+    >>> from scipy.ndimage import gaussian_filter1d
+    >>> import numpy as np
+    >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1)
+    array([ 1.42704095,  2.06782203,  3.        ,  3.93217797,  4.57295905])
+    >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4)
+    array([ 2.91948343,  2.95023502,  3.        ,  3.04976498,  3.08051657])
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = rng.standard_normal(101).cumsum()
+    >>> y3 = gaussian_filter1d(x, 3)
+    >>> y6 = gaussian_filter1d(x, 6)
+    >>> plt.plot(x, 'k', label='original data')
+    >>> plt.plot(y3, '--', label='filtered, sigma=3')
+    >>> plt.plot(y6, ':', label='filtered, sigma=6')
+    >>> plt.legend()
+    >>> plt.grid()
+    >>> plt.show()
+
+    """
+    sd = float(sigma)
+    # make the radius of the filter equal to truncate standard deviations
+    lw = int(truncate * sd + 0.5)
+    if radius is not None:
+        lw = radius
+    if not isinstance(lw, numbers.Integral) or lw < 0:
+        raise ValueError('Radius must be a nonnegative integer.')
+    # Since we are calling correlate, not convolve, revert the kernel
+    weights = _gaussian_kernel1d(sigma, order, lw)[::-1]
+    return correlate1d(input, weights, axis, output, mode, cval, 0)
+
+
+@_ni_docstrings.docfiller
+def gaussian_filter(input, sigma, order=0, output=None,
+                    mode="reflect", cval=0.0, truncate=4.0, *, radius=None,
+                    axes=None):
+    """Multidimensional Gaussian filter.
+
+    Parameters
+    ----------
+    %(input)s
+    sigma : scalar or sequence of scalars
+        Standard deviation for Gaussian kernel. The standard
+        deviations of the Gaussian filter are given for each axis as a
+        sequence, or as a single number, in which case it is equal for
+        all axes.
+    order : int or sequence of ints, optional
+        The order of the filter along each axis is given as a sequence
+        of integers, or as a single number. An order of 0 corresponds
+        to convolution with a Gaussian kernel. A positive order
+        corresponds to convolution with that derivative of a Gaussian.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    truncate : float, optional
+        Truncate the filter at this many standard deviations.
+        Default is 4.0.
+    radius : None or int or sequence of ints, optional
+        Radius of the Gaussian kernel. The radius are given for each axis
+        as a sequence, or as a single number, in which case it is equal
+        for all axes. If specified, the size of the kernel along each axis
+        will be ``2*radius + 1``, and `truncate` is ignored.
+        Default is None.
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `sigma`, `order`, `mode` and/or `radius`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    gaussian_filter : ndarray
+        Returned array of same shape as `input`.
+
+    Notes
+    -----
+    The multidimensional filter is implemented as a sequence of
+    1-D convolution filters. The intermediate arrays are
+    stored in the same data type as the output. Therefore, for output
+    types with a limited precision, the results may be imprecise
+    because intermediate results may be stored with insufficient
+    precision.
+
+    The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
+    `radius` is None, the default ``radius = round(truncate * sigma)`` will be
+    used.
+
+    Examples
+    --------
+    >>> from scipy.ndimage import gaussian_filter
+    >>> import numpy as np
+    >>> a = np.arange(50, step=2).reshape((5,5))
+    >>> a
+    array([[ 0,  2,  4,  6,  8],
+           [10, 12, 14, 16, 18],
+           [20, 22, 24, 26, 28],
+           [30, 32, 34, 36, 38],
+           [40, 42, 44, 46, 48]])
+    >>> gaussian_filter(a, sigma=1)
+    array([[ 4,  6,  8,  9, 11],
+           [10, 12, 14, 15, 17],
+           [20, 22, 24, 25, 27],
+           [29, 31, 33, 34, 36],
+           [35, 37, 39, 40, 42]])
+
+    >>> from scipy import datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = gaussian_filter(ascent, sigma=5)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _ni_support._get_output(output, input)
+
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    orders = _ni_support._normalize_sequence(order, num_axes)
+    sigmas = _ni_support._normalize_sequence(sigma, num_axes)
+    modes = _ni_support._normalize_sequence(mode, num_axes)
+    radiuses = _ni_support._normalize_sequence(radius, num_axes)
+    axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii], radiuses[ii])
+            for ii in range(num_axes) if sigmas[ii] > 1e-15]
+    if len(axes) > 0:
+        for axis, sigma, order, mode, radius in axes:
+            gaussian_filter1d(input, sigma, axis, order, output,
+                              mode, cval, truncate, radius=radius)
+            input = output
+    else:
+        output[...] = input[...]
+    return output
+
+
+@_ni_docstrings.docfiller
+def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0):
+    """Calculate a Prewitt filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(axis)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+
+    Returns
+    -------
+    prewitt : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    See Also
+    --------
+    sobel: Sobel filter
+
+    Notes
+    -----
+    This function computes the one-dimensional Prewitt filter.
+    Horizontal edges are emphasised with the horizontal transform (axis=0),
+    vertical edges with the vertical transform (axis=1), and so on for higher
+    dimensions. These can be combined to give the magnitude.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> ascent = datasets.ascent()
+    >>> prewitt_h = ndimage.prewitt(ascent, axis=0)
+    >>> prewitt_v = ndimage.prewitt(ascent, axis=1)
+    >>> magnitude = np.sqrt(prewitt_h ** 2 + prewitt_v ** 2)
+    >>> magnitude *= 255 / np.max(magnitude) # Normalization
+    >>> fig, axes = plt.subplots(2, 2, figsize = (8, 8))
+    >>> plt.gray()
+    >>> axes[0, 0].imshow(ascent)
+    >>> axes[0, 1].imshow(prewitt_h)
+    >>> axes[1, 0].imshow(prewitt_v)
+    >>> axes[1, 1].imshow(magnitude)
+    >>> titles = ["original", "horizontal", "vertical", "magnitude"]
+    >>> for i, ax in enumerate(axes.ravel()):
+    ...     ax.set_title(titles[i])
+    ...     ax.axis("off")
+    >>> plt.show()
+
+    """
+    input = np.asarray(input)
+    axis = normalize_axis_index(axis, input.ndim)
+    output = _ni_support._get_output(output, input)
+    modes = _ni_support._normalize_sequence(mode, input.ndim)
+    correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
+    axes = [ii for ii in range(input.ndim) if ii != axis]
+    for ii in axes:
+        correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,)
+    return output
+
+
+@_ni_docstrings.docfiller
+def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
+    """Calculate a Sobel filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(axis)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+
+    Returns
+    -------
+    sobel : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    This function computes the axis-specific Sobel gradient.
+    The horizontal edges can be emphasised with the horizontal transform (axis=0),
+    the vertical edges with the vertical transform (axis=1) and so on for higher
+    dimensions. These can be combined to give the magnitude.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> ascent = datasets.ascent().astype('int32')
+    >>> sobel_h = ndimage.sobel(ascent, 0)  # horizontal gradient
+    >>> sobel_v = ndimage.sobel(ascent, 1)  # vertical gradient
+    >>> magnitude = np.sqrt(sobel_h**2 + sobel_v**2)
+    >>> magnitude *= 255.0 / np.max(magnitude)  # normalization
+    >>> fig, axs = plt.subplots(2, 2, figsize=(8, 8))
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> axs[0, 0].imshow(ascent)
+    >>> axs[0, 1].imshow(sobel_h)
+    >>> axs[1, 0].imshow(sobel_v)
+    >>> axs[1, 1].imshow(magnitude)
+    >>> titles = ["original", "horizontal", "vertical", "magnitude"]
+    >>> for i, ax in enumerate(axs.ravel()):
+    ...     ax.set_title(titles[i])
+    ...     ax.axis("off")
+    >>> plt.show()
+
+    """
+    input = np.asarray(input)
+    axis = normalize_axis_index(axis, input.ndim)
+    output = _ni_support._get_output(output, input)
+    modes = _ni_support._normalize_sequence(mode, input.ndim)
+    correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
+    axes = [ii for ii in range(input.ndim) if ii != axis]
+    for ii in axes:
+        correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0)
+    return output
+
+
+@_ni_docstrings.docfiller
+def generic_laplace(input, derivative2, output=None, mode="reflect",
+                    cval=0.0,
+                    extra_arguments=(),
+                    extra_keywords=None,
+                    *, axes=None):
+    """
+    N-D Laplace filter using a provided second derivative function.
+
+    Parameters
+    ----------
+    %(input)s
+    derivative2 : callable
+        Callable with the following signature::
+
+            derivative2(input, axis, output, mode, cval,
+                        *extra_arguments, **extra_keywords)
+
+        See `extra_arguments`, `extra_keywords` below.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(extra_keywords)s
+    %(extra_arguments)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If a `mode` tuple is
+        provided, its length must match the number of axes.
+
+    Returns
+    -------
+    generic_laplace : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    """
+    if extra_keywords is None:
+        extra_keywords = {}
+    input = np.asarray(input)
+    output = _ni_support._get_output(output, input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    if len(axes) > 0:
+        modes = _ni_support._normalize_sequence(mode, len(axes))
+        derivative2(input, axes[0], output, modes[0], cval,
+                    *extra_arguments, **extra_keywords)
+        for ii in range(1, len(axes)):
+            tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval,
+                              *extra_arguments, **extra_keywords)
+            output += tmp
+    else:
+        output[...] = input[...]
+    return output
+
+
+@_ni_docstrings.docfiller
+def laplace(input, output=None, mode="reflect", cval=0.0, *, axes=None):
+    """N-D Laplace filter based on approximate second derivatives.
+
+    Parameters
+    ----------
+    %(input)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If a `mode` tuple is
+        provided, its length must match the number of axes.
+
+    Returns
+    -------
+    laplace : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.laplace(ascent)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    def derivative2(input, axis, output, mode, cval):
+        return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
+    return generic_laplace(input, derivative2, output, mode, cval, axes=axes)
+
+
+@_ni_docstrings.docfiller
+def gaussian_laplace(input, sigma, output=None, mode="reflect",
+                     cval=0.0, *, axes=None, **kwargs):
+    """Multidimensional Laplace filter using Gaussian second derivatives.
+
+    Parameters
+    ----------
+    %(input)s
+    sigma : scalar or sequence of scalars
+        The standard deviations of the Gaussian filter are given for
+        each axis as a sequence, or as a single number, in which case
+        it is equal for all axes.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If `sigma` or `mode` tuples
+        are provided, their length must match the number of axes.
+    Extra keyword arguments will be passed to gaussian_filter().
+
+    Returns
+    -------
+    gaussian_laplace : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> ascent = datasets.ascent()
+
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+
+    >>> result = ndimage.gaussian_laplace(ascent, sigma=1)
+    >>> ax1.imshow(result)
+
+    >>> result = ndimage.gaussian_laplace(ascent, sigma=3)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+
+    def derivative2(input, axis, output, mode, cval, sigma, **kwargs):
+        order = [0] * input.ndim
+        order[axis] = 2
+        return gaussian_filter(input, sigma, order, output, mode, cval,
+                               **kwargs)
+
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    sigma = _ni_support._normalize_sequence(sigma, num_axes)
+    if num_axes < input.ndim:
+        # set sigma = 0 for any axes not being filtered
+        sigma_temp = [0,] * input.ndim
+        for s, ax in zip(sigma, axes):
+            sigma_temp[ax] = s
+        sigma = sigma_temp
+
+    return generic_laplace(input, derivative2, output, mode, cval,
+                           extra_arguments=(sigma,),
+                           extra_keywords=kwargs,
+                           axes=axes)
+
+
+@_ni_docstrings.docfiller
+def generic_gradient_magnitude(input, derivative, output=None,
+                               mode="reflect", cval=0.0,
+                               extra_arguments=(), extra_keywords=None,
+                               *, axes=None):
+    """Gradient magnitude using a provided gradient function.
+
+    Parameters
+    ----------
+    %(input)s
+    derivative : callable
+        Callable with the following signature::
+
+            derivative(input, axis, output, mode, cval,
+                       *extra_arguments, **extra_keywords)
+
+        See `extra_arguments`, `extra_keywords` below.
+        `derivative` can assume that `input` and `output` are ndarrays.
+        Note that the output from `derivative` is modified inplace;
+        be careful to copy important inputs before returning them.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(extra_keywords)s
+    %(extra_arguments)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If a `mode` tuple is
+        provided, its length must match the number of axes.
+
+    Returns
+    -------
+    generic_gradient_matnitude : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    """
+    if extra_keywords is None:
+        extra_keywords = {}
+    input = np.asarray(input)
+    output = _ni_support._get_output(output, input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    if len(axes) > 0:
+        modes = _ni_support._normalize_sequence(mode, len(axes))
+        derivative(input, axes[0], output, modes[0], cval,
+                   *extra_arguments, **extra_keywords)
+        np.multiply(output, output, output)
+        for ii in range(1, len(axes)):
+            tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval,
+                             *extra_arguments, **extra_keywords)
+            np.multiply(tmp, tmp, tmp)
+            output += tmp
+        # This allows the sqrt to work with a different default casting
+        np.sqrt(output, output, casting='unsafe')
+    else:
+        output[...] = input[...]
+    return output
+
+
+@_ni_docstrings.docfiller
+def gaussian_gradient_magnitude(input, sigma, output=None,
+                                mode="reflect", cval=0.0, *, axes=None,
+                                **kwargs):
+    """Multidimensional gradient magnitude using Gaussian derivatives.
+
+    Parameters
+    ----------
+    %(input)s
+    sigma : scalar or sequence of scalars
+        The standard deviations of the Gaussian filter are given for
+        each axis as a sequence, or as a single number, in which case
+        it is equal for all axes.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If `sigma` or `mode` tuples
+        are provided, their length must match the number of axes.
+    Extra keyword arguments will be passed to gaussian_filter().
+
+    Returns
+    -------
+    gaussian_gradient_magnitude : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+
+    def derivative(input, axis, output, mode, cval, sigma, **kwargs):
+        order = [0] * input.ndim
+        order[axis] = 1
+        return gaussian_filter(input, sigma, order, output, mode,
+                               cval, **kwargs)
+
+    return generic_gradient_magnitude(input, derivative, output, mode,
+                                      cval, extra_arguments=(sigma,),
+                                      extra_keywords=kwargs, axes=axes)
+
+
+def _correlate_or_convolve(input, weights, output, mode, cval, origin,
+                           convolution, axes):
+    input = np.asarray(input)
+    weights = np.asarray(weights)
+    complex_input = input.dtype.kind == 'c'
+    complex_weights = weights.dtype.kind == 'c'
+    if complex_input or complex_weights:
+        if complex_weights and not convolution:
+            # As for np.correlate, conjugate weights rather than input.
+            weights = weights.conj()
+        kwargs = dict(
+            mode=mode, origin=origin, convolution=convolution, axes=axes
+        )
+        output = _ni_support._get_output(output, input, complex_output=True)
+
+        return _complex_via_real_components(_correlate_or_convolve, input,
+                                            weights, output, cval, **kwargs)
+
+    axes = _ni_support._check_axes(axes, input.ndim)
+    weights = np.asarray(weights, dtype=np.float64)
+
+    # expand weights and origins if num_axes < input.ndim
+    weights = _expand_footprint(input.ndim, axes, weights, "weights")
+    origins = _expand_origin(input.ndim, axes, origin)
+
+    wshape = [ii for ii in weights.shape if ii > 0]
+    if len(wshape) != input.ndim:
+        raise RuntimeError(f"weights.ndim ({len(wshape)}) must match "
+                           f"len(axes) ({len(axes)})")
+    if convolution:
+        weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
+        for ii in range(len(origins)):
+            origins[ii] = -origins[ii]
+            if not weights.shape[ii] & 1:
+                origins[ii] -= 1
+    for origin, lenw in zip(origins, wshape):
+        if _invalid_origin(origin, lenw):
+            raise ValueError('Invalid origin; origin must satisfy '
+                             '-(weights.shape[k] // 2) <= origin[k] <= '
+                             '(weights.shape[k]-1) // 2')
+
+    if not weights.flags.contiguous:
+        weights = weights.copy()
+    output = _ni_support._get_output(output, input)
+    temp_needed = np.may_share_memory(input, output)
+    if temp_needed:
+        # input and output arrays cannot share memory
+        temp = output
+        output = _ni_support._get_output(output.dtype, input)
+    if not isinstance(mode, str) and isinstance(mode, Iterable):
+        raise RuntimeError("A sequence of modes is not supported")
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.correlate(input, weights, output, mode, cval, origins)
+    if temp_needed:
+        temp[...] = output
+        output = temp
+    return output
+
+
+@_ni_docstrings.docfiller
+def correlate(input, weights, output=None, mode='reflect', cval=0.0,
+              origin=0, *, axes=None):
+    """
+    Multidimensional correlation.
+
+    The array is correlated with the given kernel.
+
+    Parameters
+    ----------
+    %(input)s
+    weights : ndarray
+        array of weights, same number of dimensions as input
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `mode` or `origin` must match the length
+        of `axes`. The ith entry in any of these tuples corresponds to the ith
+        entry in `axes`.
+
+    Returns
+    -------
+    result : ndarray
+        The result of correlation of `input` with `weights`.
+
+    See Also
+    --------
+    convolve : Convolve an image with a kernel.
+
+    Examples
+    --------
+    Correlation is the process of moving a filter mask often referred to
+    as kernel over the image and computing the sum of products at each location.
+
+    >>> from scipy.ndimage import correlate
+    >>> import numpy as np
+    >>> input_img = np.arange(25).reshape(5,5)
+    >>> print(input_img)
+    [[ 0  1  2  3  4]
+    [ 5  6  7  8  9]
+    [10 11 12 13 14]
+    [15 16 17 18 19]
+    [20 21 22 23 24]]
+
+    Define a kernel (weights) for correlation. In this example, it is for sum of
+    center and up, down, left and right next elements.
+
+    >>> weights = [[0, 1, 0],
+    ...            [1, 1, 1],
+    ...            [0, 1, 0]]
+
+    We can calculate a correlation result:
+    For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``.
+
+    >>> correlate(input_img, weights)
+    array([[  6,  10,  15,  20,  24],
+        [ 26,  30,  35,  40,  44],
+        [ 51,  55,  60,  65,  69],
+        [ 76,  80,  85,  90,  94],
+        [ 96, 100, 105, 110, 114]])
+
+    """
+    return _correlate_or_convolve(input, weights, output, mode, cval,
+                                  origin, False, axes)
+
+
+@_ni_docstrings.docfiller
+def convolve(input, weights, output=None, mode='reflect', cval=0.0,
+             origin=0, *, axes=None):
+    """
+    Multidimensional convolution.
+
+    The array is convolved with the given kernel.
+
+    Parameters
+    ----------
+    %(input)s
+    weights : array_like
+        Array of weights, same number of dimensions as input
+    %(output)s
+    %(mode_reflect)s
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0
+    origin : int or sequence, optional
+        Controls the placement of the filter on the input array's pixels.
+        A value of 0 (the default) centers the filter over the pixel, with
+        positive values shifting the filter to the right, and negative ones
+        to the left. By passing a sequence of origins with length equal to
+        the number of dimensions of the input array, different shifts can
+        be specified along each axis.
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `mode` or `origin` must match the length
+        of `axes`. The ith entry in any of these tuples corresponds to the ith
+        entry in `axes`.
+
+    Returns
+    -------
+    result : ndarray
+        The result of convolution of `input` with `weights`.
+
+    See Also
+    --------
+    correlate : Correlate an image with a kernel.
+
+    Notes
+    -----
+    Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
+    W is the `weights` kernel,
+    j is the N-D spatial index over :math:`W`,
+    I is the `input` and k is the coordinate of the center of
+    W, specified by `origin` in the input parameters.
+
+    Examples
+    --------
+    Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
+    because in this case borders (i.e., where the `weights` kernel, centered
+    on any one value, extends beyond an edge of `input`) are treated as zeros.
+
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
+    >>> from scipy import ndimage
+    >>> ndimage.convolve(a, k, mode='constant', cval=0.0)
+    array([[11, 10,  7,  4],
+           [10,  3, 11, 11],
+           [15, 12, 14,  7],
+           [12,  3,  7,  0]])
+
+    Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
+    with 1.0's (and then extracting only the original region of the result).
+
+    >>> ndimage.convolve(a, k, mode='constant', cval=1.0)
+    array([[13, 11,  8,  7],
+           [11,  3, 11, 14],
+           [16, 12, 14, 10],
+           [15,  6, 10,  5]])
+
+    With ``mode='reflect'`` (the default), outer values are reflected at the
+    edge of `input` to fill in missing values.
+
+    >>> b = np.array([[2, 0, 0],
+    ...               [1, 0, 0],
+    ...               [0, 0, 0]])
+    >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
+    >>> ndimage.convolve(b, k, mode='reflect')
+    array([[5, 0, 0],
+           [3, 0, 0],
+           [1, 0, 0]])
+
+    This includes diagonally at the corners.
+
+    >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
+    >>> ndimage.convolve(b, k)
+    array([[4, 2, 0],
+           [3, 2, 0],
+           [1, 1, 0]])
+
+    With ``mode='nearest'``, the single nearest value in to an edge in
+    `input` is repeated as many times as needed to match the overlapping
+    `weights`.
+
+    >>> c = np.array([[2, 0, 1],
+    ...               [1, 0, 0],
+    ...               [0, 0, 0]])
+    >>> k = np.array([[0, 1, 0],
+    ...               [0, 1, 0],
+    ...               [0, 1, 0],
+    ...               [0, 1, 0],
+    ...               [0, 1, 0]])
+    >>> ndimage.convolve(c, k, mode='nearest')
+    array([[7, 0, 3],
+           [5, 0, 2],
+           [3, 0, 1]])
+
+    """
+    return _correlate_or_convolve(input, weights, output, mode, cval,
+                                  origin, True, axes)
+
+
+@_ni_docstrings.docfiller
+def uniform_filter1d(input, size, axis=-1, output=None,
+                     mode="reflect", cval=0.0, origin=0):
+    """Calculate a 1-D uniform filter along the given axis.
+
+    The lines of the array along the given axis are filtered with a
+    uniform filter of given size.
+
+    Parameters
+    ----------
+    %(input)s
+    size : int
+        length of uniform filter
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    result : ndarray
+        Filtered array. Has same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy.ndimage import uniform_filter1d
+    >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+    array([4, 3, 4, 1, 4, 6, 6, 3])
+    """
+    input = np.asarray(input)
+    axis = normalize_axis_index(axis, input.ndim)
+    if size < 1:
+        raise RuntimeError('incorrect filter size')
+    complex_output = input.dtype.kind == 'c'
+    output = _ni_support._get_output(output, input,
+                                     complex_output=complex_output)
+    if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+        raise ValueError('invalid origin')
+    mode = _ni_support._extend_mode_to_code(mode)
+    if not complex_output:
+        _nd_image.uniform_filter1d(input, size, axis, output, mode, cval,
+                                   origin)
+    else:
+        _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode,
+                                   np.real(cval), origin)
+        _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode,
+                                   np.imag(cval), origin)
+    return output
+
+
+@_ni_docstrings.docfiller
+def uniform_filter(input, size=3, output=None, mode="reflect",
+                   cval=0.0, origin=0, *, axes=None):
+    """Multidimensional uniform filter.
+
+    Parameters
+    ----------
+    %(input)s
+    size : int or sequence of ints, optional
+        The sizes of the uniform filter are given for each axis as a
+        sequence, or as a single number, in which case the size is
+        equal for all axes.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    uniform_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    The multidimensional filter is implemented as a sequence of
+    1-D uniform filters. The intermediate arrays are stored
+    in the same data type as the output. Therefore, for output types
+    with a limited precision, the results may be imprecise because
+    intermediate results may be stored with insufficient precision.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.uniform_filter(ascent, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _ni_support._get_output(output, input,
+                                     complex_output=input.dtype.kind == 'c')
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    sizes = _ni_support._normalize_sequence(size, num_axes)
+    origins = _ni_support._normalize_sequence(origin, num_axes)
+    modes = _ni_support._normalize_sequence(mode, num_axes)
+    axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
+            for ii in range(num_axes) if sizes[ii] > 1]
+    if len(axes) > 0:
+        for axis, size, origin, mode in axes:
+            uniform_filter1d(input, int(size), axis, output, mode,
+                             cval, origin)
+            input = output
+    else:
+        output[...] = input[...]
+    return output
+
+
+@_ni_docstrings.docfiller
+def minimum_filter1d(input, size, axis=-1, output=None,
+                     mode="reflect", cval=0.0, origin=0):
+    """Calculate a 1-D minimum filter along the given axis.
+
+    The lines of the array along the given axis are filtered with a
+    minimum filter of given size.
+
+    Parameters
+    ----------
+    %(input)s
+    size : int
+        length along which to calculate 1D minimum
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    result : ndarray.
+        Filtered image. Has the same shape as `input`.
+
+    Notes
+    -----
+    This function implements the MINLIST algorithm [1]_, as described by
+    Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
+    the `input` length, regardless of filter size.
+
+    References
+    ----------
+    .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
+    .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
+
+
+    Examples
+    --------
+    >>> from scipy.ndimage import minimum_filter1d
+    >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+    array([2, 0, 0, 0, 1, 1, 0, 0])
+    """
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axis = normalize_axis_index(axis, input.ndim)
+    if size < 1:
+        raise RuntimeError('incorrect filter size')
+    output = _ni_support._get_output(output, input)
+    if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+        raise ValueError('invalid origin')
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
+                                  origin, 1)
+    return output
+
+
+@_ni_docstrings.docfiller
+def maximum_filter1d(input, size, axis=-1, output=None,
+                     mode="reflect", cval=0.0, origin=0):
+    """Calculate a 1-D maximum filter along the given axis.
+
+    The lines of the array along the given axis are filtered with a
+    maximum filter of given size.
+
+    Parameters
+    ----------
+    %(input)s
+    size : int
+        Length along which to calculate the 1-D maximum.
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    maximum1d : ndarray, None
+        Maximum-filtered array with same shape as input.
+        None if `output` is not None
+
+    Notes
+    -----
+    This function implements the MAXLIST algorithm [1]_, as described by
+    Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
+    the `input` length, regardless of filter size.
+
+    References
+    ----------
+    .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
+    .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
+
+    Examples
+    --------
+    >>> from scipy.ndimage import maximum_filter1d
+    >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+    array([8, 8, 8, 4, 9, 9, 9, 9])
+    """
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axis = normalize_axis_index(axis, input.ndim)
+    if size < 1:
+        raise RuntimeError('incorrect filter size')
+    output = _ni_support._get_output(output, input)
+    if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+        raise ValueError('invalid origin')
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
+                                  origin, 0)
+    return output
+
+
+def _min_or_max_filter(input, size, footprint, structure, output, mode,
+                       cval, origin, minimum, axes=None):
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=3)
+    if structure is None:
+        if footprint is None:
+            if size is None:
+                raise RuntimeError("no footprint provided")
+            separable = True
+        else:
+            footprint = np.asarray(footprint, dtype=bool)
+            if not footprint.any():
+                raise ValueError("All-zero footprint is not supported.")
+            if footprint.all():
+                size = footprint.shape
+                footprint = None
+                separable = True
+            else:
+                separable = False
+    else:
+        structure = np.asarray(structure, dtype=np.float64)
+        separable = False
+        if footprint is None:
+            footprint = np.ones(structure.shape, bool)
+        else:
+            footprint = np.asarray(footprint, dtype=bool)
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError("Complex type not supported")
+    output = _ni_support._get_output(output, input)
+    temp_needed = np.may_share_memory(input, output)
+    if temp_needed:
+        # input and output arrays cannot share memory
+        temp = output
+        output = _ni_support._get_output(output.dtype, input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if separable:
+        origins = _ni_support._normalize_sequence(origin, num_axes)
+        sizes = _ni_support._normalize_sequence(size, num_axes)
+        modes = _ni_support._normalize_sequence(mode, num_axes)
+        axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
+                for ii in range(len(axes)) if sizes[ii] > 1]
+        if minimum:
+            filter_ = minimum_filter1d
+        else:
+            filter_ = maximum_filter1d
+        if len(axes) > 0:
+            for axis, size, origin, mode in axes:
+                filter_(input, int(size), axis, output, mode, cval, origin)
+                input = output
+        else:
+            output[...] = input[...]
+    else:
+        # expand origins and footprint if num_axes < input.ndim
+        footprint = _expand_footprint(input.ndim, axes, footprint)
+        origins = _expand_origin(input.ndim, axes, origin)
+
+        fshape = [ii for ii in footprint.shape if ii > 0]
+        if len(fshape) != input.ndim:
+            raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
+                               f"len(axes) ({len(axes)})")
+        for origin, lenf in zip(origins, fshape):
+            if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+                raise ValueError("invalid origin")
+        if not footprint.flags.contiguous:
+            footprint = footprint.copy()
+        if structure is not None:
+            if len(structure.shape) != num_axes:
+                raise RuntimeError("structure array has incorrect shape")
+            if num_axes != structure.ndim:
+                structure = np.expand_dims(
+                    structure,
+                    tuple(ax for ax in range(structure.ndim) if ax not in axes)
+                )
+            if not structure.flags.contiguous:
+                structure = structure.copy()
+        if not isinstance(mode, str) and isinstance(mode, Iterable):
+            raise RuntimeError(
+                "A sequence of modes is not supported for non-separable "
+                "footprints")
+        mode = _ni_support._extend_mode_to_code(mode)
+        _nd_image.min_or_max_filter(input, footprint, structure, output,
+                                    mode, cval, origins, minimum)
+    if temp_needed:
+        temp[...] = output
+        output = temp
+    return output
+
+
+@_ni_docstrings.docfiller
+def minimum_filter(input, size=None, footprint=None, output=None,
+                   mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """Calculate a multidimensional minimum filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(size_foot)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    minimum_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    A sequence of modes (one per axis) is only supported when the footprint is
+    separable. Otherwise, a single mode string must be provided.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.minimum_filter(ascent, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    return _min_or_max_filter(input, size, footprint, None, output, mode,
+                              cval, origin, 1, axes)
+
+
+@_ni_docstrings.docfiller
+def maximum_filter(input, size=None, footprint=None, output=None,
+                   mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """Calculate a multidimensional maximum filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(size_foot)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    maximum_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    A sequence of modes (one per axis) is only supported when the footprint is
+    separable. Otherwise, a single mode string must be provided.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.maximum_filter(ascent, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    return _min_or_max_filter(input, size, footprint, None, output, mode,
+                              cval, origin, 0, axes)
+
+
+@_ni_docstrings.docfiller
+def _rank_filter(input, rank, size=None, footprint=None, output=None,
+                 mode="reflect", cval=0.0, origin=0, operation='rank',
+                 axes=None):
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=3)
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if footprint is None:
+        if size is None:
+            raise RuntimeError("no footprint or filter size provided")
+        sizes = _ni_support._normalize_sequence(size, num_axes)
+        footprint = np.ones(sizes, dtype=bool)
+    else:
+        footprint = np.asarray(footprint, dtype=bool)
+    # expand origins, footprint and modes if num_axes < input.ndim
+    footprint = _expand_footprint(input.ndim, axes, footprint)
+    origins = _expand_origin(input.ndim, axes, origin)
+    mode = _expand_mode(input.ndim, axes, mode)
+
+    fshape = [ii for ii in footprint.shape if ii > 0]
+    if len(fshape) != input.ndim:
+        raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
+                           f"len(axes) ({len(axes)})")
+    for origin, lenf in zip(origins, fshape):
+        if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+            raise ValueError('invalid origin')
+    if not footprint.flags.contiguous:
+        footprint = footprint.copy()
+    filter_size = np.where(footprint, 1, 0).sum()
+    if operation == 'median':
+        rank = filter_size // 2
+    elif operation == 'percentile':
+        percentile = rank
+        if percentile < 0.0:
+            percentile += 100.0
+        if percentile < 0 or percentile > 100:
+            raise RuntimeError('invalid percentile')
+        if percentile == 100.0:
+            rank = filter_size - 1
+        else:
+            rank = int(float(filter_size) * percentile / 100.0)
+    if rank < 0:
+        rank += filter_size
+    if rank < 0 or rank >= filter_size:
+        raise RuntimeError('rank not within filter footprint size')
+    if rank == 0:
+        return minimum_filter(input, None, footprint, output, mode, cval,
+                              origins, axes=None)
+    elif rank == filter_size - 1:
+        return maximum_filter(input, None, footprint, output, mode, cval,
+                              origins, axes=None)
+    else:
+        output = _ni_support._get_output(output, input)
+        temp_needed = np.may_share_memory(input, output)
+        if temp_needed:
+            # input and output arrays cannot share memory
+            temp = output
+            output = _ni_support._get_output(output.dtype, input)
+        if not isinstance(mode, str) and isinstance(mode, Iterable):
+            raise RuntimeError(
+                "A sequence of modes is not supported by non-separable rank "
+                "filters")
+        mode = _ni_support._extend_mode_to_code(mode, is_filter=True)
+        if input.ndim == 1:
+            if input.dtype in (np.int64, np.float64, np.float32):
+                x = input
+                x_out = output
+            elif input.dtype == np.float16:
+                x = input.astype('float32')
+                x_out = np.empty(x.shape, dtype='float32')
+            elif np.result_type(input, np.int64) == np.int64:
+                x = input.astype('int64')
+                x_out = np.empty(x.shape, dtype='int64')
+            elif input.dtype.kind in 'biu':
+                # cast any other boolean, integer or unsigned type to int64
+                x = input.astype('int64')
+                x_out = np.empty(x.shape, dtype='int64')
+            else:
+                raise RuntimeError('Unsupported array type')
+            cval = x.dtype.type(cval)
+            _rank_filter_1d.rank_filter(x, rank, footprint.size, x_out, mode, cval,
+                                        origin)
+            if input.dtype not in (np.int64, np.float64, np.float32):
+                np.copyto(output, x_out, casting='unsafe')
+        else:
+            _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins)
+        if temp_needed:
+            temp[...] = output
+            output = temp
+        return output
+
+
+@_ni_docstrings.docfiller
+def rank_filter(input, rank, size=None, footprint=None, output=None,
+                mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """Calculate a multidimensional rank filter.
+
+    Parameters
+    ----------
+    %(input)s
+    rank : int
+        The rank parameter may be less than zero, i.e., rank = -1
+        indicates the largest element.
+    %(size_foot)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    rank_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    rank = operator.index(rank)
+    return _rank_filter(input, rank, size, footprint, output, mode, cval,
+                        origin, 'rank', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def median_filter(input, size=None, footprint=None, output=None,
+                  mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """
+    Calculate a multidimensional median filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(size_foot)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    median_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    See Also
+    --------
+    scipy.signal.medfilt2d
+
+    Notes
+    -----
+    For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes
+    the specialised function `scipy.signal.medfilt2d` may be faster. It is
+    however limited to constant mode with ``cval=0``.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.median_filter(ascent, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    return _rank_filter(input, 0, size, footprint, output, mode, cval,
+                        origin, 'median', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def percentile_filter(input, percentile, size=None, footprint=None,
+                      output=None, mode="reflect", cval=0.0, origin=0, *,
+                      axes=None):
+    """Calculate a multidimensional percentile filter.
+
+    Parameters
+    ----------
+    %(input)s
+    percentile : scalar
+        The percentile parameter may be less than zero, i.e.,
+        percentile = -20 equals percentile = 80
+    %(size_foot)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    percentile_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    return _rank_filter(input, percentile, size, footprint, output, mode,
+                        cval, origin, 'percentile', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def generic_filter1d(input, function, filter_size, axis=-1,
+                     output=None, mode="reflect", cval=0.0, origin=0,
+                     extra_arguments=(), extra_keywords=None):
+    """Calculate a 1-D filter along the given axis.
+
+    `generic_filter1d` iterates over the lines of the array, calling the
+    given function at each line. The arguments of the line are the
+    input line, and the output line. The input and output lines are 1-D
+    double arrays. The input line is extended appropriately according
+    to the filter size and origin. The output line must be modified
+    in-place with the result.
+
+    Parameters
+    ----------
+    %(input)s
+    function : {callable, scipy.LowLevelCallable}
+        Function to apply along given axis.
+    filter_size : scalar
+        Length of the filter.
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+    %(extra_arguments)s
+    %(extra_keywords)s
+
+    Returns
+    -------
+    generic_filter1d : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    This function also accepts low-level callback functions with one of
+    the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+    .. code:: c
+
+       int function(double *input_line, npy_intp input_length,
+                    double *output_line, npy_intp output_length,
+                    void *user_data)
+       int function(double *input_line, intptr_t input_length,
+                    double *output_line, intptr_t output_length,
+                    void *user_data)
+
+    The calling function iterates over the lines of the input and output
+    arrays, calling the callback function at each line. The current line
+    is extended according to the border conditions set by the calling
+    function, and the result is copied into the array that is passed
+    through ``input_line``. The length of the input line (after extension)
+    is passed through ``input_length``. The callback function should apply
+    the filter and store the result in the array passed through
+    ``output_line``. The length of the output line is passed through
+    ``output_length``. ``user_data`` is the data pointer provided
+    to `scipy.LowLevelCallable` as-is.
+
+    The callback function must return an integer error status that is zero
+    if something went wrong and one otherwise. If an error occurs, you should
+    normally set the python error status with an informative message
+    before returning, otherwise a default error message is set by the
+    calling function.
+
+    In addition, some other low-level function pointer specifications
+    are accepted, but these are for backward compatibility only and should
+    not be used in new code.
+
+    """
+    if extra_keywords is None:
+        extra_keywords = {}
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    output = _ni_support._get_output(output, input)
+    if filter_size < 1:
+        raise RuntimeError('invalid filter size')
+    axis = normalize_axis_index(axis, input.ndim)
+    if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >=
+                                           filter_size):
+        raise ValueError('invalid origin')
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.generic_filter1d(input, function, filter_size, axis, output,
+                               mode, cval, origin, extra_arguments,
+                               extra_keywords)
+    return output
+
+
+@_ni_docstrings.docfiller
+def generic_filter(input, function, size=None, footprint=None,
+                   output=None, mode="reflect", cval=0.0, origin=0,
+                   extra_arguments=(), extra_keywords=None, *, axes=None):
+    """Calculate a multidimensional filter using the given function.
+
+    At each element the provided function is called. The input values
+    within the filter footprint at that element are passed to the function
+    as a 1-D array of double values.
+
+    Parameters
+    ----------
+    %(input)s
+    function : {callable, scipy.LowLevelCallable}
+        Function to apply at each element.
+    %(size_foot)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    %(extra_arguments)s
+    %(extra_keywords)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size` or `origin` must match the length
+        of `axes`. The ith entry in any of these tuples corresponds to the ith
+        entry in `axes`.
+
+    Returns
+    -------
+    generic_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    This function also accepts low-level callback functions with one of
+    the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+    .. code:: c
+
+       int callback(double *buffer, npy_intp filter_size,
+                    double *return_value, void *user_data)
+       int callback(double *buffer, intptr_t filter_size,
+                    double *return_value, void *user_data)
+
+    The calling function iterates over the elements of the input and
+    output arrays, calling the callback function at each element. The
+    elements within the footprint of the filter at the current element are
+    passed through the ``buffer`` parameter, and the number of elements
+    within the footprint through ``filter_size``. The calculated value is
+    returned in ``return_value``. ``user_data`` is the data pointer provided
+    to `scipy.LowLevelCallable` as-is.
+
+    The callback function must return an integer error status that is zero
+    if something went wrong and one otherwise. If an error occurs, you should
+    normally set the python error status with an informative message
+    before returning, otherwise a default error message is set by the
+    calling function.
+
+    In addition, some other low-level function pointer specifications
+    are accepted, but these are for backward compatibility only and should
+    not be used in new code.
+
+    Examples
+    --------
+    Import the necessary modules and load the example image used for
+    filtering.
+
+    >>> import numpy as np
+    >>> from scipy import datasets
+    >>> from scipy.ndimage import zoom, generic_filter
+    >>> import matplotlib.pyplot as plt
+    >>> ascent = zoom(datasets.ascent(), 0.5)
+
+    Compute a maximum filter with kernel size 5 by passing a simple NumPy
+    aggregation function as argument to `function`.
+
+    >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5])
+
+    While a maximum filter could also directly be obtained using
+    `maximum_filter`, `generic_filter` allows generic Python function or
+    `scipy.LowLevelCallable` to be used as a filter. Here, we compute the
+    range between maximum and minimum value as an example for a kernel size
+    of 5.
+
+    >>> def custom_filter(image):
+    ...     return np.amax(image) - np.amin(image)
+    >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5])
+
+    Plot the original and filtered images.
+
+    >>> fig, axes = plt.subplots(3, 1, figsize=(3, 9))
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> top, middle, bottom = axes
+    >>> for ax in axes:
+    ...     ax.set_axis_off()  # remove coordinate system
+    >>> top.imshow(ascent)
+    >>> top.set_title("Original image")
+    >>> middle.imshow(maximum_filter_result)
+    >>> middle.set_title("Maximum filter, Kernel: 5x5")
+    >>> bottom.imshow(custom_filter_result)
+    >>> bottom.set_title("Custom filter, Kernel: 5x5")
+    >>> fig.tight_layout()
+
+    """
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    if extra_keywords is None:
+        extra_keywords = {}
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if footprint is None:
+        if size is None:
+            raise RuntimeError("no footprint or filter size provided")
+        sizes = _ni_support._normalize_sequence(size, num_axes)
+        footprint = np.ones(sizes, dtype=bool)
+    else:
+        footprint = np.asarray(footprint, dtype=bool)
+
+    # expand origins, footprint if num_axes < input.ndim
+    footprint = _expand_footprint(input.ndim, axes, footprint)
+    origins = _expand_origin(input.ndim, axes, origin)
+
+    fshape = [ii for ii in footprint.shape if ii > 0]
+    if len(fshape) != input.ndim:
+        raise RuntimeError(f"footprint.ndim ({footprint.ndim}) "
+                           f"must match len(axes) ({num_axes})")
+    for origin, lenf in zip(origins, fshape):
+        if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+            raise ValueError('invalid origin')
+    if not footprint.flags.contiguous:
+        footprint = footprint.copy()
+    output = _ni_support._get_output(output, input)
+
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.generic_filter(input, function, footprint, output, mode,
+                             cval, origins, extra_arguments, extra_keywords)
+    return output
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_fourier.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb5ffa6b9287cb740611aefba5f1f322011518cf
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_fourier.py
@@ -0,0 +1,306 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# 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 scipy._lib._util import normalize_axis_index
+from . import _ni_support
+from . import _nd_image
+
+__all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid',
+           'fourier_shift']
+
+
+def _get_output_fourier(output, input):
+    if output is None:
+        if input.dtype.type in [np.complex64, np.complex128, np.float32]:
+            output = np.zeros(input.shape, dtype=input.dtype)
+        else:
+            output = np.zeros(input.shape, dtype=np.float64)
+    elif type(output) is type:
+        if output not in [np.complex64, np.complex128,
+                          np.float32, np.float64]:
+            raise RuntimeError("output type not supported")
+        output = np.zeros(input.shape, dtype=output)
+    elif output.shape != input.shape:
+        raise RuntimeError("output shape not correct")
+    return output
+
+
+def _get_output_fourier_complex(output, input):
+    if output is None:
+        if input.dtype.type in [np.complex64, np.complex128]:
+            output = np.zeros(input.shape, dtype=input.dtype)
+        else:
+            output = np.zeros(input.shape, dtype=np.complex128)
+    elif type(output) is type:
+        if output not in [np.complex64, np.complex128]:
+            raise RuntimeError("output type not supported")
+        output = np.zeros(input.shape, dtype=output)
+    elif output.shape != input.shape:
+        raise RuntimeError("output shape not correct")
+    return output
+
+
+def fourier_gaussian(input, sigma, n=-1, axis=-1, output=None):
+    """
+    Multidimensional Gaussian fourier filter.
+
+    The array is multiplied with the fourier transform of a Gaussian
+    kernel.
+
+    Parameters
+    ----------
+    input : array_like
+        The input array.
+    sigma : float or sequence
+        The sigma of the Gaussian kernel. If a float, `sigma` is the same for
+        all axes. If a sequence, `sigma` has to contain one value for each
+        axis.
+    n : int, optional
+        If `n` is negative (default), then the input is assumed to be the
+        result of a complex fft.
+        If `n` is larger than or equal to zero, the input is assumed to be the
+        result of a real fft, and `n` gives the length of the array before
+        transformation along the real transform direction.
+    axis : int, optional
+        The axis of the real transform.
+    output : ndarray, optional
+        If given, the result of filtering the input is placed in this array.
+
+    Returns
+    -------
+    fourier_gaussian : ndarray
+        The filtered input.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import numpy.fft
+    >>> import matplotlib.pyplot as plt
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ascent = datasets.ascent()
+    >>> input_ = numpy.fft.fft2(ascent)
+    >>> result = ndimage.fourier_gaussian(input_, sigma=4)
+    >>> result = numpy.fft.ifft2(result)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result.real)  # the imaginary part is an artifact
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _get_output_fourier(output, input)
+    axis = normalize_axis_index(axis, input.ndim)
+    sigmas = _ni_support._normalize_sequence(sigma, input.ndim)
+    sigmas = np.asarray(sigmas, dtype=np.float64)
+    if not sigmas.flags.contiguous:
+        sigmas = sigmas.copy()
+
+    _nd_image.fourier_filter(input, sigmas, n, axis, output, 0)
+    return output
+
+
+def fourier_uniform(input, size, n=-1, axis=-1, output=None):
+    """
+    Multidimensional uniform fourier filter.
+
+    The array is multiplied with the Fourier transform of a box of given
+    size.
+
+    Parameters
+    ----------
+    input : array_like
+        The input array.
+    size : float or sequence
+        The size of the box used for filtering.
+        If a float, `size` is the same for all axes. If a sequence, `size` has
+        to contain one value for each axis.
+    n : int, optional
+        If `n` is negative (default), then the input is assumed to be the
+        result of a complex fft.
+        If `n` is larger than or equal to zero, the input is assumed to be the
+        result of a real fft, and `n` gives the length of the array before
+        transformation along the real transform direction.
+    axis : int, optional
+        The axis of the real transform.
+    output : ndarray, optional
+        If given, the result of filtering the input is placed in this array.
+
+    Returns
+    -------
+    fourier_uniform : ndarray
+        The filtered input.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import numpy.fft
+    >>> import matplotlib.pyplot as plt
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ascent = datasets.ascent()
+    >>> input_ = numpy.fft.fft2(ascent)
+    >>> result = ndimage.fourier_uniform(input_, size=20)
+    >>> result = numpy.fft.ifft2(result)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result.real)  # the imaginary part is an artifact
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _get_output_fourier(output, input)
+    axis = normalize_axis_index(axis, input.ndim)
+    sizes = _ni_support._normalize_sequence(size, input.ndim)
+    sizes = np.asarray(sizes, dtype=np.float64)
+    if not sizes.flags.contiguous:
+        sizes = sizes.copy()
+    _nd_image.fourier_filter(input, sizes, n, axis, output, 1)
+    return output
+
+
+def fourier_ellipsoid(input, size, n=-1, axis=-1, output=None):
+    """
+    Multidimensional ellipsoid Fourier filter.
+
+    The array is multiplied with the fourier transform of an ellipsoid of
+    given sizes.
+
+    Parameters
+    ----------
+    input : array_like
+        The input array.
+    size : float or sequence
+        The size of the box used for filtering.
+        If a float, `size` is the same for all axes. If a sequence, `size` has
+        to contain one value for each axis.
+    n : int, optional
+        If `n` is negative (default), then the input is assumed to be the
+        result of a complex fft.
+        If `n` is larger than or equal to zero, the input is assumed to be the
+        result of a real fft, and `n` gives the length of the array before
+        transformation along the real transform direction.
+    axis : int, optional
+        The axis of the real transform.
+    output : ndarray, optional
+        If given, the result of filtering the input is placed in this array.
+
+    Returns
+    -------
+    fourier_ellipsoid : ndarray
+        The filtered input.
+
+    Notes
+    -----
+    This function is implemented for arrays of rank 1, 2, or 3.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import numpy.fft
+    >>> import matplotlib.pyplot as plt
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ascent = datasets.ascent()
+    >>> input_ = numpy.fft.fft2(ascent)
+    >>> result = ndimage.fourier_ellipsoid(input_, size=20)
+    >>> result = numpy.fft.ifft2(result)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result.real)  # the imaginary part is an artifact
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    if input.ndim > 3:
+        raise NotImplementedError("Only 1d, 2d and 3d inputs are supported")
+    output = _get_output_fourier(output, input)
+    if output.size == 0:
+        # The C code has a bug that can result in a segfault with arrays
+        # that have size 0 (gh-17270), so check here.
+        return output
+    axis = normalize_axis_index(axis, input.ndim)
+    sizes = _ni_support._normalize_sequence(size, input.ndim)
+    sizes = np.asarray(sizes, dtype=np.float64)
+    if not sizes.flags.contiguous:
+        sizes = sizes.copy()
+    _nd_image.fourier_filter(input, sizes, n, axis, output, 2)
+    return output
+
+
+def fourier_shift(input, shift, n=-1, axis=-1, output=None):
+    """
+    Multidimensional Fourier shift filter.
+
+    The array is multiplied with the Fourier transform of a shift operation.
+
+    Parameters
+    ----------
+    input : array_like
+        The input array.
+    shift : float or sequence
+        The size of the box used for filtering.
+        If a float, `shift` is the same for all axes. If a sequence, `shift`
+        has to contain one value for each axis.
+    n : int, optional
+        If `n` is negative (default), then the input is assumed to be the
+        result of a complex fft.
+        If `n` is larger than or equal to zero, the input is assumed to be the
+        result of a real fft, and `n` gives the length of the array before
+        transformation along the real transform direction.
+    axis : int, optional
+        The axis of the real transform.
+    output : ndarray, optional
+        If given, the result of shifting the input is placed in this array.
+
+    Returns
+    -------
+    fourier_shift : ndarray
+        The shifted input.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy.fft
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ascent = datasets.ascent()
+    >>> input_ = numpy.fft.fft2(ascent)
+    >>> result = ndimage.fourier_shift(input_, shift=200)
+    >>> result = numpy.fft.ifft2(result)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result.real)  # the imaginary part is an artifact
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _get_output_fourier_complex(output, input)
+    axis = normalize_axis_index(axis, input.ndim)
+    shifts = _ni_support._normalize_sequence(shift, input.ndim)
+    shifts = np.asarray(shifts, dtype=np.float64)
+    if not shifts.flags.contiguous:
+        shifts = shifts.copy()
+    _nd_image.fourier_shift(input, shifts, n, axis, output)
+    return output
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e4ea94184871fe87f848532b21e2def29bd406b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py
@@ -0,0 +1,1003 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# 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 itertools
+import warnings
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+
+from scipy import special
+from . import _ni_support
+from . import _nd_image
+from ._ni_docstrings import docfiller
+
+
+__all__ = ['spline_filter1d', 'spline_filter', 'geometric_transform',
+           'map_coordinates', 'affine_transform', 'shift', 'zoom', 'rotate']
+
+
+@docfiller
+def spline_filter1d(input, order=3, axis=-1, output=np.float64,
+                    mode='mirror'):
+    """
+    Calculate a 1-D spline filter along the given axis.
+
+    The lines of the array along the given axis are filtered by a
+    spline filter. The order of the spline must be >= 2 and <= 5.
+
+    Parameters
+    ----------
+    %(input)s
+    order : int, optional
+        The order of the spline, default is 3.
+    axis : int, optional
+        The axis along which the spline filter is applied. Default is the last
+        axis.
+    output : ndarray or dtype, optional
+        The array in which to place the output, or the dtype of the returned
+        array. Default is ``numpy.float64``.
+    %(mode_interp_mirror)s
+
+    Returns
+    -------
+    spline_filter1d : ndarray
+        The filtered input.
+
+    See Also
+    --------
+    spline_filter : Multidimensional spline filter.
+
+    Notes
+    -----
+    All of the interpolation functions in `ndimage` do spline interpolation of
+    the input image. If using B-splines of `order > 1`, the input image
+    values have to be converted to B-spline coefficients first, which is
+    done by applying this 1-D filter sequentially along all
+    axes of the input. All functions that require B-spline coefficients
+    will automatically filter their inputs, a behavior controllable with
+    the `prefilter` keyword argument. For functions that accept a `mode`
+    parameter, the result will only be correct if it matches the `mode`
+    used when filtering.
+
+    For complex-valued `input`, this function processes the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    We can filter an image using 1-D spline along the given axis:
+
+    >>> from scipy.ndimage import spline_filter1d
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> orig_img = np.eye(20)  # create an image
+    >>> orig_img[10, :] = 1.0
+    >>> sp_filter_axis_0 = spline_filter1d(orig_img, axis=0)
+    >>> sp_filter_axis_1 = spline_filter1d(orig_img, axis=1)
+    >>> f, ax = plt.subplots(1, 3, sharex=True)
+    >>> for ind, data in enumerate([[orig_img, "original image"],
+    ...             [sp_filter_axis_0, "spline filter (axis=0)"],
+    ...             [sp_filter_axis_1, "spline filter (axis=1)"]]):
+    ...     ax[ind].imshow(data[0], cmap='gray_r')
+    ...     ax[ind].set_title(data[1])
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input,
+                                     complex_output=complex_output)
+    if complex_output:
+        spline_filter1d(input.real, order, axis, output.real, mode)
+        spline_filter1d(input.imag, order, axis, output.imag, mode)
+        return output
+    if order in [0, 1]:
+        output[...] = np.array(input)
+    else:
+        mode = _ni_support._extend_mode_to_code(mode)
+        axis = normalize_axis_index(axis, input.ndim)
+        _nd_image.spline_filter1d(input, order, axis, output, mode)
+    return output
+
+@docfiller
+def spline_filter(input, order=3, output=np.float64, mode='mirror'):
+    """
+    Multidimensional spline filter.
+
+    Parameters
+    ----------
+    %(input)s
+    order : int, optional
+        The order of the spline, default is 3.
+    output : ndarray or dtype, optional
+        The array in which to place the output, or the dtype of the returned
+        array. Default is ``numpy.float64``.
+    %(mode_interp_mirror)s
+
+    Returns
+    -------
+    spline_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    See Also
+    --------
+    spline_filter1d : Calculate a 1-D spline filter along the given axis.
+
+    Notes
+    -----
+    The multidimensional filter is implemented as a sequence of
+    1-D spline filters. The intermediate arrays are stored
+    in the same data type as the output. Therefore, for output types
+    with a limited precision, the results may be imprecise because
+    intermediate results may be stored with insufficient precision.
+
+    For complex-valued `input`, this function processes the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    We can filter an image using multidimensional splines:
+
+    >>> from scipy.ndimage import spline_filter
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> orig_img = np.eye(20)  # create an image
+    >>> orig_img[10, :] = 1.0
+    >>> sp_filter = spline_filter(orig_img, order=3)
+    >>> f, ax = plt.subplots(1, 2, sharex=True)
+    >>> for ind, data in enumerate([[orig_img, "original image"],
+    ...                             [sp_filter, "spline filter"]]):
+    ...     ax[ind].imshow(data[0], cmap='gray_r')
+    ...     ax[ind].set_title(data[1])
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    if order < 2 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input,
+                                     complex_output=complex_output)
+    if complex_output:
+        spline_filter(input.real, order, output.real, mode)
+        spline_filter(input.imag, order, output.imag, mode)
+        return output
+    if order not in [0, 1] and input.ndim > 0:
+        for axis in range(input.ndim):
+            spline_filter1d(input, order, axis, output=output, mode=mode)
+            input = output
+    else:
+        output[...] = input[...]
+    return output
+
+
+def _prepad_for_spline_filter(input, mode, cval):
+    if mode in ['nearest', 'grid-constant']:
+        npad = 12
+        if mode == 'grid-constant':
+            padded = np.pad(input, npad, mode='constant',
+                               constant_values=cval)
+        elif mode == 'nearest':
+            padded = np.pad(input, npad, mode='edge')
+    else:
+        # other modes have exact boundary conditions implemented so
+        # no prepadding is needed
+        npad = 0
+        padded = input
+    return padded, npad
+
+
+@docfiller
+def geometric_transform(input, mapping, output_shape=None,
+                        output=None, order=3,
+                        mode='constant', cval=0.0, prefilter=True,
+                        extra_arguments=(), extra_keywords=None):
+    """
+    Apply an arbitrary geometric transform.
+
+    The given mapping function is used to find, for each point in the
+    output, the corresponding coordinates in the input. The value of the
+    input at those coordinates is determined by spline interpolation of
+    the requested order.
+
+    Parameters
+    ----------
+    %(input)s
+    mapping : {callable, scipy.LowLevelCallable}
+        A callable object that accepts a tuple of length equal to the output
+        array rank, and returns the corresponding input coordinates as a tuple
+        of length equal to the input array rank.
+    output_shape : tuple of ints, optional
+        Shape tuple.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+    extra_arguments : tuple, optional
+        Extra arguments passed to `mapping`.
+    extra_keywords : dict, optional
+        Extra keywords passed to `mapping`.
+
+    Returns
+    -------
+    output : ndarray
+        The filtered input.
+
+    See Also
+    --------
+    map_coordinates, affine_transform, spline_filter1d
+
+
+    Notes
+    -----
+    This function also accepts low-level callback functions with one
+    the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+    .. code:: c
+
+       int mapping(npy_intp *output_coordinates, double *input_coordinates,
+                   int output_rank, int input_rank, void *user_data)
+       int mapping(intptr_t *output_coordinates, double *input_coordinates,
+                   int output_rank, int input_rank, void *user_data)
+
+    The calling function iterates over the elements of the output array,
+    calling the callback function at each element. The coordinates of the
+    current output element are passed through ``output_coordinates``. The
+    callback function must return the coordinates at which the input must
+    be interpolated in ``input_coordinates``. The rank of the input and
+    output arrays are given by ``input_rank`` and ``output_rank``
+    respectively. ``user_data`` is the data pointer provided
+    to `scipy.LowLevelCallable` as-is.
+
+    The callback function must return an integer error status that is zero
+    if something went wrong and one otherwise. If an error occurs, you should
+    normally set the Python error status with an informative message
+    before returning, otherwise a default error message is set by the
+    calling function.
+
+    In addition, some other low-level function pointer specifications
+    are accepted, but these are for backward compatibility only and should
+    not be used in new code.
+
+    For complex-valued `input`, this function transforms the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.ndimage import geometric_transform
+    >>> a = np.arange(12.).reshape((4, 3))
+    >>> def shift_func(output_coords):
+    ...     return (output_coords[0] - 0.5, output_coords[1] - 0.5)
+    ...
+    >>> geometric_transform(a, shift_func)
+    array([[ 0.   ,  0.   ,  0.   ],
+           [ 0.   ,  1.362,  2.738],
+           [ 0.   ,  4.812,  6.187],
+           [ 0.   ,  8.263,  9.637]])
+
+    >>> b = [1, 2, 3, 4, 5]
+    >>> def shift_func(output_coords):
+    ...     return (output_coords[0] - 3,)
+    ...
+    >>> geometric_transform(b, shift_func, mode='constant')
+    array([0, 0, 0, 1, 2])
+    >>> geometric_transform(b, shift_func, mode='nearest')
+    array([1, 1, 1, 1, 2])
+    >>> geometric_transform(b, shift_func, mode='reflect')
+    array([3, 2, 1, 1, 2])
+    >>> geometric_transform(b, shift_func, mode='wrap')
+    array([2, 3, 4, 1, 2])
+
+    """
+    if extra_keywords is None:
+        extra_keywords = {}
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    if output_shape is None:
+        output_shape = input.shape
+    if input.ndim < 1 or len(output_shape) < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, shape=output_shape,
+                                     complex_output=complex_output)
+    if complex_output:
+        kwargs = dict(order=order, mode=mode, prefilter=prefilter,
+                      output_shape=output_shape,
+                      extra_arguments=extra_arguments,
+                      extra_keywords=extra_keywords)
+        geometric_transform(input.real, mapping, output=output.real,
+                            cval=np.real(cval), **kwargs)
+        geometric_transform(input.imag, mapping, output=output.imag,
+                            cval=np.imag(cval), **kwargs)
+        return output
+
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64,
+                                 mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.geometric_transform(filtered, mapping, None, None, None, output,
+                                  order, mode, cval, npad, extra_arguments,
+                                  extra_keywords)
+    return output
+
+
+@docfiller
+def map_coordinates(input, coordinates, output=None, order=3,
+                    mode='constant', cval=0.0, prefilter=True):
+    """
+    Map the input array to new coordinates by interpolation.
+
+    The array of coordinates is used to find, for each point in the output,
+    the corresponding coordinates in the input. The value of the input at
+    those coordinates is determined by spline interpolation of the
+    requested order.
+
+    The shape of the output is derived from that of the coordinate
+    array by dropping the first axis. The values of the array along
+    the first axis are the coordinates in the input array at which the
+    output value is found.
+
+    Parameters
+    ----------
+    %(input)s
+    coordinates : array_like
+        The coordinates at which `input` is evaluated.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+
+    Returns
+    -------
+    map_coordinates : ndarray
+        The result of transforming the input. The shape of the output is
+        derived from that of `coordinates` by dropping the first axis.
+
+    See Also
+    --------
+    spline_filter, geometric_transform, scipy.interpolate
+
+    Notes
+    -----
+    For complex-valued `input`, this function maps the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.arange(12.).reshape((4, 3))
+    >>> a
+    array([[  0.,   1.,   2.],
+           [  3.,   4.,   5.],
+           [  6.,   7.,   8.],
+           [  9.,  10.,  11.]])
+    >>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
+    array([ 2.,  7.])
+
+    Above, the interpolated value of a[0.5, 0.5] gives output[0], while
+    a[2, 1] is output[1].
+
+    >>> inds = np.array([[0.5, 2], [0.5, 4]])
+    >>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
+    array([  2. , -33.3])
+    >>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
+    array([ 2.,  8.])
+    >>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
+    array([ True, False], dtype=bool)
+
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    coordinates = np.asarray(coordinates)
+    if np.iscomplexobj(coordinates):
+        raise TypeError('Complex type not supported')
+    output_shape = coordinates.shape[1:]
+    if input.ndim < 1 or len(output_shape) < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    if coordinates.shape[0] != input.ndim:
+        raise RuntimeError('invalid shape for coordinate array')
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, shape=output_shape,
+                                     complex_output=complex_output)
+    if complex_output:
+        kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+        map_coordinates(input.real, coordinates, output=output.real,
+                        cval=np.real(cval), **kwargs)
+        map_coordinates(input.imag, coordinates, output=output.imag,
+                        cval=np.imag(cval), **kwargs)
+        return output
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.geometric_transform(filtered, None, coordinates, None, None,
+                                  output, order, mode, cval, npad, None, None)
+    return output
+
+
+@docfiller
+def affine_transform(input, matrix, offset=0.0, output_shape=None,
+                     output=None, order=3,
+                     mode='constant', cval=0.0, prefilter=True):
+    """
+    Apply an affine transformation.
+
+    Given an output image pixel index vector ``o``, the pixel value
+    is determined from the input image at position
+    ``np.dot(matrix, o) + offset``.
+
+    This does 'pull' (or 'backward') resampling, transforming the output space
+    to the input to locate data. Affine transformations are often described in
+    the 'push' (or 'forward') direction, transforming input to output. If you
+    have a matrix for the 'push' transformation, use its inverse
+    (:func:`numpy.linalg.inv`) in this function.
+
+    Parameters
+    ----------
+    %(input)s
+    matrix : ndarray
+        The inverse coordinate transformation matrix, mapping output
+        coordinates to input coordinates. If ``ndim`` is the number of
+        dimensions of ``input``, the given matrix must have one of the
+        following shapes:
+
+            - ``(ndim, ndim)``: the linear transformation matrix for each
+              output coordinate.
+            - ``(ndim,)``: assume that the 2-D transformation matrix is
+              diagonal, with the diagonal specified by the given value. A more
+              efficient algorithm is then used that exploits the separability
+              of the problem.
+            - ``(ndim + 1, ndim + 1)``: assume that the transformation is
+              specified using homogeneous coordinates [1]_. In this case, any
+              value passed to ``offset`` is ignored.
+            - ``(ndim, ndim + 1)``: as above, but the bottom row of a
+              homogeneous transformation matrix is always ``[0, 0, ..., 1]``,
+              and may be omitted.
+
+    offset : float or sequence, optional
+        The offset into the array where the transform is applied. If a float,
+        `offset` is the same for each axis. If a sequence, `offset` should
+        contain one value for each axis.
+    output_shape : tuple of ints, optional
+        Shape tuple.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+
+    Returns
+    -------
+    affine_transform : ndarray
+        The transformed input.
+
+    Notes
+    -----
+    The given matrix and offset are used to find for each point in the
+    output the corresponding coordinates in the input by an affine
+    transformation. The value of the input at those coordinates is
+    determined by spline interpolation of the requested order. Points
+    outside the boundaries of the input are filled according to the given
+    mode.
+
+    .. versionchanged:: 0.18.0
+        Previously, the exact interpretation of the affine transformation
+        depended on whether the matrix was supplied as a 1-D or a
+        2-D array. If a 1-D array was supplied
+        to the matrix parameter, the output pixel value at index ``o``
+        was determined from the input image at position
+        ``matrix * (o + offset)``.
+
+    For complex-valued `input`, this function transforms the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Homogeneous_coordinates
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    if output_shape is None:
+        if isinstance(output, np.ndarray):
+            output_shape = output.shape
+        else:
+            output_shape = input.shape
+    if input.ndim < 1 or len(output_shape) < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, shape=output_shape,
+                                     complex_output=complex_output)
+    if complex_output:
+        kwargs = dict(offset=offset, output_shape=output_shape, order=order,
+                      mode=mode, prefilter=prefilter)
+        affine_transform(input.real, matrix, output=output.real,
+                         cval=np.real(cval), **kwargs)
+        affine_transform(input.imag, matrix, output=output.imag,
+                         cval=np.imag(cval), **kwargs)
+        return output
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    mode = _ni_support._extend_mode_to_code(mode)
+    matrix = np.asarray(matrix, dtype=np.float64)
+    if matrix.ndim not in [1, 2] or matrix.shape[0] < 1:
+        raise RuntimeError('no proper affine matrix provided')
+    if (matrix.ndim == 2 and matrix.shape[1] == input.ndim + 1 and
+            (matrix.shape[0] in [input.ndim, input.ndim + 1])):
+        if matrix.shape[0] == input.ndim + 1:
+            exptd = [0] * input.ndim + [1]
+            if not np.all(matrix[input.ndim] == exptd):
+                msg = (f'Expected homogeneous transformation matrix with '
+                       f'shape {matrix.shape} for image shape {input.shape}, '
+                       f'but bottom row was not equal to {exptd}')
+                raise ValueError(msg)
+        # assume input is homogeneous coordinate transformation matrix
+        offset = matrix[:input.ndim, input.ndim]
+        matrix = matrix[:input.ndim, :input.ndim]
+    if matrix.shape[0] != input.ndim:
+        raise RuntimeError('affine matrix has wrong number of rows')
+    if matrix.ndim == 2 and matrix.shape[1] != output.ndim:
+        raise RuntimeError('affine matrix has wrong number of columns')
+    if not matrix.flags.contiguous:
+        matrix = matrix.copy()
+    offset = _ni_support._normalize_sequence(offset, input.ndim)
+    offset = np.asarray(offset, dtype=np.float64)
+    if offset.ndim != 1 or offset.shape[0] < 1:
+        raise RuntimeError('no proper offset provided')
+    if not offset.flags.contiguous:
+        offset = offset.copy()
+    if matrix.ndim == 1:
+        warnings.warn(
+            "The behavior of affine_transform with a 1-D "
+            "array supplied for the matrix parameter has changed in "
+            "SciPy 0.18.0.",
+            stacklevel=2
+        )
+        _nd_image.zoom_shift(filtered, matrix, offset/matrix, output, order,
+                             mode, cval, npad, False)
+    else:
+        _nd_image.geometric_transform(filtered, None, None, matrix, offset,
+                                      output, order, mode, cval, npad, None,
+                                      None)
+    return output
+
+
+@docfiller
+def shift(input, shift, output=None, order=3, mode='constant', cval=0.0,
+          prefilter=True):
+    """
+    Shift an array.
+
+    The array is shifted using spline interpolation of the requested order.
+    Points outside the boundaries of the input are filled according to the
+    given mode.
+
+    Parameters
+    ----------
+    %(input)s
+    shift : float or sequence
+        The shift along the axes. If a float, `shift` is the same for each
+        axis. If a sequence, `shift` should contain one value for each axis.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+
+    Returns
+    -------
+    shift : ndarray
+        The shifted input.
+
+    See Also
+    --------
+    affine_transform : Affine transformations
+
+    Notes
+    -----
+    For complex-valued `input`, this function shifts the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    Import the necessary modules and an exemplary image.
+
+    >>> from scipy.ndimage import shift
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import datasets
+    >>> image = datasets.ascent()
+
+    Shift the image vertically by 20 pixels.
+
+    >>> image_shifted_vertically = shift(image, (20, 0))
+
+    Shift the image vertically by -200 pixels and horizontally by 100 pixels.
+
+    >>> image_shifted_both_directions = shift(image, (-200, 100))
+
+    Plot the original and the shifted images.
+
+    >>> fig, axes = plt.subplots(3, 1, figsize=(4, 12))
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> top, middle, bottom = axes
+    >>> for ax in axes:
+    ...     ax.set_axis_off()  # remove coordinate system
+    >>> top.imshow(image)
+    >>> top.set_title("Original image")
+    >>> middle.imshow(image_shifted_vertically)
+    >>> middle.set_title("Vertically shifted image")
+    >>> bottom.imshow(image_shifted_both_directions)
+    >>> bottom.set_title("Image shifted in both directions")
+    >>> fig.tight_layout()
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    if input.ndim < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, complex_output=complex_output)
+    if complex_output:
+        # import under different name to avoid confusion with shift parameter
+        from scipy.ndimage._interpolation import shift as _shift
+
+        kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+        _shift(input.real, shift, output=output.real, cval=np.real(cval), **kwargs)
+        _shift(input.imag, shift, output=output.imag, cval=np.imag(cval), **kwargs)
+        return output
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    mode = _ni_support._extend_mode_to_code(mode)
+    shift = _ni_support._normalize_sequence(shift, input.ndim)
+    shift = [-ii for ii in shift]
+    shift = np.asarray(shift, dtype=np.float64)
+    if not shift.flags.contiguous:
+        shift = shift.copy()
+    _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval,
+                         npad, False)
+    return output
+
+
+@docfiller
+def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0,
+         prefilter=True, *, grid_mode=False):
+    """
+    Zoom an array.
+
+    The array is zoomed using spline interpolation of the requested order.
+
+    Parameters
+    ----------
+    %(input)s
+    zoom : float or sequence
+        The zoom factor along the axes. If a float, `zoom` is the same for each
+        axis. If a sequence, `zoom` should contain one value for each axis.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+    grid_mode : bool, optional
+        If False, the distance from the pixel centers is zoomed. Otherwise, the
+        distance including the full pixel extent is used. For example, a 1d
+        signal of length 5 is considered to have length 4 when `grid_mode` is
+        False, but length 5 when `grid_mode` is True. See the following
+        visual illustration:
+
+        .. code-block:: text
+
+                | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |
+                     |<-------------------------------------->|
+                                        vs.
+                |<----------------------------------------------->|
+
+        The starting point of the arrow in the diagram above corresponds to
+        coordinate location 0 in each mode.
+
+    Returns
+    -------
+    zoom : ndarray
+        The zoomed input.
+
+    Notes
+    -----
+    For complex-valued `input`, this function zooms the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.zoom(ascent, 3.0)
+    >>> ax1.imshow(ascent, vmin=0, vmax=255)
+    >>> ax2.imshow(result, vmin=0, vmax=255)
+    >>> plt.show()
+
+    >>> print(ascent.shape)
+    (512, 512)
+
+    >>> print(result.shape)
+    (1536, 1536)
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    if input.ndim < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    zoom = _ni_support._normalize_sequence(zoom, input.ndim)
+    output_shape = tuple(
+            [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)])
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, shape=output_shape,
+                                     complex_output=complex_output)
+    if complex_output:
+        # import under different name to avoid confusion with zoom parameter
+        from scipy.ndimage._interpolation import zoom as _zoom
+
+        kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+        _zoom(input.real, zoom, output=output.real, cval=np.real(cval), **kwargs)
+        _zoom(input.imag, zoom, output=output.imag, cval=np.imag(cval), **kwargs)
+        return output
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    if grid_mode:
+        # warn about modes that may have surprising behavior
+        suggest_mode = None
+        if mode == 'constant':
+            suggest_mode = 'grid-constant'
+        elif mode == 'wrap':
+            suggest_mode = 'grid-wrap'
+        if suggest_mode is not None:
+            warnings.warn(
+                (f"It is recommended to use mode = {suggest_mode} instead of {mode} "
+                 f"when grid_mode is True."),
+                stacklevel=2
+            )
+    mode = _ni_support._extend_mode_to_code(mode)
+
+    zoom_div = np.array(output_shape)
+    zoom_nominator = np.array(input.shape)
+    if not grid_mode:
+        zoom_div -= 1
+        zoom_nominator -= 1
+
+    # Zooming to infinite values is unpredictable, so just choose
+    # zoom factor 1 instead
+    zoom = np.divide(zoom_nominator, zoom_div,
+                     out=np.ones_like(input.shape, dtype=np.float64),
+                     where=zoom_div != 0)
+    zoom = np.ascontiguousarray(zoom)
+    _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad,
+                         grid_mode)
+    return output
+
+
+@docfiller
+def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3,
+           mode='constant', cval=0.0, prefilter=True):
+    """
+    Rotate an array.
+
+    The array is rotated in the plane defined by the two axes given by the
+    `axes` parameter using spline interpolation of the requested order.
+
+    Parameters
+    ----------
+    %(input)s
+    angle : float
+        The rotation angle in degrees.
+    axes : tuple of 2 ints, optional
+        The two axes that define the plane of rotation. Default is the first
+        two axes.
+    reshape : bool, optional
+        If `reshape` is true, the output shape is adapted so that the input
+        array is contained completely in the output. Default is True.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+
+    Returns
+    -------
+    rotate : ndarray
+        The rotated input.
+
+    Notes
+    -----
+    For complex-valued `input`, this function rotates the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure(figsize=(10, 3))
+    >>> ax1, ax2, ax3 = fig.subplots(1, 3)
+    >>> img = datasets.ascent()
+    >>> img_45 = ndimage.rotate(img, 45, reshape=False)
+    >>> full_img_45 = ndimage.rotate(img, 45, reshape=True)
+    >>> ax1.imshow(img, cmap='gray')
+    >>> ax1.set_axis_off()
+    >>> ax2.imshow(img_45, cmap='gray')
+    >>> ax2.set_axis_off()
+    >>> ax3.imshow(full_img_45, cmap='gray')
+    >>> ax3.set_axis_off()
+    >>> fig.set_layout_engine('tight')
+    >>> plt.show()
+    >>> print(img.shape)
+    (512, 512)
+    >>> print(img_45.shape)
+    (512, 512)
+    >>> print(full_img_45.shape)
+    (724, 724)
+
+    """
+    input_arr = np.asarray(input)
+    ndim = input_arr.ndim
+
+    if ndim < 2:
+        raise ValueError('input array should be at least 2D')
+
+    axes = list(axes)
+
+    if len(axes) != 2:
+        raise ValueError('axes should contain exactly two values')
+
+    if not all([float(ax).is_integer() for ax in axes]):
+        raise ValueError('axes should contain only integer values')
+
+    if axes[0] < 0:
+        axes[0] += ndim
+    if axes[1] < 0:
+        axes[1] += ndim
+    if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim:
+        raise ValueError('invalid rotation plane specified')
+
+    axes.sort()
+
+    c, s = special.cosdg(angle), special.sindg(angle)
+
+    rot_matrix = np.array([[c, s],
+                           [-s, c]])
+
+    img_shape = np.asarray(input_arr.shape)
+    in_plane_shape = img_shape[axes]
+    if reshape:
+        # Compute transformed input bounds
+        iy, ix = in_plane_shape
+        out_bounds = rot_matrix @ [[0, 0, iy, iy],
+                                   [0, ix, 0, ix]]
+        # Compute the shape of the transformed input plane
+        out_plane_shape = (np.ptp(out_bounds, axis=1) + 0.5).astype(int)
+    else:
+        out_plane_shape = img_shape[axes]
+
+    out_center = rot_matrix @ ((out_plane_shape - 1) / 2)
+    in_center = (in_plane_shape - 1) / 2
+    offset = in_center - out_center
+
+    output_shape = img_shape
+    output_shape[axes] = out_plane_shape
+    output_shape = tuple(output_shape)
+
+    complex_output = np.iscomplexobj(input_arr)
+    output = _ni_support._get_output(output, input_arr, shape=output_shape,
+                                     complex_output=complex_output)
+
+    if ndim <= 2:
+        affine_transform(input_arr, rot_matrix, offset, output_shape, output,
+                         order, mode, cval, prefilter)
+    else:
+        # If ndim > 2, the rotation is applied over all the planes
+        # parallel to axes
+        planes_coord = itertools.product(
+            *[[slice(None)] if ax in axes else range(img_shape[ax])
+              for ax in range(ndim)])
+
+        out_plane_shape = tuple(out_plane_shape)
+
+        for coordinates in planes_coord:
+            ia = input_arr[coordinates]
+            oa = output[coordinates]
+            affine_transform(ia, rot_matrix, offset, out_plane_shape,
+                             oa, order, mode, cval, prefilter)
+
+    return output
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_measurements.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..67ec12870ccf1dfe52624da05787b197542a0253
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_measurements.py
@@ -0,0 +1,1687 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# 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 . import _ni_support
+from . import _ni_label
+from . import _nd_image
+from . import _morphology
+
+__all__ = ['label', 'find_objects', 'labeled_comprehension', 'sum', 'mean',
+           'variance', 'standard_deviation', 'minimum', 'maximum', 'median',
+           'minimum_position', 'maximum_position', 'extrema', 'center_of_mass',
+           'histogram', 'watershed_ift', 'sum_labels', 'value_indices']
+
+
+def label(input, structure=None, output=None):
+    """
+    Label features in an array.
+
+    Parameters
+    ----------
+    input : array_like
+        An array-like object to be labeled. Any non-zero values in `input` are
+        counted as features and zero values are considered the background.
+    structure : array_like, optional
+        A structuring element that defines feature connections.
+        `structure` must be centrosymmetric
+        (see Notes).
+        If no structuring element is provided,
+        one is automatically generated with a squared connectivity equal to
+        one.  That is, for a 2-D `input` array, the default structuring element
+        is::
+
+            [[0,1,0],
+             [1,1,1],
+             [0,1,0]]
+
+    output : (None, data-type, array_like), optional
+        If `output` is a data type, it specifies the type of the resulting
+        labeled feature array.
+        If `output` is an array-like object, then `output` will be updated
+        with the labeled features from this function.  This function can
+        operate in-place, by passing output=input.
+        Note that the output must be able to store the largest label, or this
+        function will raise an Exception.
+
+    Returns
+    -------
+    label : ndarray or int
+        An integer ndarray where each unique feature in `input` has a unique
+        label in the returned array.
+    num_features : int
+        How many objects were found.
+
+        If `output` is None, this function returns a tuple of
+        (`labeled_array`, `num_features`).
+
+        If `output` is a ndarray, then it will be updated with values in
+        `labeled_array` and only `num_features` will be returned by this
+        function.
+
+    See Also
+    --------
+    find_objects : generate a list of slices for the labeled features (or
+                   objects); useful for finding features' position or
+                   dimensions
+
+    Notes
+    -----
+    A centrosymmetric matrix is a matrix that is symmetric about the center.
+    See [1]_ for more information.
+
+    The `structure` matrix must be centrosymmetric to ensure
+    two-way connections.
+    For instance, if the `structure` matrix is not centrosymmetric
+    and is defined as::
+
+        [[0,1,0],
+         [1,1,0],
+         [0,0,0]]
+
+    and the `input` is::
+
+        [[1,2],
+         [0,3]]
+
+    then the structure matrix would indicate the
+    entry 2 in the input is connected to 1,
+    but 1 is not connected to 2.
+
+    References
+    ----------
+    .. [1] James R. Weaver, "Centrosymmetric (cross-symmetric)
+       matrices, their basic properties, eigenvalues, and
+       eigenvectors." The American Mathematical Monthly 92.10
+       (1985): 711-717.
+
+    Examples
+    --------
+    Create an image with some features, then label it using the default
+    (cross-shaped) structuring element:
+
+    >>> from scipy.ndimage import label, generate_binary_structure
+    >>> import numpy as np
+    >>> a = np.array([[0,0,1,1,0,0],
+    ...               [0,0,0,1,0,0],
+    ...               [1,1,0,0,1,0],
+    ...               [0,0,0,1,0,0]])
+    >>> labeled_array, num_features = label(a)
+
+    Each of the 4 features are labeled with a different integer:
+
+    >>> num_features
+    4
+    >>> labeled_array
+    array([[0, 0, 1, 1, 0, 0],
+           [0, 0, 0, 1, 0, 0],
+           [2, 2, 0, 0, 3, 0],
+           [0, 0, 0, 4, 0, 0]], dtype=int32)
+
+    Generate a structuring element that will consider features connected even
+    if they touch diagonally:
+
+    >>> s = generate_binary_structure(2,2)
+
+    or,
+
+    >>> s = [[1,1,1],
+    ...      [1,1,1],
+    ...      [1,1,1]]
+
+    Label the image using the new structuring element:
+
+    >>> labeled_array, num_features = label(a, structure=s)
+
+    Show the 2 labeled features (note that features 1, 3, and 4 from above are
+    now considered a single feature):
+
+    >>> num_features
+    2
+    >>> labeled_array
+    array([[0, 0, 1, 1, 0, 0],
+           [0, 0, 0, 1, 0, 0],
+           [2, 2, 0, 0, 1, 0],
+           [0, 0, 0, 1, 0, 0]], dtype=int32)
+
+    """
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    if structure is None:
+        structure = _morphology.generate_binary_structure(input.ndim, 1)
+    structure = np.asarray(structure, dtype=bool)
+    if structure.ndim != input.ndim:
+        raise RuntimeError('structure and input must have equal rank')
+    for ii in structure.shape:
+        if ii != 3:
+            raise ValueError('structure dimensions must be equal to 3')
+
+    # Use 32 bits if it's large enough for this image.
+    # _ni_label.label() needs two entries for background and
+    # foreground tracking
+    need_64bits = input.size >= (2**31 - 2)
+
+    if isinstance(output, np.ndarray):
+        if output.shape != input.shape:
+            raise ValueError("output shape not correct")
+        caller_provided_output = True
+    else:
+        caller_provided_output = False
+        if output is None:
+            output = np.empty(input.shape, np.intp if need_64bits else np.int32)
+        else:
+            output = np.empty(input.shape, output)
+
+    # handle scalars, 0-D arrays
+    if input.ndim == 0 or input.size == 0:
+        if input.ndim == 0:
+            # scalar
+            maxlabel = 1 if (input != 0) else 0
+            output[...] = maxlabel
+        else:
+            # 0-D
+            maxlabel = 0
+        if caller_provided_output:
+            return maxlabel
+        else:
+            return output, maxlabel
+
+    try:
+        max_label = _ni_label._label(input, structure, output)
+    except _ni_label.NeedMoreBits as e:
+        # Make another attempt with enough bits, then try to cast to the
+        # new type.
+        tmp_output = np.empty(input.shape, np.intp if need_64bits else np.int32)
+        max_label = _ni_label._label(input, structure, tmp_output)
+        output[...] = tmp_output[...]
+        if not np.all(output == tmp_output):
+            # refuse to return bad results
+            raise RuntimeError(
+                "insufficient bit-depth in requested output type"
+            ) from e
+
+    if caller_provided_output:
+        # result was written in-place
+        return max_label
+    else:
+        return output, max_label
+
+
+def find_objects(input, max_label=0):
+    """
+    Find objects in a labeled array.
+
+    Parameters
+    ----------
+    input : ndarray of ints
+        Array containing objects defined by different labels. Labels with
+        value 0 are ignored.
+    max_label : int, optional
+        Maximum label to be searched for in `input`. If max_label is not
+        given, the positions of all objects are returned.
+
+    Returns
+    -------
+    object_slices : list of tuples
+        A list of tuples, with each tuple containing N slices (with N the
+        dimension of the input array). Slices correspond to the minimal
+        parallelepiped that contains the object. If a number is missing,
+        None is returned instead of a slice. The label ``l`` corresponds to
+        the index ``l-1`` in the returned list.
+
+    See Also
+    --------
+    label, center_of_mass
+
+    Notes
+    -----
+    This function is very useful for isolating a volume of interest inside
+    a 3-D array, that cannot be "seen through".
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((6,6), dtype=int)
+    >>> a[2:4, 2:4] = 1
+    >>> a[4, 4] = 1
+    >>> a[:2, :3] = 2
+    >>> a[0, 5] = 3
+    >>> a
+    array([[2, 2, 2, 0, 0, 3],
+           [2, 2, 2, 0, 0, 0],
+           [0, 0, 1, 1, 0, 0],
+           [0, 0, 1, 1, 0, 0],
+           [0, 0, 0, 0, 1, 0],
+           [0, 0, 0, 0, 0, 0]])
+    >>> ndimage.find_objects(a)
+    [(slice(2, 5, None), slice(2, 5, None)),
+     (slice(0, 2, None), slice(0, 3, None)),
+     (slice(0, 1, None), slice(5, 6, None))]
+    >>> ndimage.find_objects(a, max_label=2)
+    [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))]
+    >>> ndimage.find_objects(a == 1, max_label=2)
+    [(slice(2, 5, None), slice(2, 5, None)), None]
+
+    >>> loc = ndimage.find_objects(a)[0]
+    >>> a[loc]
+    array([[1, 1, 0],
+           [1, 1, 0],
+           [0, 0, 1]])
+
+    """
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+
+    if max_label < 1:
+        max_label = input.max()
+
+    return _nd_image.find_objects(input, max_label)
+
+
+def value_indices(arr, *, ignore_value=None):
+    """
+    Find indices of each distinct value in given array.
+
+    Parameters
+    ----------
+    arr : ndarray of ints
+        Array containing integer values.
+    ignore_value : int, optional
+        This value will be ignored in searching the `arr` array. If not
+        given, all values found will be included in output. Default
+        is None.
+
+    Returns
+    -------
+    indices : dictionary
+        A Python dictionary of array indices for each distinct value. The
+        dictionary is keyed by the distinct values, the entries are array
+        index tuples covering all occurrences of the value within the
+        array.
+
+        This dictionary can occupy significant memory, usually several times
+        the size of the input array.
+
+    See Also
+    --------
+    label, maximum, median, minimum_position, extrema, sum, mean, variance,
+    standard_deviation, numpy.where, numpy.unique
+
+    Notes
+    -----
+    For a small array with few distinct values, one might use
+    `numpy.unique()` to find all possible values, and ``(arr == val)`` to
+    locate each value within that array. However, for large arrays,
+    with many distinct values, this can become extremely inefficient,
+    as locating each value would require a new search through the entire
+    array. Using this function, there is essentially one search, with
+    the indices saved for all distinct values.
+
+    This is useful when matching a categorical image (e.g. a segmentation
+    or classification) to an associated image of other data, allowing
+    any per-class statistic(s) to then be calculated. Provides a
+    more flexible alternative to functions like ``scipy.ndimage.mean()``
+    and ``scipy.ndimage.variance()``.
+
+    Some other closely related functionality, with different strengths and
+    weaknesses, can also be found in ``scipy.stats.binned_statistic()`` and
+    the `scikit-image `_ function
+    ``skimage.measure.regionprops()``.
+
+    Note for IDL users: this provides functionality equivalent to IDL's
+    REVERSE_INDICES option (as per the IDL documentation for the
+    `HISTOGRAM `_
+    function).
+
+    .. versionadded:: 1.10.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import ndimage
+    >>> a = np.zeros((6, 6), dtype=int)
+    >>> a[2:4, 2:4] = 1
+    >>> a[4, 4] = 1
+    >>> a[:2, :3] = 2
+    >>> a[0, 5] = 3
+    >>> a
+    array([[2, 2, 2, 0, 0, 3],
+           [2, 2, 2, 0, 0, 0],
+           [0, 0, 1, 1, 0, 0],
+           [0, 0, 1, 1, 0, 0],
+           [0, 0, 0, 0, 1, 0],
+           [0, 0, 0, 0, 0, 0]])
+    >>> val_indices = ndimage.value_indices(a)
+
+    The dictionary `val_indices` will have an entry for each distinct
+    value in the input array.
+
+    >>> val_indices.keys()
+    dict_keys([np.int64(0), np.int64(1), np.int64(2), np.int64(3)])
+
+    The entry for each value is an index tuple, locating the elements
+    with that value.
+
+    >>> ndx1 = val_indices[1]
+    >>> ndx1
+    (array([2, 2, 3, 3, 4]), array([2, 3, 2, 3, 4]))
+
+    This can be used to index into the original array, or any other
+    array with the same shape.
+
+    >>> a[ndx1]
+    array([1, 1, 1, 1, 1])
+
+    If the zeros were to be ignored, then the resulting dictionary
+    would no longer have an entry for zero.
+
+    >>> val_indices = ndimage.value_indices(a, ignore_value=0)
+    >>> val_indices.keys()
+    dict_keys([np.int64(1), np.int64(2), np.int64(3)])
+
+    """
+    # Cope with ignore_value being None, without too much extra complexity
+    # in the C code. If not None, the value is passed in as a numpy array
+    # with the same dtype as arr.
+    arr = np.asarray(arr)
+    ignore_value_arr = np.zeros((1,), dtype=arr.dtype)
+    ignoreIsNone = (ignore_value is None)
+    if not ignoreIsNone:
+        ignore_value_arr[0] = ignore_value_arr.dtype.type(ignore_value)
+
+    val_indices = _nd_image.value_indices(arr, ignoreIsNone, ignore_value_arr)
+    return val_indices
+
+
+def labeled_comprehension(input, labels, index, func, out_dtype, default,
+                          pass_positions=False):
+    """
+    Roughly equivalent to [func(input[labels == i]) for i in index].
+
+    Sequentially applies an arbitrary function (that works on array_like input)
+    to subsets of an N-D image array specified by `labels` and `index`.
+    The option exists to provide the function with positional parameters as the
+    second argument.
+
+    Parameters
+    ----------
+    input : array_like
+        Data from which to select `labels` to process.
+    labels : array_like or None
+        Labels to objects in `input`.
+        If not None, array must be same shape as `input`.
+        If None, `func` is applied to raveled `input`.
+    index : int, sequence of ints or None
+        Subset of `labels` to which to apply `func`.
+        If a scalar, a single value is returned.
+        If None, `func` is applied to all non-zero values of `labels`.
+    func : callable
+        Python function to apply to `labels` from `input`.
+    out_dtype : dtype
+        Dtype to use for `result`.
+    default : int, float or None
+        Default return value when a element of `index` does not exist
+        in `labels`.
+    pass_positions : bool, optional
+        If True, pass linear indices to `func` as a second argument.
+        Default is False.
+
+    Returns
+    -------
+    result : ndarray
+        Result of applying `func` to each of `labels` to `input` in `index`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> from scipy import ndimage
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> lbls = np.arange(1, nlbl+1)
+    >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0)
+    array([ 2.75,  5.5 ,  6.  ])
+
+    Falling back to `default`:
+
+    >>> lbls = np.arange(1, nlbl+2)
+    >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1)
+    array([ 2.75,  5.5 ,  6.  , -1.  ])
+
+    Passing positions:
+
+    >>> def fn(val, pos):
+    ...     print("fn says: %s : %s" % (val, pos))
+    ...     return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum())
+    ...
+    >>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True)
+    fn says: [1 2 5 3] : [0 1 4 5]
+    fn says: [4 7] : [ 7 11]
+    fn says: [9 3] : [12 13]
+    array([ 11.,  11., -12.,   0.])
+
+    """
+
+    as_scalar = np.isscalar(index)
+    input = np.asarray(input)
+
+    if pass_positions:
+        positions = np.arange(input.size).reshape(input.shape)
+
+    if labels is None:
+        if index is not None:
+            raise ValueError("index without defined labels")
+        if not pass_positions:
+            return func(input.ravel())
+        else:
+            return func(input.ravel(), positions.ravel())
+
+    labels = np.asarray(labels)
+
+    try:
+        input, labels = np.broadcast_arrays(input, labels)
+    except ValueError as e:
+        raise ValueError("input and labels must have the same shape "
+                            "(excepting dimensions with width 1)") from e
+
+    if index is None:
+        if not pass_positions:
+            return func(input[labels > 0])
+        else:
+            return func(input[labels > 0], positions[labels > 0])
+
+    index = np.atleast_1d(index)
+    if np.any(index.astype(labels.dtype).astype(index.dtype) != index):
+        raise ValueError(f"Cannot convert index values from <{index.dtype}> to "
+                         f"<{labels.dtype}> (labels' type) without loss of precision")
+
+    index = index.astype(labels.dtype)
+
+    # optimization: find min/max in index,
+    # and select those parts of labels, input, and positions
+    lo = index.min()
+    hi = index.max()
+    mask = (labels >= lo) & (labels <= hi)
+
+    # this also ravels the arrays
+    labels = labels[mask]
+    input = input[mask]
+    if pass_positions:
+        positions = positions[mask]
+
+    # sort everything by labels
+    label_order = labels.argsort()
+    labels = labels[label_order]
+    input = input[label_order]
+    if pass_positions:
+        positions = positions[label_order]
+
+    index_order = index.argsort()
+    sorted_index = index[index_order]
+
+    def do_map(inputs, output):
+        """labels must be sorted"""
+        nidx = sorted_index.size
+
+        # Find boundaries for each stretch of constant labels
+        # This could be faster, but we already paid N log N to sort labels.
+        lo = np.searchsorted(labels, sorted_index, side='left')
+        hi = np.searchsorted(labels, sorted_index, side='right')
+
+        for i, l, h in zip(range(nidx), lo, hi):
+            if l == h:
+                continue
+            output[i] = func(*[inp[l:h] for inp in inputs])
+
+    temp = np.empty(index.shape, out_dtype)
+    temp[:] = default
+    if not pass_positions:
+        do_map([input], temp)
+    else:
+        do_map([input, positions], temp)
+
+    output = np.zeros(index.shape, out_dtype)
+    output[index_order] = temp
+    if as_scalar:
+        output = output[0]
+
+    return output
+
+
+def _safely_castable_to_int(dt):
+    """Test whether the NumPy data type `dt` can be safely cast to an int."""
+    int_size = np.dtype(int).itemsize
+    safe = ((np.issubdtype(dt, np.signedinteger) and dt.itemsize <= int_size) or
+            (np.issubdtype(dt, np.unsignedinteger) and dt.itemsize < int_size))
+    return safe
+
+
+def _stats(input, labels=None, index=None, centered=False):
+    """Count, sum, and optionally compute (sum - centre)^2 of input by label
+
+    Parameters
+    ----------
+    input : array_like, N-D
+        The input data to be analyzed.
+    labels : array_like (N-D), optional
+        The labels of the data in `input`. This array must be broadcast
+        compatible with `input`; typically, it is the same shape as `input`.
+        If `labels` is None, all nonzero values in `input` are treated as
+        the single labeled group.
+    index : label or sequence of labels, optional
+        These are the labels of the groups for which the stats are computed.
+        If `index` is None, the stats are computed for the single group where
+        `labels` is greater than 0.
+    centered : bool, optional
+        If True, the centered sum of squares for each labeled group is
+        also returned. Default is False.
+
+    Returns
+    -------
+    counts : int or ndarray of ints
+        The number of elements in each labeled group.
+    sums : scalar or ndarray of scalars
+        The sums of the values in each labeled group.
+    sums_c : scalar or ndarray of scalars, optional
+        The sums of mean-centered squares of the values in each labeled group.
+        This is only returned if `centered` is True.
+
+    """
+    def single_group(vals):
+        if centered:
+            vals_c = vals - vals.mean()
+            return vals.size, vals.sum(), (vals_c * vals_c.conjugate()).sum()
+        else:
+            return vals.size, vals.sum()
+
+    input = np.asarray(input)
+    if labels is None:
+        return single_group(input)
+
+    # ensure input and labels match sizes
+    input, labels = np.broadcast_arrays(input, labels)
+
+    if index is None:
+        return single_group(input[labels > 0])
+
+    if np.isscalar(index):
+        return single_group(input[labels == index])
+
+    def _sum_centered(labels):
+        # `labels` is expected to be an ndarray with the same shape as `input`.
+        # It must contain the label indices (which are not necessarily the labels
+        # themselves).
+        means = sums / counts
+        centered_input = input - means[labels]
+        # bincount expects 1-D inputs, so we ravel the arguments.
+        bc = np.bincount(labels.ravel(),
+                              weights=(centered_input *
+                                       centered_input.conjugate()).ravel())
+        return bc
+
+    # Remap labels to unique integers if necessary, or if the largest
+    # label is larger than the number of values.
+
+    if (not _safely_castable_to_int(labels.dtype) or
+            labels.min() < 0 or labels.max() > labels.size):
+        # Use np.unique to generate the label indices.  `new_labels` will
+        # be 1-D, but it should be interpreted as the flattened N-D array of
+        # label indices.
+        unique_labels, new_labels = np.unique(labels, return_inverse=True)
+        new_labels = np.reshape(new_labels, (-1,))  # flatten, since it may be >1-D
+        counts = np.bincount(new_labels)
+        sums = np.bincount(new_labels, weights=input.ravel())
+        if centered:
+            # Compute the sum of the mean-centered squares.
+            # We must reshape new_labels to the N-D shape of `input` before
+            # passing it _sum_centered.
+            sums_c = _sum_centered(new_labels.reshape(labels.shape))
+        idxs = np.searchsorted(unique_labels, index)
+        # make all of idxs valid
+        idxs[idxs >= unique_labels.size] = 0
+        found = (unique_labels[idxs] == index)
+    else:
+        # labels are an integer type allowed by bincount, and there aren't too
+        # many, so call bincount directly.
+        counts = np.bincount(labels.ravel())
+        sums = np.bincount(labels.ravel(), weights=input.ravel())
+        if centered:
+            sums_c = _sum_centered(labels)
+        # make sure all index values are valid
+        idxs = np.asanyarray(index, np.int_).copy()
+        found = (idxs >= 0) & (idxs < counts.size)
+        idxs[~found] = 0
+
+    counts = counts[idxs]
+    counts[~found] = 0
+    sums = sums[idxs]
+    sums[~found] = 0
+
+    if not centered:
+        return (counts, sums)
+    else:
+        sums_c = sums_c[idxs]
+        sums_c[~found] = 0
+        return (counts, sums, sums_c)
+
+
+def sum(input, labels=None, index=None):
+    """
+    Calculate the sum of the values of the array.
+
+    Notes
+    -----
+    This is an alias for `ndimage.sum_labels` kept for backwards compatibility
+    reasons, for new code please prefer `sum_labels`.  See the `sum_labels`
+    docstring for more details.
+
+    """
+    return sum_labels(input, labels, index)
+
+
+def sum_labels(input, labels=None, index=None):
+    """
+    Calculate the sum of the values of the array.
+
+    Parameters
+    ----------
+    input : array_like
+        Values of `input` inside the regions defined by `labels`
+        are summed together.
+    labels : array_like of ints, optional
+        Assign labels to the values of the array. Has to have the same shape as
+        `input`.
+    index : array_like, optional
+        A single label number or a sequence of label numbers of
+        the objects to be measured.
+
+    Returns
+    -------
+    sum : ndarray or scalar
+        An array of the sums of values of `input` inside the regions defined
+        by `labels` with the same shape as `index`. If 'index' is None or scalar,
+        a scalar is returned.
+
+    See Also
+    --------
+    mean, median
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> input =  [0,1,2,3]
+    >>> labels = [1,1,2,2]
+    >>> ndimage.sum_labels(input, labels, index=[1,2])
+    [1.0, 5.0]
+    >>> ndimage.sum_labels(input, labels, index=1)
+    1
+    >>> ndimage.sum_labels(input, labels)
+    6
+
+
+    """
+    count, sum = _stats(input, labels, index)
+    return sum
+
+
+def mean(input, labels=None, index=None):
+    """
+    Calculate the mean of the values of an array at labels.
+
+    Parameters
+    ----------
+    input : array_like
+        Array on which to compute the mean of elements over distinct
+        regions.
+    labels : array_like, optional
+        Array of labels of same shape, or broadcastable to the same shape as
+        `input`. All elements sharing the same label form one region over
+        which the mean of the elements is computed.
+    index : int or sequence of ints, optional
+        Labels of the objects over which the mean is to be computed.
+        Default is None, in which case the mean for all values where label is
+        greater than 0 is calculated.
+
+    Returns
+    -------
+    out : list
+        Sequence of same length as `index`, with the mean of the different
+        regions labeled by the labels in `index`.
+
+    See Also
+    --------
+    variance, standard_deviation, minimum, maximum, sum, label
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.arange(25).reshape((5,5))
+    >>> labels = np.zeros_like(a)
+    >>> labels[3:5,3:5] = 1
+    >>> index = np.unique(labels)
+    >>> labels
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 1],
+           [0, 0, 0, 1, 1]])
+    >>> index
+    array([0, 1])
+    >>> ndimage.mean(a, labels=labels, index=index)
+    [10.285714285714286, 21.0]
+
+    """
+
+    count, sum = _stats(input, labels, index)
+    return sum / np.asanyarray(count).astype(np.float64)
+
+
+def variance(input, labels=None, index=None):
+    """
+    Calculate the variance of the values of an N-D image array, optionally at
+    specified sub-regions.
+
+    Parameters
+    ----------
+    input : array_like
+        Nd-image data to process.
+    labels : array_like, optional
+        Labels defining sub-regions in `input`.
+        If not None, must be same shape as `input`.
+    index : int or sequence of ints, optional
+        `labels` to include in output.  If None (default), all values where
+        `labels` is non-zero are used.
+
+    Returns
+    -------
+    variance : float or ndarray
+        Values of variance, for each sub-region if `labels` and `index` are
+        specified.
+
+    See Also
+    --------
+    label, standard_deviation, maximum, minimum, extrema
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> from scipy import ndimage
+    >>> ndimage.variance(a)
+    7.609375
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> ndimage.variance(a, lbl, index=np.arange(1, nlbl+1))
+    array([ 2.1875,  2.25  ,  9.    ])
+
+    If no index is given, all non-zero `labels` are processed:
+
+    >>> ndimage.variance(a, lbl)
+    6.1875
+
+    """
+    count, sum, sum_c_sq = _stats(input, labels, index, centered=True)
+    return sum_c_sq / np.asanyarray(count).astype(float)
+
+
+def standard_deviation(input, labels=None, index=None):
+    """
+    Calculate the standard deviation of the values of an N-D image array,
+    optionally at specified sub-regions.
+
+    Parameters
+    ----------
+    input : array_like
+        N-D image data to process.
+    labels : array_like, optional
+        Labels to identify sub-regions in `input`.
+        If not None, must be same shape as `input`.
+    index : int or sequence of ints, optional
+        `labels` to include in output. If None (default), all values where
+        `labels` is non-zero are used.
+
+    Returns
+    -------
+    standard_deviation : float or ndarray
+        Values of standard deviation, for each sub-region if `labels` and
+        `index` are specified.
+
+    See Also
+    --------
+    label, variance, maximum, minimum, extrema
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> from scipy import ndimage
+    >>> ndimage.standard_deviation(a)
+    2.7585095613392387
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> ndimage.standard_deviation(a, lbl, index=np.arange(1, nlbl+1))
+    array([ 1.479,  1.5  ,  3.   ])
+
+    If no index is given, non-zero `labels` are processed:
+
+    >>> ndimage.standard_deviation(a, lbl)
+    2.4874685927665499
+
+    """
+    return np.sqrt(variance(input, labels, index))
+
+
+def _select(input, labels=None, index=None, find_min=False, find_max=False,
+            find_min_positions=False, find_max_positions=False,
+            find_median=False):
+    """Returns min, max, or both, plus their positions (if requested), and
+    median."""
+
+    input = np.asanyarray(input)
+
+    find_positions = find_min_positions or find_max_positions
+    positions = None
+    if find_positions:
+        positions = np.arange(input.size).reshape(input.shape)
+
+    def single_group(vals, positions):
+        result = []
+        if find_min:
+            result += [vals.min()]
+        if find_min_positions:
+            result += [positions[vals == vals.min()][0]]
+        if find_max:
+            result += [vals.max()]
+        if find_max_positions:
+            result += [positions[vals == vals.max()][0]]
+        if find_median:
+            result += [np.median(vals)]
+        return result
+
+    if labels is None:
+        return single_group(input, positions)
+
+    # ensure input and labels match sizes
+    input, labels = np.broadcast_arrays(input, labels)
+
+    if index is None:
+        mask = (labels > 0)
+        masked_positions = None
+        if find_positions:
+            masked_positions = positions[mask]
+        return single_group(input[mask], masked_positions)
+
+    if np.isscalar(index):
+        mask = (labels == index)
+        masked_positions = None
+        if find_positions:
+            masked_positions = positions[mask]
+        return single_group(input[mask], masked_positions)
+
+    index = np.asarray(index)
+
+    # remap labels to unique integers if necessary, or if the largest
+    # label is larger than the number of values.
+    if (not _safely_castable_to_int(labels.dtype) or
+            labels.min() < 0 or labels.max() > labels.size):
+        # remap labels, and indexes
+        unique_labels, labels = np.unique(labels, return_inverse=True)
+        idxs = np.searchsorted(unique_labels, index)
+
+        # make all of idxs valid
+        idxs[idxs >= unique_labels.size] = 0
+        found = (unique_labels[idxs] == index)
+    else:
+        # labels are an integer type, and there aren't too many
+        idxs = np.asanyarray(index, np.int_).copy()
+        found = (idxs >= 0) & (idxs <= labels.max())
+
+    idxs[~ found] = labels.max() + 1
+
+    if find_median:
+        order = np.lexsort((input.ravel(), labels.ravel()))
+    else:
+        order = input.ravel().argsort()
+    input = input.ravel()[order]
+    labels = labels.ravel()[order]
+    if find_positions:
+        positions = positions.ravel()[order]
+
+    result = []
+    if find_min:
+        mins = np.zeros(labels.max() + 2, input.dtype)
+        mins[labels[::-1]] = input[::-1]
+        result += [mins[idxs]]
+    if find_min_positions:
+        minpos = np.zeros(labels.max() + 2, int)
+        minpos[labels[::-1]] = positions[::-1]
+        result += [minpos[idxs]]
+    if find_max:
+        maxs = np.zeros(labels.max() + 2, input.dtype)
+        maxs[labels] = input
+        result += [maxs[idxs]]
+    if find_max_positions:
+        maxpos = np.zeros(labels.max() + 2, int)
+        maxpos[labels] = positions
+        result += [maxpos[idxs]]
+    if find_median:
+        locs = np.arange(len(labels))
+        lo = np.zeros(labels.max() + 2, np.int_)
+        lo[labels[::-1]] = locs[::-1]
+        hi = np.zeros(labels.max() + 2, np.int_)
+        hi[labels] = locs
+        lo = lo[idxs]
+        hi = hi[idxs]
+        # lo is an index to the lowest value in input for each label,
+        # hi is an index to the largest value.
+        # move them to be either the same ((hi - lo) % 2 == 0) or next
+        # to each other ((hi - lo) % 2 == 1), then average.
+        step = (hi - lo) // 2
+        lo += step
+        hi -= step
+        if (np.issubdtype(input.dtype, np.integer)
+                or np.issubdtype(input.dtype, np.bool_)):
+            # avoid integer overflow or boolean addition (gh-12836)
+            result += [(input[lo].astype('d') + input[hi].astype('d')) / 2.0]
+        else:
+            result += [(input[lo] + input[hi]) / 2.0]
+
+    return result
+
+
+def minimum(input, labels=None, index=None):
+    """
+    Calculate the minimum of the values of an array over labeled regions.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values. For each region specified by `labels`, the
+        minimal values of `input` over the region is computed.
+    labels : array_like, optional
+        An array_like of integers marking different regions over which the
+        minimum value of `input` is to be computed. `labels` must have the
+        same shape as `input`. If `labels` is not specified, the minimum
+        over the whole array is returned.
+    index : array_like, optional
+        A list of region labels that are taken into account for computing the
+        minima. If index is None, the minimum over all elements where `labels`
+        is non-zero is returned.
+
+    Returns
+    -------
+    minimum : float or list of floats
+        List of minima of `input` over the regions determined by `labels` and
+        whose index is in `index`. If `index` or `labels` are not specified, a
+        float is returned: the minimal value of `input` if `labels` is None,
+        and the minimal value of elements where `labels` is greater than zero
+        if `index` is None.
+
+    See Also
+    --------
+    label, maximum, median, minimum_position, extrema, sum, mean, variance,
+    standard_deviation
+
+    Notes
+    -----
+    The function returns a Python list and not a NumPy array, use
+    `np.array` to convert the list to an array.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> labels, labels_nb = ndimage.label(a)
+    >>> labels
+    array([[1, 1, 0, 0],
+           [1, 1, 0, 2],
+           [0, 0, 0, 2],
+           [3, 3, 0, 0]], dtype=int32)
+    >>> ndimage.minimum(a, labels=labels, index=np.arange(1, labels_nb + 1))
+    [1, 4, 3]
+    >>> ndimage.minimum(a)
+    0
+    >>> ndimage.minimum(a, labels=labels)
+    1
+
+    """
+    return _select(input, labels, index, find_min=True)[0]
+
+
+def maximum(input, labels=None, index=None):
+    """
+    Calculate the maximum of the values of an array over labeled regions.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values. For each region specified by `labels`, the
+        maximal values of `input` over the region is computed.
+    labels : array_like, optional
+        An array of integers marking different regions over which the
+        maximum value of `input` is to be computed. `labels` must have the
+        same shape as `input`. If `labels` is not specified, the maximum
+        over the whole array is returned.
+    index : array_like, optional
+        A list of region labels that are taken into account for computing the
+        maxima. If index is None, the maximum over all elements where `labels`
+        is non-zero is returned.
+
+    Returns
+    -------
+    output : float or list of floats
+        List of maxima of `input` over the regions determined by `labels` and
+        whose index is in `index`. If `index` or `labels` are not specified, a
+        float is returned: the maximal value of `input` if `labels` is None,
+        and the maximal value of elements where `labels` is greater than zero
+        if `index` is None.
+
+    See Also
+    --------
+    label, minimum, median, maximum_position, extrema, sum, mean, variance,
+    standard_deviation
+
+    Notes
+    -----
+    The function returns a Python list and not a NumPy array, use
+    `np.array` to convert the list to an array.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.arange(16).reshape((4,4))
+    >>> a
+    array([[ 0,  1,  2,  3],
+           [ 4,  5,  6,  7],
+           [ 8,  9, 10, 11],
+           [12, 13, 14, 15]])
+    >>> labels = np.zeros_like(a)
+    >>> labels[:2,:2] = 1
+    >>> labels[2:, 1:3] = 2
+    >>> labels
+    array([[1, 1, 0, 0],
+           [1, 1, 0, 0],
+           [0, 2, 2, 0],
+           [0, 2, 2, 0]])
+    >>> from scipy import ndimage
+    >>> ndimage.maximum(a)
+    15
+    >>> ndimage.maximum(a, labels=labels, index=[1,2])
+    [5, 14]
+    >>> ndimage.maximum(a, labels=labels)
+    14
+
+    >>> b = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> labels, labels_nb = ndimage.label(b)
+    >>> labels
+    array([[1, 1, 0, 0],
+           [1, 1, 0, 2],
+           [0, 0, 0, 2],
+           [3, 3, 0, 0]], dtype=int32)
+    >>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1))
+    [5, 7, 9]
+
+    """
+    return _select(input, labels, index, find_max=True)[0]
+
+
+def median(input, labels=None, index=None):
+    """
+    Calculate the median of the values of an array over labeled regions.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values. For each region specified by `labels`, the
+        median value of `input` over the region is computed.
+    labels : array_like, optional
+        An array_like of integers marking different regions over which the
+        median value of `input` is to be computed. `labels` must have the
+        same shape as `input`. If `labels` is not specified, the median
+        over the whole array is returned.
+    index : array_like, optional
+        A list of region labels that are taken into account for computing the
+        medians. If index is None, the median over all elements where `labels`
+        is non-zero is returned.
+
+    Returns
+    -------
+    median : float or list of floats
+        List of medians of `input` over the regions determined by `labels` and
+        whose index is in `index`. If `index` or `labels` are not specified, a
+        float is returned: the median value of `input` if `labels` is None,
+        and the median value of elements where `labels` is greater than zero
+        if `index` is None.
+
+    See Also
+    --------
+    label, minimum, maximum, extrema, sum, mean, variance, standard_deviation
+
+    Notes
+    -----
+    The function returns a Python list and not a NumPy array, use
+    `np.array` to convert the list to an array.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 1],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> labels, labels_nb = ndimage.label(a)
+    >>> labels
+    array([[1, 1, 0, 2],
+           [1, 1, 0, 2],
+           [0, 0, 0, 2],
+           [3, 3, 0, 0]], dtype=int32)
+    >>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1))
+    [2.5, 4.0, 6.0]
+    >>> ndimage.median(a)
+    1.0
+    >>> ndimage.median(a, labels=labels)
+    3.0
+
+    """
+    return _select(input, labels, index, find_median=True)[0]
+
+
+def minimum_position(input, labels=None, index=None):
+    """
+    Find the positions of the minimums of the values of an array at labels.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values.
+    labels : array_like, optional
+        An array of integers marking different regions over which the
+        position of the minimum value of `input` is to be computed.
+        `labels` must have the same shape as `input`. If `labels` is not
+        specified, the location of the first minimum over the whole
+        array is returned.
+
+        The `labels` argument only works when `index` is specified.
+    index : array_like, optional
+        A list of region labels that are taken into account for finding the
+        location of the minima. If `index` is None, the ``first`` minimum
+        over all elements where `labels` is non-zero is returned.
+
+        The `index` argument only works when `labels` is specified.
+
+    Returns
+    -------
+    output : list of tuples of ints
+        Tuple of ints or list of tuples of ints that specify the location
+        of minima of `input` over the regions determined by `labels` and
+        whose index is in `index`.
+
+        If `index` or `labels` are not specified, a tuple of ints is
+        returned specifying the location of the first minimal value of `input`.
+
+    See Also
+    --------
+    label, minimum, median, maximum_position, extrema, sum, mean, variance,
+    standard_deviation
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[10, 20, 30],
+    ...               [40, 80, 100],
+    ...               [1, 100, 200]])
+    >>> b = np.array([[1, 2, 0, 1],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+
+    >>> from scipy import ndimage
+
+    >>> ndimage.minimum_position(a)
+    (2, 0)
+    >>> ndimage.minimum_position(b)
+    (0, 2)
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> label, pos = ndimage.label(a)
+    >>> ndimage.minimum_position(a, label, index=np.arange(1, pos+1))
+    [(2, 0)]
+
+    >>> label, pos = ndimage.label(b)
+    >>> ndimage.minimum_position(b, label, index=np.arange(1, pos+1))
+    [(0, 0), (0, 3), (3, 1)]
+
+    """
+    dims = np.array(np.asarray(input).shape)
+    # see np.unravel_index to understand this line.
+    dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+    result = _select(input, labels, index, find_min_positions=True)[0]
+
+    if np.isscalar(result):
+        return tuple((result // dim_prod) % dims)
+
+    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
+
+
+def maximum_position(input, labels=None, index=None):
+    """
+    Find the positions of the maximums of the values of an array at labels.
+
+    For each region specified by `labels`, the position of the maximum
+    value of `input` within the region is returned.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values.
+    labels : array_like, optional
+        An array of integers marking different regions over which the
+        position of the maximum value of `input` is to be computed.
+        `labels` must have the same shape as `input`. If `labels` is not
+        specified, the location of the first maximum over the whole
+        array is returned.
+
+        The `labels` argument only works when `index` is specified.
+    index : array_like, optional
+        A list of region labels that are taken into account for finding the
+        location of the maxima. If `index` is None, the first maximum
+        over all elements where `labels` is non-zero is returned.
+
+        The `index` argument only works when `labels` is specified.
+
+    Returns
+    -------
+    output : list of tuples of ints
+        List of tuples of ints that specify the location of maxima of
+        `input` over the regions determined by `labels` and whose index
+        is in `index`.
+
+        If `index` or `labels` are not specified, a tuple of ints is
+        returned specifying the location of the ``first`` maximal value
+        of `input`.
+
+    See Also
+    --------
+    label, minimum, median, maximum_position, extrema, sum, mean, variance,
+    standard_deviation
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> ndimage.maximum_position(a)
+    (3, 0)
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> lbl = np.array([[0, 1, 2, 3],
+    ...                 [0, 1, 2, 3],
+    ...                 [0, 1, 2, 3],
+    ...                 [0, 1, 2, 3]])
+    >>> ndimage.maximum_position(a, lbl, 1)
+    (1, 1)
+
+    If no index is given, non-zero `labels` are processed:
+
+    >>> ndimage.maximum_position(a, lbl)
+    (2, 3)
+
+    If there are no maxima, the position of the first element is returned:
+
+    >>> ndimage.maximum_position(a, lbl, 2)
+    (0, 2)
+
+    """
+    dims = np.array(np.asarray(input).shape)
+    # see np.unravel_index to understand this line.
+    dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+    result = _select(input, labels, index, find_max_positions=True)[0]
+
+    if np.isscalar(result):
+        return tuple((result // dim_prod) % dims)
+
+    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
+
+
+def extrema(input, labels=None, index=None):
+    """
+    Calculate the minimums and maximums of the values of an array
+    at labels, along with their positions.
+
+    Parameters
+    ----------
+    input : ndarray
+        N-D image data to process.
+    labels : ndarray, optional
+        Labels of features in input.
+        If not None, must be same shape as `input`.
+    index : int or sequence of ints, optional
+        Labels to include in output.  If None (default), all values where
+        non-zero `labels` are used.
+
+    Returns
+    -------
+    minimums, maximums : int or ndarray
+        Values of minimums and maximums in each feature.
+    min_positions, max_positions : tuple or list of tuples
+        Each tuple gives the N-D coordinates of the corresponding minimum
+        or maximum.
+
+    See Also
+    --------
+    maximum, minimum, maximum_position, minimum_position, center_of_mass
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> from scipy import ndimage
+    >>> ndimage.extrema(a)
+    (0, 9, (0, 2), (3, 0))
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> ndimage.extrema(a, lbl, index=np.arange(1, nlbl+1))
+    (array([1, 4, 3]),
+     array([5, 7, 9]),
+     [(0, 0), (1, 3), (3, 1)],
+     [(1, 0), (2, 3), (3, 0)])
+
+    If no index is given, non-zero `labels` are processed:
+
+    >>> ndimage.extrema(a, lbl)
+    (1, 9, (0, 0), (3, 0))
+
+    """
+    dims = np.array(np.asarray(input).shape)
+    # see np.unravel_index to understand this line.
+    dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+    minimums, min_positions, maximums, max_positions = _select(input, labels,
+                                                               index,
+                                                               find_min=True,
+                                                               find_max=True,
+                                                               find_min_positions=True,
+                                                               find_max_positions=True)
+
+    if np.isscalar(minimums):
+        return (minimums, maximums, tuple((min_positions // dim_prod) % dims),
+                tuple((max_positions // dim_prod) % dims))
+
+    min_positions = [
+        tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims
+    ]
+    max_positions = [
+        tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims
+    ]
+
+    return minimums, maximums, min_positions, max_positions
+
+
+def center_of_mass(input, labels=None, index=None):
+    """
+    Calculate the center of mass of the values of an array at labels.
+
+    Parameters
+    ----------
+    input : ndarray
+        Data from which to calculate center-of-mass. The masses can either
+        be positive or negative.
+    labels : ndarray, optional
+        Labels for objects in `input`, as generated by `ndimage.label`.
+        Only used with `index`. Dimensions must be the same as `input`.
+    index : int or sequence of ints, optional
+        Labels for which to calculate centers-of-mass. If not specified,
+        the combined center of mass of all labels greater than zero
+        will be calculated. Only used with `labels`.
+
+    Returns
+    -------
+    center_of_mass : tuple, or list of tuples
+        Coordinates of centers-of-mass.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array(([0,0,0,0],
+    ...               [0,1,1,0],
+    ...               [0,1,1,0],
+    ...               [0,1,1,0]))
+    >>> from scipy import ndimage
+    >>> ndimage.center_of_mass(a)
+    (2.0, 1.5)
+
+    Calculation of multiple objects in an image
+
+    >>> b = np.array(([0,1,1,0],
+    ...               [0,1,0,0],
+    ...               [0,0,0,0],
+    ...               [0,0,1,1],
+    ...               [0,0,1,1]))
+    >>> lbl = ndimage.label(b)[0]
+    >>> ndimage.center_of_mass(b, lbl, [1,2])
+    [(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)]
+
+    Negative masses are also accepted, which can occur for example when
+    bias is removed from measured data due to random noise.
+
+    >>> c = np.array(([-1,0,0,0],
+    ...               [0,-1,-1,0],
+    ...               [0,1,-1,0],
+    ...               [0,1,1,0]))
+    >>> ndimage.center_of_mass(c)
+    (-4.0, 1.0)
+
+    If there are division by zero issues, the function does not raise an
+    error but rather issues a RuntimeWarning before returning inf and/or NaN.
+
+    >>> d = np.array([-1, 1])
+    >>> ndimage.center_of_mass(d)
+    (inf,)
+    """
+    input = np.asarray(input)
+    normalizer = sum_labels(input, labels, index)
+    grids = np.ogrid[[slice(0, i) for i in input.shape]]
+
+    results = [sum_labels(input * grids[dir].astype(float), labels, index) / normalizer
+               for dir in range(input.ndim)]
+
+    if np.isscalar(results[0]):
+        return tuple(results)
+
+    return [tuple(v) for v in np.array(results).T]
+
+
+def histogram(input, min, max, bins, labels=None, index=None):
+    """
+    Calculate the histogram of the values of an array, optionally at labels.
+
+    Histogram calculates the frequency of values in an array within bins
+    determined by `min`, `max`, and `bins`. The `labels` and `index`
+    keywords can limit the scope of the histogram to specified sub-regions
+    within the array.
+
+    Parameters
+    ----------
+    input : array_like
+        Data for which to calculate histogram.
+    min, max : int
+        Minimum and maximum values of range of histogram bins.
+    bins : int
+        Number of bins.
+    labels : array_like, optional
+        Labels for objects in `input`.
+        If not None, must be same shape as `input`.
+    index : int or sequence of ints, optional
+        Label or labels for which to calculate histogram. If None, all values
+        where label is greater than zero are used
+
+    Returns
+    -------
+    hist : ndarray
+        Histogram counts.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[ 0.    ,  0.2146,  0.5962,  0.    ],
+    ...               [ 0.    ,  0.7778,  0.    ,  0.    ],
+    ...               [ 0.    ,  0.    ,  0.    ,  0.    ],
+    ...               [ 0.    ,  0.    ,  0.7181,  0.2787],
+    ...               [ 0.    ,  0.    ,  0.6573,  0.3094]])
+    >>> from scipy import ndimage
+    >>> ndimage.histogram(a, 0, 1, 10)
+    array([13,  0,  2,  1,  0,  1,  1,  2,  0,  0])
+
+    With labels and no indices, non-zero elements are counted:
+
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> ndimage.histogram(a, 0, 1, 10, lbl)
+    array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0])
+
+    Indices can be used to count only certain objects:
+
+    >>> ndimage.histogram(a, 0, 1, 10, lbl, 2)
+    array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])
+
+    """
+    _bins = np.linspace(min, max, bins + 1)
+
+    def _hist(vals):
+        return np.histogram(vals, _bins)[0]
+
+    return labeled_comprehension(input, labels, index, _hist, object, None,
+                                 pass_positions=False)
+
+
+def watershed_ift(input, markers, structure=None, output=None):
+    """
+    Apply watershed from markers using image foresting transform algorithm.
+
+    Parameters
+    ----------
+    input : array_like
+        Input.
+    markers : array_like
+        Markers are points within each watershed that form the beginning
+        of the process. Negative markers are considered background markers
+        which are processed after the other markers.
+    structure : structure element, optional
+        A structuring element defining the connectivity of the object can be
+        provided. If None, an element is generated with a squared
+        connectivity equal to one.
+    output : ndarray, optional
+        An output array can optionally be provided. The same shape as input.
+
+    Returns
+    -------
+    watershed_ift : ndarray
+        Output.  Same shape as `input`.
+
+    References
+    ----------
+    .. [1] A.X. Falcao, J. Stolfi and R. de Alencar Lotufo, "The image
+           foresting transform: theory, algorithms, and applications",
+           Pattern Analysis and Machine Intelligence, vol. 26, pp. 19-29, 2004.
+
+    """
+    input = np.asarray(input)
+    if input.dtype.type not in [np.uint8, np.uint16]:
+        raise TypeError('only 8 and 16 unsigned inputs are supported')
+
+    if structure is None:
+        structure = _morphology.generate_binary_structure(input.ndim, 1)
+    structure = np.asarray(structure, dtype=bool)
+    if structure.ndim != input.ndim:
+        raise RuntimeError('structure and input must have equal rank')
+    for ii in structure.shape:
+        if ii != 3:
+            raise RuntimeError('structure dimensions must be equal to 3')
+
+    if not structure.flags.contiguous:
+        structure = structure.copy()
+    markers = np.asarray(markers)
+    if input.shape != markers.shape:
+        raise RuntimeError('input and markers must have equal shape')
+
+    integral_types = [np.int8,
+                      np.int16,
+                      np.int32,
+                      np.int64,
+                      np.intc,
+                      np.intp]
+
+    if markers.dtype.type not in integral_types:
+        raise RuntimeError('marker should be of integer type')
+
+    if isinstance(output, np.ndarray):
+        if output.dtype.type not in integral_types:
+            raise RuntimeError('output should be of integer type')
+    else:
+        output = markers.dtype
+
+    output = _ni_support._get_output(output, input)
+    _nd_image.watershed_ift(input, markers, structure, output)
+    return output
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_morphology.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..12972c09a7cd5de0ca059814281fb9d210fbd395
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_morphology.py
@@ -0,0 +1,2629 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# 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 warnings
+import operator
+
+import numpy as np
+from . import _ni_support
+from . import _nd_image
+from . import _filters
+
+__all__ = ['iterate_structure', 'generate_binary_structure', 'binary_erosion',
+           'binary_dilation', 'binary_opening', 'binary_closing',
+           'binary_hit_or_miss', 'binary_propagation', 'binary_fill_holes',
+           'grey_erosion', 'grey_dilation', 'grey_opening', 'grey_closing',
+           'morphological_gradient', 'morphological_laplace', 'white_tophat',
+           'black_tophat', 'distance_transform_bf', 'distance_transform_cdt',
+           'distance_transform_edt']
+
+
+def _center_is_true(structure, origin):
+    structure = np.asarray(structure)
+    coor = tuple([oo + ss // 2 for ss, oo in zip(structure.shape,
+                                                 origin)])
+    return bool(structure[coor])
+
+
+def iterate_structure(structure, iterations, origin=None):
+    """
+    Iterate a structure by dilating it with itself.
+
+    Parameters
+    ----------
+    structure : array_like
+       Structuring element (an array of bools, for example), to be dilated with
+       itself.
+    iterations : int
+       number of dilations performed on the structure with itself
+    origin : optional
+        If origin is None, only the iterated structure is returned. If
+        not, a tuple of the iterated structure and the modified origin is
+        returned.
+
+    Returns
+    -------
+    iterate_structure : ndarray of bools
+        A new structuring element obtained by dilating `structure`
+        (`iterations` - 1) times with itself.
+
+    See Also
+    --------
+    generate_binary_structure
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> struct = ndimage.generate_binary_structure(2, 1)
+    >>> struct.astype(int)
+    array([[0, 1, 0],
+           [1, 1, 1],
+           [0, 1, 0]])
+    >>> ndimage.iterate_structure(struct, 2).astype(int)
+    array([[0, 0, 1, 0, 0],
+           [0, 1, 1, 1, 0],
+           [1, 1, 1, 1, 1],
+           [0, 1, 1, 1, 0],
+           [0, 0, 1, 0, 0]])
+    >>> ndimage.iterate_structure(struct, 3).astype(int)
+    array([[0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [1, 1, 1, 1, 1, 1, 1],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 1, 0, 0, 0]])
+
+    """
+    structure = np.asarray(structure)
+    if iterations < 2:
+        return structure.copy()
+    ni = iterations - 1
+    shape = [ii + ni * (ii - 1) for ii in structure.shape]
+    pos = [ni * (structure.shape[ii] // 2) for ii in range(len(shape))]
+    slc = tuple(slice(pos[ii], pos[ii] + structure.shape[ii], None)
+                for ii in range(len(shape)))
+    out = np.zeros(shape, bool)
+    out[slc] = structure != 0
+    out = binary_dilation(out, structure, iterations=ni)
+    if origin is None:
+        return out
+    else:
+        origin = _ni_support._normalize_sequence(origin, structure.ndim)
+        origin = [iterations * o for o in origin]
+        return out, origin
+
+
+def generate_binary_structure(rank, connectivity):
+    """
+    Generate a binary structure for binary morphological operations.
+
+    Parameters
+    ----------
+    rank : int
+         Number of dimensions of the array to which the structuring element
+         will be applied, as returned by `np.ndim`.
+    connectivity : int
+         `connectivity` determines which elements of the output array belong
+         to the structure, i.e., are considered as neighbors of the central
+         element. Elements up to a squared distance of `connectivity` from
+         the center are considered neighbors. `connectivity` may range from 1
+         (no diagonal elements are neighbors) to `rank` (all elements are
+         neighbors).
+
+    Returns
+    -------
+    output : ndarray of bools
+         Structuring element which may be used for binary morphological
+         operations, with `rank` dimensions and all dimensions equal to 3.
+
+    See Also
+    --------
+    iterate_structure, binary_dilation, binary_erosion
+
+    Notes
+    -----
+    `generate_binary_structure` can only create structuring elements with
+    dimensions equal to 3, i.e., minimal dimensions. For larger structuring
+    elements, that are useful e.g., for eroding large objects, one may either
+    use `iterate_structure`, or create directly custom arrays with
+    numpy functions such as `numpy.ones`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> struct = ndimage.generate_binary_structure(2, 1)
+    >>> struct
+    array([[False,  True, False],
+           [ True,  True,  True],
+           [False,  True, False]], dtype=bool)
+    >>> a = np.zeros((5,5))
+    >>> a[2, 2] = 1
+    >>> a
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
+    >>> b
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
+    array([[ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 1.,  1.,  1.,  1.,  1.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.]])
+    >>> struct = ndimage.generate_binary_structure(2, 2)
+    >>> struct
+    array([[ True,  True,  True],
+           [ True,  True,  True],
+           [ True,  True,  True]], dtype=bool)
+    >>> struct = ndimage.generate_binary_structure(3, 1)
+    >>> struct # no diagonal elements
+    array([[[False, False, False],
+            [False,  True, False],
+            [False, False, False]],
+           [[False,  True, False],
+            [ True,  True,  True],
+            [False,  True, False]],
+           [[False, False, False],
+            [False,  True, False],
+            [False, False, False]]], dtype=bool)
+
+    """
+    if connectivity < 1:
+        connectivity = 1
+    if rank < 1:
+        return np.array(True, dtype=bool)
+    output = np.fabs(np.indices([3] * rank) - 1)
+    output = np.add.reduce(output, 0)
+    return output <= connectivity
+
+
+def _binary_erosion(input, structure, iterations, mask, output,
+                    border_value, origin, invert, brute_force, axes):
+    try:
+        iterations = operator.index(iterations)
+    except TypeError as e:
+        raise TypeError('iterations parameter should be an integer') from e
+
+    input = np.asarray(input)
+    ndim = input.ndim
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure is None:
+        structure = generate_binary_structure(num_axes, 1)
+    else:
+        structure = np.asarray(structure, dtype=bool)
+    if ndim > num_axes:
+        structure = _filters._expand_footprint(ndim, axes, structure,
+                                               footprint_name="structure")
+
+    if structure.ndim != input.ndim:
+        raise RuntimeError('structure and input must have same dimensionality')
+    if not structure.flags.contiguous:
+        structure = structure.copy()
+    if structure.size < 1:
+        raise RuntimeError('structure must not be empty')
+    if mask is not None:
+        mask = np.asarray(mask)
+        if mask.shape != input.shape:
+            raise RuntimeError('mask and input must have equal sizes')
+    origin = _ni_support._normalize_sequence(origin, num_axes)
+    origin = _filters._expand_origin(ndim, axes, origin)
+    cit = _center_is_true(structure, origin)
+    if isinstance(output, np.ndarray):
+        if np.iscomplexobj(output):
+            raise TypeError('Complex output type not supported')
+    else:
+        output = bool
+    output = _ni_support._get_output(output, input)
+    temp_needed = np.may_share_memory(input, output)
+    if temp_needed:
+        # input and output arrays cannot share memory
+        temp = output
+        output = _ni_support._get_output(output.dtype, input)
+    if iterations == 1:
+        _nd_image.binary_erosion(input, structure, mask, output,
+                                 border_value, origin, invert, cit, 0)
+    elif cit and not brute_force:
+        changed, coordinate_list = _nd_image.binary_erosion(
+            input, structure, mask, output,
+            border_value, origin, invert, cit, 1)
+        structure = structure[tuple([slice(None, None, -1)] *
+                                    structure.ndim)]
+        for ii in range(len(origin)):
+            origin[ii] = -origin[ii]
+            if not structure.shape[ii] & 1:
+                origin[ii] -= 1
+        if mask is not None:
+            mask = np.asarray(mask, dtype=np.int8)
+        if not structure.flags.contiguous:
+            structure = structure.copy()
+        _nd_image.binary_erosion2(output, structure, mask, iterations - 1,
+                                  origin, invert, coordinate_list)
+    else:
+        tmp_in = np.empty_like(input, dtype=bool)
+        tmp_out = output
+        if iterations >= 1 and not iterations & 1:
+            tmp_in, tmp_out = tmp_out, tmp_in
+        changed = _nd_image.binary_erosion(
+            input, structure, mask, tmp_out,
+            border_value, origin, invert, cit, 0)
+        ii = 1
+        while ii < iterations or (iterations < 1 and changed):
+            tmp_in, tmp_out = tmp_out, tmp_in
+            changed = _nd_image.binary_erosion(
+                tmp_in, structure, mask, tmp_out,
+                border_value, origin, invert, cit, 0)
+            ii += 1
+    if temp_needed:
+        temp[...] = output
+        output = temp
+    return output
+
+
+def binary_erosion(input, structure=None, iterations=1, mask=None, output=None,
+                   border_value=0, origin=0, brute_force=False, *, axes=None):
+    """
+    Multidimensional binary erosion with a given structuring element.
+
+    Binary erosion is a mathematical morphology operation used for image
+    processing.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary image to be eroded. Non-zero (True) elements form
+        the subset to be eroded.
+    structure : array_like, optional
+        Structuring element used for the erosion. Non-zero elements are
+        considered True. If no structuring element is provided, an element
+        is generated with a square connectivity equal to one.
+    iterations : int, optional
+        The erosion is repeated `iterations` times (one, by default).
+        If iterations is less than 1, the erosion is repeated until the
+        result does not change anymore.
+    mask : array_like, optional
+        If a mask is given, only those elements with a True value at
+        the corresponding mask element are modified at each iteration.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    brute_force : boolean, optional
+        Memory condition: if False, only the pixels whose value was changed in
+        the last iteration are tracked as candidates to be updated (eroded) in
+        the current iteration; if True all pixels are considered as candidates
+        for erosion, regardless of what happened in the previous iteration.
+        False by default.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_erosion : ndarray of bools
+        Erosion of the input by the structuring element.
+
+    See Also
+    --------
+    grey_erosion, binary_dilation, binary_closing, binary_opening,
+    generate_binary_structure
+
+    Notes
+    -----
+    Erosion [1]_ is a mathematical morphology operation [2]_ that uses a
+    structuring element for shrinking the shapes in an image. The binary
+    erosion of an image by a structuring element is the locus of the points
+    where a superimposition of the structuring element centered on the point
+    is entirely contained in the set of non-zero elements of the image.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[1:6, 2:5] = 1
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.binary_erosion(a).astype(a.dtype)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 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]])
+    >>> #Erosion removes objects smaller than the structure
+    >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
+    array([[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]])
+
+    """
+    return _binary_erosion(input, structure, iterations, mask,
+                           output, border_value, origin, 0, brute_force, axes)
+
+
+def binary_dilation(input, structure=None, iterations=1, mask=None,
+                    output=None, border_value=0, origin=0,
+                    brute_force=False, *, axes=None):
+    """
+    Multidimensional binary dilation with the given structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary array_like to be dilated. Non-zero (True) elements form
+        the subset to be dilated.
+    structure : array_like, optional
+        Structuring element used for the dilation. Non-zero elements are
+        considered True. If no structuring element is provided an element
+        is generated with a square connectivity equal to one.
+    iterations : int, optional
+        The dilation is repeated `iterations` times (one, by default).
+        If iterations is less than 1, the dilation is repeated until the
+        result does not change anymore. Only an integer of iterations is
+        accepted.
+    mask : array_like, optional
+        If a mask is given, only those elements with a True value at
+        the corresponding mask element are modified at each iteration.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    brute_force : boolean, optional
+        Memory condition: if False, only the pixels whose value was changed in
+        the last iteration are tracked as candidates to be updated (dilated)
+        in the current iteration; if True all pixels are considered as
+        candidates for dilation, regardless of what happened in the previous
+        iteration. False by default.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_dilation : ndarray of bools
+        Dilation of the input by the structuring element.
+
+    See Also
+    --------
+    grey_dilation, binary_erosion, binary_closing, binary_opening,
+    generate_binary_structure
+
+    Notes
+    -----
+    Dilation [1]_ is a mathematical morphology operation [2]_ that uses a
+    structuring element for expanding the shapes in an image. The binary
+    dilation of an image by a structuring element is the locus of the points
+    covered by the structuring element, when its center lies within the
+    non-zero points of the image.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((5, 5))
+    >>> a[2, 2] = 1
+    >>> a
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> ndimage.binary_dilation(a)
+    array([[False, False, False, False, False],
+           [False, False,  True, False, False],
+           [False,  True,  True,  True, False],
+           [False, False,  True, False, False],
+           [False, False, False, False, False]], dtype=bool)
+    >>> ndimage.binary_dilation(a).astype(a.dtype)
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> # 3x3 structuring element with connectivity 1, used by default
+    >>> struct1 = ndimage.generate_binary_structure(2, 1)
+    >>> struct1
+    array([[False,  True, False],
+           [ True,  True,  True],
+           [False,  True, False]], dtype=bool)
+    >>> # 3x3 structuring element with connectivity 2
+    >>> struct2 = ndimage.generate_binary_structure(2, 2)
+    >>> struct2
+    array([[ True,  True,  True],
+           [ True,  True,  True],
+           [ True,  True,  True]], dtype=bool)
+    >>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype)
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype)
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> ndimage.binary_dilation(a, structure=struct1,\\
+    ... iterations=2).astype(a.dtype)
+    array([[ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 1.,  1.,  1.,  1.,  1.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.]])
+
+    """
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure is None:
+        structure = generate_binary_structure(num_axes, 1)
+    origin = _ni_support._normalize_sequence(origin, num_axes)
+    structure = np.asarray(structure)
+    structure = structure[tuple([slice(None, None, -1)] *
+                                structure.ndim)]
+    for ii in range(len(origin)):
+        origin[ii] = -origin[ii]
+        if not structure.shape[ii] & 1:
+            origin[ii] -= 1
+
+    return _binary_erosion(input, structure, iterations, mask,
+                           output, border_value, origin, 1, brute_force, axes)
+
+
+def binary_opening(input, structure=None, iterations=1, output=None,
+                   origin=0, mask=None, border_value=0, brute_force=False, *,
+                   axes=None):
+    """
+    Multidimensional binary opening with the given structuring element.
+
+    The *opening* of an input image by a structuring element is the
+    *dilation* of the *erosion* of the image by the structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary array_like to be opened. Non-zero (True) elements form
+        the subset to be opened.
+    structure : array_like, optional
+        Structuring element used for the opening. Non-zero elements are
+        considered True. If no structuring element is provided an element
+        is generated with a square connectivity equal to one (i.e., only
+        nearest neighbors are connected to the center, diagonally-connected
+        elements are not considered neighbors).
+    iterations : int, optional
+        The erosion step of the opening, then the dilation step are each
+        repeated `iterations` times (one, by default). If `iterations` is
+        less than 1, each operation is repeated until the result does
+        not change anymore. Only an integer of iterations is accepted.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    mask : array_like, optional
+        If a mask is given, only those elements with a True value at
+        the corresponding mask element are modified at each iteration.
+
+        .. versionadded:: 1.1.0
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+
+        .. versionadded:: 1.1.0
+    brute_force : boolean, optional
+        Memory condition: if False, only the pixels whose value was changed in
+        the last iteration are tracked as candidates to be updated in the
+        current iteration; if true all pixels are considered as candidates for
+        update, regardless of what happened in the previous iteration.
+        False by default.
+
+        .. versionadded:: 1.1.0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_opening : ndarray of bools
+        Opening of the input by the structuring element.
+
+    See Also
+    --------
+    grey_opening, binary_closing, binary_erosion, binary_dilation,
+    generate_binary_structure
+
+    Notes
+    -----
+    *Opening* [1]_ is a mathematical morphology operation [2]_ that
+    consists in the succession of an erosion and a dilation of the
+    input with the same structuring element. Opening, therefore, removes
+    objects smaller than the structuring element.
+
+    Together with *closing* (`binary_closing`), opening can be used for
+    noise removal.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Opening_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((5,5), dtype=int)
+    >>> a[1:4, 1:4] = 1; a[4, 4] = 1
+    >>> a
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 1]])
+    >>> # Opening removes small objects
+    >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Opening can also smooth corners
+    >>> ndimage.binary_opening(a).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Opening is the dilation of the erosion of the input
+    >>> ndimage.binary_erosion(a).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0]])
+    >>> ndimage.binary_dilation(ndimage.binary_erosion(a)).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure is None:
+        structure = generate_binary_structure(num_axes, 1)
+
+    tmp = binary_erosion(input, structure, iterations, mask, None,
+                         border_value, origin, brute_force, axes=axes)
+    return binary_dilation(tmp, structure, iterations, mask, output,
+                           border_value, origin, brute_force, axes=axes)
+
+
+def binary_closing(input, structure=None, iterations=1, output=None,
+                   origin=0, mask=None, border_value=0, brute_force=False, *,
+                   axes=None):
+    """
+    Multidimensional binary closing with the given structuring element.
+
+    The *closing* of an input image by a structuring element is the
+    *erosion* of the *dilation* of the image by the structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary array_like to be closed. Non-zero (True) elements form
+        the subset to be closed.
+    structure : array_like, optional
+        Structuring element used for the closing. Non-zero elements are
+        considered True. If no structuring element is provided an element
+        is generated with a square connectivity equal to one (i.e., only
+        nearest neighbors are connected to the center, diagonally-connected
+        elements are not considered neighbors).
+    iterations : int, optional
+        The dilation step of the closing, then the erosion step are each
+        repeated `iterations` times (one, by default). If iterations is
+        less than 1, each operations is repeated until the result does
+        not change anymore. Only an integer of iterations is accepted.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    mask : array_like, optional
+        If a mask is given, only those elements with a True value at
+        the corresponding mask element are modified at each iteration.
+
+        .. versionadded:: 1.1.0
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+
+        .. versionadded:: 1.1.0
+    brute_force : boolean, optional
+        Memory condition: if False, only the pixels whose value was changed in
+        the last iteration are tracked as candidates to be updated in the
+        current iteration; if true al pixels are considered as candidates for
+        update, regardless of what happened in the previous iteration.
+        False by default.
+
+        .. versionadded:: 1.1.0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_closing : ndarray of bools
+        Closing of the input by the structuring element.
+
+    See Also
+    --------
+    grey_closing, binary_opening, binary_dilation, binary_erosion,
+    generate_binary_structure
+
+    Notes
+    -----
+    *Closing* [1]_ is a mathematical morphology operation [2]_ that
+    consists in the succession of a dilation and an erosion of the
+    input with the same structuring element. Closing therefore fills
+    holes smaller than the structuring element.
+
+    Together with *opening* (`binary_opening`), closing can be used for
+    noise removal.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Closing_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((5,5), dtype=int)
+    >>> a[1:-1, 1:-1] = 1; a[2,2] = 0
+    >>> a
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 0, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Closing removes small holes
+    >>> ndimage.binary_closing(a).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Closing is the erosion of the dilation of the input
+    >>> ndimage.binary_dilation(a).astype(int)
+    array([[0, 1, 1, 1, 0],
+           [1, 1, 1, 1, 1],
+           [1, 1, 1, 1, 1],
+           [1, 1, 1, 1, 1],
+           [0, 1, 1, 1, 0]])
+    >>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+
+
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[1:6, 2:5] = 1; a[1:3,3] = 0
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 1, 0, 0],
+           [0, 0, 1, 0, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> # In addition to removing holes, closing can also
+    >>> # coarsen boundaries with fine hollows.
+    >>> ndimage.binary_closing(a).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure is None:
+        structure = generate_binary_structure(num_axes, 1)
+
+    tmp = binary_dilation(input, structure, iterations, mask, None,
+                          border_value, origin, brute_force, axes=axes)
+    return binary_erosion(tmp, structure, iterations, mask, output,
+                          border_value, origin, brute_force, axes=axes)
+
+
+def binary_hit_or_miss(input, structure1=None, structure2=None,
+                       output=None, origin1=0, origin2=None, *, axes=None):
+    """
+    Multidimensional binary hit-or-miss transform.
+
+    The hit-or-miss transform finds the locations of a given pattern
+    inside the input image.
+
+    Parameters
+    ----------
+    input : array_like (cast to booleans)
+        Binary image where a pattern is to be detected.
+    structure1 : array_like (cast to booleans), optional
+        Part of the structuring element to be fitted to the foreground
+        (non-zero elements) of `input`. If no value is provided, a
+        structure of square connectivity 1 is chosen.
+    structure2 : array_like (cast to booleans), optional
+        Second part of the structuring element that has to miss completely
+        the foreground. If no value is provided, the complementary of
+        `structure1` is taken.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    origin1 : int or tuple of ints, optional
+        Placement of the first part of the structuring element `structure1`,
+        by default 0 for a centered structure.
+    origin2 : int or tuple of ints, optional
+        Placement of the second part of the structuring element `structure2`,
+        by default 0 for a centered structure. If a value is provided for
+        `origin1` and not for `origin2`, then `origin2` is set to `origin1`.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If `origin1` or `origin2` tuples are provided, their
+        length must match the number of axes.
+
+    Returns
+    -------
+    binary_hit_or_miss : ndarray
+        Hit-or-miss transform of `input` with the given structuring
+        element (`structure1`, `structure2`).
+
+    See Also
+    --------
+    binary_erosion
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Hit-or-miss_transform
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[1, 1] = 1; a[2:4, 2:4] = 1; a[4:6, 4:6] = 1
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 0, 0, 0],
+           [0, 0, 1, 1, 0, 0, 0],
+           [0, 0, 0, 0, 1, 1, 0],
+           [0, 0, 0, 0, 1, 1, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> structure1 = np.array([[1, 0, 0], [0, 1, 1], [0, 1, 1]])
+    >>> structure1
+    array([[1, 0, 0],
+           [0, 1, 1],
+           [0, 1, 1]])
+    >>> # Find the matches of structure1 in the array a
+    >>> ndimage.binary_hit_or_miss(a, structure1=structure1).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> # Change the origin of the filter
+    >>> # origin1=1 is equivalent to origin1=(1,1) here
+    >>> ndimage.binary_hit_or_miss(a, structure1=structure1,\\
+    ... origin1=1).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 1, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure1 is None:
+        structure1 = generate_binary_structure(num_axes, 1)
+    else:
+        structure1 = np.asarray(structure1)
+    if structure2 is None:
+        structure2 = np.logical_not(structure1)
+    origin1 = _ni_support._normalize_sequence(origin1, num_axes)
+    if origin2 is None:
+        origin2 = origin1
+    else:
+        origin2 = _ni_support._normalize_sequence(origin2, num_axes)
+
+    tmp1 = _binary_erosion(input, structure1, 1, None, None, 0, origin1,
+                           0, False, axes)
+    inplace = isinstance(output, np.ndarray)
+    result = _binary_erosion(input, structure2, 1, None, output, 0,
+                             origin2, 1, False, axes)
+    if inplace:
+        np.logical_not(output, output)
+        np.logical_and(tmp1, output, output)
+    else:
+        np.logical_not(result, result)
+        return np.logical_and(tmp1, result)
+
+
+def binary_propagation(input, structure=None, mask=None,
+                       output=None, border_value=0, origin=0, *, axes=None):
+    """
+    Multidimensional binary propagation with the given structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary image to be propagated inside `mask`.
+    structure : array_like, optional
+        Structuring element used in the successive dilations. The output
+        may depend on the structuring element, especially if `mask` has
+        several connex components. If no structuring element is
+        provided, an element is generated with a squared connectivity equal
+        to one.
+    mask : array_like, optional
+        Binary mask defining the region into which `input` is allowed to
+        propagate.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_propagation : ndarray
+        Binary propagation of `input` inside `mask`.
+
+    Notes
+    -----
+    This function is functionally equivalent to calling binary_dilation
+    with the number of iterations less than one: iterative dilation until
+    the result does not change anymore.
+
+    The succession of an erosion and propagation inside the original image
+    can be used instead of an *opening* for deleting small objects while
+    keeping the contours of larger objects untouched.
+
+    References
+    ----------
+    .. [1] http://cmm.ensmp.fr/~serra/cours/pdf/en/ch6en.pdf, slide 15.
+    .. [2] I.T. Young, J.J. Gerbrands, and L.J. van Vliet, "Fundamentals of
+        image processing", 1998
+        ftp://qiftp.tudelft.nl/DIPimage/docs/FIP2.3.pdf
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> input = np.zeros((8, 8), dtype=int)
+    >>> input[2, 2] = 1
+    >>> mask = np.zeros((8, 8), dtype=int)
+    >>> mask[1:4, 1:4] = mask[4, 4]  = mask[6:8, 6:8] = 1
+    >>> input
+    array([[0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 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, 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]])
+    >>> mask
+    array([[0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 1, 1],
+           [0, 0, 0, 0, 0, 0, 1, 1]])
+    >>> ndimage.binary_propagation(input, mask=mask).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 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, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.binary_propagation(input, mask=mask,\\
+    ... structure=np.ones((3,3))).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 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, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0]])
+
+    >>> # Comparison between opening and erosion+propagation
+    >>> a = np.zeros((6,6), dtype=int)
+    >>> a[2:5, 2:5] = 1; a[0, 0] = 1; a[5, 5] = 1
+    >>> a
+    array([[1, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0, 1]])
+    >>> ndimage.binary_opening(a).astype(int)
+    array([[0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0]])
+    >>> b = ndimage.binary_erosion(a)
+    >>> b.astype(int)
+    array([[0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0]])
+    >>> ndimage.binary_propagation(b, mask=a).astype(int)
+    array([[0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0, 0]])
+
+    """
+    return binary_dilation(input, structure, -1, mask, output,
+                           border_value, origin, axes=axes)
+
+
+def binary_fill_holes(input, structure=None, output=None, origin=0, *,
+                      axes=None):
+    """
+    Fill the holes in binary objects.
+
+
+    Parameters
+    ----------
+    input : array_like
+        N-D binary array with holes to be filled
+    structure : array_like, optional
+        Structuring element used in the computation; large-size elements
+        make computations faster but may miss holes separated from the
+        background by thin regions. The default element (with a square
+        connectivity equal to one) yields the intuitive result where all
+        holes in the input have been filled.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    origin : int, tuple of ints, optional
+        Position of the structuring element.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    out : ndarray
+        Transformation of the initial image `input` where holes have been
+        filled.
+
+    See Also
+    --------
+    binary_dilation, binary_propagation, label
+
+    Notes
+    -----
+    The algorithm used in this function consists in invading the complementary
+    of the shapes in `input` from the outer boundary of the image,
+    using binary dilations. Holes are not connected to the boundary and are
+    therefore not invaded. The result is the complementary subset of the
+    invaded region.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((5, 5), dtype=int)
+    >>> a[1:4, 1:4] = 1
+    >>> a[2,2] = 0
+    >>> a
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 0, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> ndimage.binary_fill_holes(a).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Too big structuring element
+    >>> ndimage.binary_fill_holes(a, structure=np.ones((5,5))).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 0, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+    mask = np.logical_not(input)
+    tmp = np.zeros(mask.shape, bool)
+    inplace = isinstance(output, np.ndarray)
+    if inplace:
+        binary_dilation(tmp, structure, -1, mask, output, 1, origin, axes=axes)
+        np.logical_not(output, output)
+    else:
+        output = binary_dilation(tmp, structure, -1, mask, None, 1,
+                                 origin, axes=axes)
+        np.logical_not(output, output)
+        return output
+
+
+def grey_erosion(input, size=None, footprint=None, structure=None,
+                 output=None, mode="reflect", cval=0.0, origin=0, *,
+                 axes=None):
+    """
+    Calculate a greyscale erosion, using either a structuring element,
+    or a footprint corresponding to a flat structuring element.
+
+    Grayscale erosion is a mathematical morphology operation. For the
+    simple case of a full and flat structuring element, it can be viewed
+    as a minimum filter over a sliding window.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which the grayscale erosion is to be computed.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the grayscale
+        erosion. Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the grayscale erosion. Non-zero values give the set of
+        neighbors of the center over which the minimum is chosen.
+    structure : array of ints, optional
+        Structuring element used for the grayscale erosion. `structure`
+        may be a non-flat structuring element. The `structure` array applies a
+        subtractive offset for each pixel in the neighborhood.
+    output : array, optional
+        An array used for storing the output of the erosion may be provided.
+    mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    output : ndarray
+        Grayscale erosion of `input`.
+
+    See Also
+    --------
+    binary_erosion, grey_dilation, grey_opening, grey_closing
+    generate_binary_structure, minimum_filter
+
+    Notes
+    -----
+    The grayscale erosion of an image input by a structuring element s defined
+    over a domain E is given by:
+
+    (input+s)(x) = min {input(y) - s(x-y), for y in E}
+
+    In particular, for structuring elements defined as
+    s(y) = 0 for y in E, the grayscale erosion computes the minimum of the
+    input image inside a sliding window defined by E.
+
+    Grayscale erosion [1]_ is a *mathematical morphology* operation [2]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[1:6, 1:6] = 3
+    >>> a[4,4] = 2; a[2,3] = 1
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 3, 3, 3, 3, 3, 0],
+           [0, 3, 3, 1, 3, 3, 0],
+           [0, 3, 3, 3, 3, 3, 0],
+           [0, 3, 3, 3, 2, 3, 0],
+           [0, 3, 3, 3, 3, 3, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.grey_erosion(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 3, 2, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> footprint = ndimage.generate_binary_structure(2, 1)
+    >>> footprint
+    array([[False,  True, False],
+           [ True,  True,  True],
+           [False,  True, False]], dtype=bool)
+    >>> # Diagonally-connected elements are not considered neighbors
+    >>> ndimage.grey_erosion(a, footprint=footprint)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 3, 1, 2, 0, 0],
+           [0, 0, 3, 2, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    if size is None and footprint is None and structure is None:
+        raise ValueError("size, footprint, or structure must be specified")
+
+    return _filters._min_or_max_filter(input, size, footprint, structure,
+                                       output, mode, cval, origin, 1,
+                                       axes=axes)
+
+
+def grey_dilation(input, size=None, footprint=None, structure=None,
+                  output=None, mode="reflect", cval=0.0, origin=0, *,
+                  axes=None):
+    """
+    Calculate a greyscale dilation, using either a structuring element,
+    or a footprint corresponding to a flat structuring element.
+
+    Grayscale dilation is a mathematical morphology operation. For the
+    simple case of a full and flat structuring element, it can be viewed
+    as a maximum filter over a sliding window.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which the grayscale dilation is to be computed.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the grayscale
+        dilation. Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the grayscale dilation. Non-zero values give the set of
+        neighbors of the center over which the maximum is chosen.
+    structure : array of ints, optional
+        Structuring element used for the grayscale dilation. `structure`
+        may be a non-flat structuring element. The `structure` array applies an
+        additive offset for each pixel in the neighborhood.
+    output : array, optional
+        An array used for storing the output of the dilation may be provided.
+    mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    grey_dilation : ndarray
+        Grayscale dilation of `input`.
+
+    See Also
+    --------
+    binary_dilation, grey_erosion, grey_closing, grey_opening
+    generate_binary_structure, maximum_filter
+
+    Notes
+    -----
+    The grayscale dilation of an image input by a structuring element s defined
+    over a domain E is given by:
+
+    (input+s)(x) = max {input(y) + s(x-y), for y in E}
+
+    In particular, for structuring elements defined as
+    s(y) = 0 for y in E, the grayscale dilation computes the maximum of the
+    input image inside a sliding window defined by E.
+
+    Grayscale dilation [1]_ is a *mathematical morphology* operation [2]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[2:5, 2:5] = 1
+    >>> a[4,4] = 2; a[2,3] = 3
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 3, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.grey_dilation(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.grey_dilation(a, footprint=np.ones((3,3)))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> s = ndimage.generate_binary_structure(2,1)
+    >>> s
+    array([[False,  True, False],
+           [ True,  True,  True],
+           [False,  True, False]], dtype=bool)
+    >>> ndimage.grey_dilation(a, footprint=s)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 3, 1, 0, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 1, 3, 2, 1, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 0, 1, 1, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.grey_dilation(a, size=(3,3), structure=np.ones((3,3)))
+    array([[1, 1, 1, 1, 1, 1, 1],
+           [1, 2, 4, 4, 4, 2, 1],
+           [1, 2, 4, 4, 4, 2, 1],
+           [1, 2, 4, 4, 4, 3, 1],
+           [1, 2, 2, 3, 3, 3, 1],
+           [1, 2, 2, 3, 3, 3, 1],
+           [1, 1, 1, 1, 1, 1, 1]])
+
+    """
+    if size is None and footprint is None and structure is None:
+        raise ValueError("size, footprint, or structure must be specified")
+    if structure is not None:
+        structure = np.asarray(structure)
+        structure = structure[tuple([slice(None, None, -1)] *
+                                    structure.ndim)]
+    if footprint is not None:
+        footprint = np.asarray(footprint)
+        footprint = footprint[tuple([slice(None, None, -1)] *
+                                    footprint.ndim)]
+
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    origin = _ni_support._normalize_sequence(origin, len(axes))
+    for ii in range(len(origin)):
+        origin[ii] = -origin[ii]
+        if footprint is not None:
+            sz = footprint.shape[ii]
+        elif structure is not None:
+            sz = structure.shape[ii]
+        elif np.isscalar(size):
+            sz = size
+        else:
+            sz = size[ii]
+        if not sz & 1:
+            origin[ii] -= 1
+
+    return _filters._min_or_max_filter(input, size, footprint, structure,
+                                       output, mode, cval, origin, 0,
+                                       axes=axes)
+
+
+def grey_opening(input, size=None, footprint=None, structure=None,
+                 output=None, mode="reflect", cval=0.0, origin=0, *,
+                 axes=None):
+    """
+    Multidimensional grayscale opening.
+
+    A grayscale opening consists in the succession of a grayscale erosion,
+    and a grayscale dilation.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which the grayscale opening is to be computed.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the grayscale
+        opening. Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the grayscale opening.
+    structure : array of ints, optional
+        Structuring element used for the grayscale opening. `structure`
+        may be a non-flat structuring element. The `structure` array applies
+        offsets to the pixels in a neighborhood (the offset is additive during
+        dilation and subtractive during erosion).
+    output : array, optional
+        An array used for storing the output of the opening may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    grey_opening : ndarray
+        Result of the grayscale opening of `input` with `structure`.
+
+    See Also
+    --------
+    binary_opening, grey_dilation, grey_erosion, grey_closing
+    generate_binary_structure
+
+    Notes
+    -----
+    The action of a grayscale opening with a flat structuring element amounts
+    to smoothen high local maxima, whereas binary opening erases small objects.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.arange(36).reshape((6,6))
+    >>> a[3, 3] = 50
+    >>> a
+    array([[ 0,  1,  2,  3,  4,  5],
+           [ 6,  7,  8,  9, 10, 11],
+           [12, 13, 14, 15, 16, 17],
+           [18, 19, 20, 50, 22, 23],
+           [24, 25, 26, 27, 28, 29],
+           [30, 31, 32, 33, 34, 35]])
+    >>> ndimage.grey_opening(a, size=(3,3))
+    array([[ 0,  1,  2,  3,  4,  4],
+           [ 6,  7,  8,  9, 10, 10],
+           [12, 13, 14, 15, 16, 16],
+           [18, 19, 20, 22, 22, 22],
+           [24, 25, 26, 27, 28, 28],
+           [24, 25, 26, 27, 28, 28]])
+    >>> # Note that the local maximum a[3,3] has disappeared
+
+    """
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    tmp = grey_erosion(input, size, footprint, structure, None, mode,
+                       cval, origin, axes=axes)
+    return grey_dilation(tmp, size, footprint, structure, output, mode,
+                         cval, origin, axes=axes)
+
+
+def grey_closing(input, size=None, footprint=None, structure=None,
+                 output=None, mode="reflect", cval=0.0, origin=0, *,
+                 axes=None):
+    """
+    Multidimensional grayscale closing.
+
+    A grayscale closing consists in the succession of a grayscale dilation,
+    and a grayscale erosion.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which the grayscale closing is to be computed.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the grayscale
+        closing. Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the grayscale closing.
+    structure : array of ints, optional
+        Structuring element used for the grayscale closing. `structure`
+        may be a non-flat structuring element. The `structure` array applies
+        offsets to the pixels in a neighborhood (the offset is additive during
+        dilation and subtractive during erosion)
+    output : array, optional
+        An array used for storing the output of the closing may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    grey_closing : ndarray
+        Result of the grayscale closing of `input` with `structure`.
+
+    See Also
+    --------
+    binary_closing, grey_dilation, grey_erosion, grey_opening,
+    generate_binary_structure
+
+    Notes
+    -----
+    The action of a grayscale closing with a flat structuring element amounts
+    to smoothen deep local minima, whereas binary closing fills small holes.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.arange(36).reshape((6,6))
+    >>> a[3,3] = 0
+    >>> a
+    array([[ 0,  1,  2,  3,  4,  5],
+           [ 6,  7,  8,  9, 10, 11],
+           [12, 13, 14, 15, 16, 17],
+           [18, 19, 20,  0, 22, 23],
+           [24, 25, 26, 27, 28, 29],
+           [30, 31, 32, 33, 34, 35]])
+    >>> ndimage.grey_closing(a, size=(3,3))
+    array([[ 7,  7,  8,  9, 10, 11],
+           [ 7,  7,  8,  9, 10, 11],
+           [13, 13, 14, 15, 16, 17],
+           [19, 19, 20, 20, 22, 23],
+           [25, 25, 26, 27, 28, 29],
+           [31, 31, 32, 33, 34, 35]])
+    >>> # Note that the local minimum a[3,3] has disappeared
+
+    """
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    tmp = grey_dilation(input, size, footprint, structure, None, mode,
+                        cval, origin, axes=axes)
+    return grey_erosion(tmp, size, footprint, structure, output, mode,
+                        cval, origin, axes=axes)
+
+
+def morphological_gradient(input, size=None, footprint=None, structure=None,
+                           output=None, mode="reflect", cval=0.0, origin=0, *,
+                           axes=None):
+    """
+    Multidimensional morphological gradient.
+
+    The morphological gradient is calculated as the difference between a
+    dilation and an erosion of the input with a given structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which to compute the morphlogical gradient.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the mathematical
+        morphology operations. Optional if `footprint` or `structure` is
+        provided. A larger `size` yields a more blurred gradient.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the morphology operations. Larger footprints
+        give a more blurred morphological gradient.
+    structure : array of ints, optional
+        Structuring element used for the morphology operations. `structure` may
+        be a non-flat structuring element. The `structure` array applies
+        offsets to the pixels in a neighborhood (the offset is additive during
+        dilation and subtractive during erosion)
+    output : array, optional
+        An array used for storing the output of the morphological gradient
+        may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    morphological_gradient : ndarray
+        Morphological gradient of `input`.
+
+    See Also
+    --------
+    grey_dilation, grey_erosion, gaussian_gradient_magnitude
+
+    Notes
+    -----
+    For a flat structuring element, the morphological gradient
+    computed at a given point corresponds to the maximal difference
+    between elements of the input among the elements covered by the
+    structuring element centered on the point.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[2:5, 2:5] = 1
+    >>> ndimage.morphological_gradient(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 0, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> # The morphological gradient is computed as the difference
+    >>> # between a dilation and an erosion
+    >>> ndimage.grey_dilation(a, size=(3,3)) -\\
+    ...  ndimage.grey_erosion(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 0, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[2:5, 2:5] = 1
+    >>> a[4,4] = 2; a[2,3] = 3
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 3, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.morphological_gradient(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 2, 3, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    tmp = grey_dilation(input, size, footprint, structure, None, mode,
+                        cval, origin, axes=axes)
+    if isinstance(output, np.ndarray):
+        grey_erosion(input, size, footprint, structure, output, mode,
+                     cval, origin, axes=axes)
+        return np.subtract(tmp, output, output)
+    else:
+        return (tmp - grey_erosion(input, size, footprint, structure,
+                                   None, mode, cval, origin, axes=axes))
+
+
+def morphological_laplace(input, size=None, footprint=None, structure=None,
+                          output=None, mode="reflect", cval=0.0, origin=0, *,
+                          axes=None):
+    """
+    Multidimensional morphological laplace.
+
+    Parameters
+    ----------
+    input : array_like
+        Input.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the mathematical
+        morphology operations. Optional if `footprint` or `structure` is
+        provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the morphology operations.
+    structure : array of ints, optional
+        Structuring element used for the morphology operations. `structure` may
+        be a non-flat structuring element. The `structure` array applies
+        offsets to the pixels in a neighborhood (the offset is additive during
+        dilation and subtractive during erosion)
+    output : ndarray, optional
+        An output array can optionally be provided.
+    mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+        The mode parameter determines how the array borders are handled.
+        For 'constant' mode, values beyond borders are set to be `cval`.
+        Default is 'reflect'.
+    cval : scalar, optional
+        Value to fill past edges of input if mode is 'constant'.
+        Default is 0.0
+    origin : origin, optional
+        The origin parameter controls the placement of the filter.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    morphological_laplace : ndarray
+        Output
+
+    """
+    tmp1 = grey_dilation(input, size, footprint, structure, None, mode,
+                         cval, origin, axes=axes)
+    if isinstance(output, np.ndarray):
+        grey_erosion(input, size, footprint, structure, output, mode,
+                     cval, origin, axes=axes)
+        np.add(tmp1, output, output)
+        np.subtract(output, input, output)
+        return np.subtract(output, input, output)
+    else:
+        tmp2 = grey_erosion(input, size, footprint, structure, None, mode,
+                            cval, origin, axes=axes)
+        np.add(tmp1, tmp2, tmp2)
+        np.subtract(tmp2, input, tmp2)
+        np.subtract(tmp2, input, tmp2)
+        return tmp2
+
+
+def white_tophat(input, size=None, footprint=None, structure=None,
+                 output=None, mode="reflect", cval=0.0, origin=0, *,
+                 axes=None):
+    """
+    Multidimensional white tophat filter.
+
+    Parameters
+    ----------
+    input : array_like
+        Input.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the filter.
+        Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of elements of a flat structuring element
+        used for the white tophat filter.
+    structure : array of ints, optional
+        Structuring element used for the filter. `structure` may be a non-flat
+        structuring element. The `structure` array applies offsets to the
+        pixels in a neighborhood (the offset is additive during dilation and
+        subtractive during erosion)
+    output : array, optional
+        An array used for storing the output of the filter may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'.
+        Default is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default is 0.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    output : ndarray
+        Result of the filter of `input` with `structure`.
+
+    See Also
+    --------
+    black_tophat
+
+    Examples
+    --------
+    Subtract gray background from a bright peak.
+
+    >>> from scipy.ndimage import generate_binary_structure, white_tophat
+    >>> import numpy as np
+    >>> square = generate_binary_structure(rank=2, connectivity=3)
+    >>> bright_on_gray = np.array([[2, 3, 3, 3, 2],
+    ...                            [3, 4, 5, 4, 3],
+    ...                            [3, 5, 9, 5, 3],
+    ...                            [3, 4, 5, 4, 3],
+    ...                            [2, 3, 3, 3, 2]])
+    >>> white_tophat(input=bright_on_gray, structure=square)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 1, 5, 1, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    tmp = grey_erosion(input, size, footprint, structure, None, mode,
+                       cval, origin, axes=axes)
+    tmp = grey_dilation(tmp, size, footprint, structure, output, mode,
+                        cval, origin, axes=axes)
+    if tmp is None:
+        tmp = output
+
+    if input.dtype == np.bool_ and tmp.dtype == np.bool_:
+        np.bitwise_xor(input, tmp, out=tmp)
+    else:
+        np.subtract(input, tmp, out=tmp)
+    return tmp
+
+
+def black_tophat(input, size=None, footprint=None, structure=None, output=None,
+                 mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """
+    Multidimensional black tophat filter.
+
+    Parameters
+    ----------
+    input : array_like
+        Input.
+    size : tuple of ints, optional
+        Shape of a flat and full structuring element used for the filter.
+        Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the black tophat filter.
+    structure : array of ints, optional
+        Structuring element used for the filter. `structure` may be a non-flat
+        structuring element. The `structure` array applies offsets to the
+        pixels in a neighborhood (the offset is additive during dilation and
+        subtractive during erosion)
+    output : array, optional
+        An array used for storing the output of the filter may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    black_tophat : ndarray
+        Result of the filter of `input` with `structure`.
+
+    See Also
+    --------
+    white_tophat, grey_opening, grey_closing
+
+    Examples
+    --------
+    Change dark peak to bright peak and subtract background.
+
+    >>> from scipy.ndimage import generate_binary_structure, black_tophat
+    >>> import numpy as np
+    >>> square = generate_binary_structure(rank=2, connectivity=3)
+    >>> dark_on_gray = np.array([[7, 6, 6, 6, 7],
+    ...                          [6, 5, 4, 5, 6],
+    ...                          [6, 4, 0, 4, 6],
+    ...                          [6, 5, 4, 5, 6],
+    ...                          [7, 6, 6, 6, 7]])
+    >>> black_tophat(input=dark_on_gray, structure=square)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 1, 5, 1, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    tmp = grey_dilation(input, size, footprint, structure, None, mode,
+                        cval, origin, axes=axes)
+    tmp = grey_erosion(tmp, size, footprint, structure, output, mode,
+                       cval, origin, axes=axes)
+    if tmp is None:
+        tmp = output
+
+    if input.dtype == np.bool_ and tmp.dtype == np.bool_:
+        np.bitwise_xor(tmp, input, out=tmp)
+    else:
+        np.subtract(tmp, input, out=tmp)
+    return tmp
+
+
+def distance_transform_bf(input, metric="euclidean", sampling=None,
+                          return_distances=True, return_indices=False,
+                          distances=None, indices=None):
+    """
+    Distance transform function by a brute force algorithm.
+
+    This function calculates the distance transform of the `input`, by
+    replacing each foreground (non-zero) element, with its
+    shortest distance to the background (any zero-valued element).
+
+    In addition to the distance transform, the feature transform can
+    be calculated. In this case the index of the closest background
+    element to each foreground element is returned in a separate array.
+
+    Parameters
+    ----------
+    input : array_like
+        Input
+    metric : {'euclidean', 'taxicab', 'chessboard'}, optional
+        'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
+        The default is 'euclidean'.
+    sampling : float, or sequence of float, optional
+        This parameter is only used when `metric` is 'euclidean'.
+        Spacing of elements along each dimension. If a sequence, must be of
+        length equal to the input rank; if a single number, this is used for
+        all axes. If not specified, a grid spacing of unity is implied.
+    return_distances : bool, optional
+        Whether to calculate the distance transform.
+        Default is True.
+    return_indices : bool, optional
+        Whether to calculate the feature transform.
+        Default is False.
+    distances : ndarray, optional
+        An output array to store the calculated distance transform, instead of
+        returning it.
+        `return_distances` must be True.
+        It must be the same shape as `input`, and of type float64 if `metric`
+        is 'euclidean', uint32 otherwise.
+    indices : int32 ndarray, optional
+        An output array to store the calculated feature transform, instead of
+        returning it.
+        `return_indicies` must be True.
+        Its shape must be ``(input.ndim,) + input.shape``.
+
+    Returns
+    -------
+    distances : ndarray, optional
+        The calculated distance transform. Returned only when
+        `return_distances` is True and `distances` is not supplied.
+        It will have the same shape as the input array.
+    indices : int32 ndarray, optional
+        The calculated feature transform. It has an input-shaped array for each
+        dimension of the input. See distance_transform_edt documentation for an
+        example.
+        Returned only when `return_indices` is True and `indices` is not
+        supplied.
+
+    See Also
+    --------
+    distance_transform_cdt : Faster distance transform for taxicab and
+                             chessboard metrics
+    distance_transform_edt : Faster distance transform for euclidean metric
+
+    Notes
+    -----
+    This function employs a slow brute force algorithm. See also the
+    function `distance_transform_cdt` for more efficient taxicab [1]_ and
+    chessboard algorithms [2]_.
+
+    References
+    ----------
+    .. [1] Taxicab distance. Wikipedia, 2023.
+           https://en.wikipedia.org/wiki/Taxicab_geometry
+    .. [2] Chessboard distance. Wikipedia, 2023.
+           https://en.wikipedia.org/wiki/Chebyshev_distance
+
+    Examples
+    --------
+    Import the necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.ndimage import distance_transform_bf
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.axes_grid1 import ImageGrid
+
+    First, we create a toy binary image.
+
+    >>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
+    ...     # fill circular area with 1
+    ...     xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
+    ...     circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
+    ...     circle_shape = np.sqrt(circle) < radius
+    ...     image[circle_shape] = fillvalue
+    ...     return image
+    >>> image = np.zeros((100, 100), dtype=np.uint8)
+    >>> image[35:65, 20:80] = 1
+    >>> image = add_circle(28, 65, 10, image)
+    >>> image = add_circle(37, 30, 10, image)
+    >>> image = add_circle(70, 45, 20, image)
+    >>> image = add_circle(45, 80, 10, image)
+
+    Next, we set up the figure.
+
+    >>> fig = plt.figure(figsize=(8, 8))  # set up the figure structure
+    >>> grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=(0.4, 0.3),
+    ...                  label_mode="1", share_all=True,
+    ...                  cbar_location="right", cbar_mode="each",
+    ...                  cbar_size="7%", cbar_pad="2%")
+    >>> for ax in grid:
+    ...     ax.axis('off')  # remove axes from images
+
+    The top left image is the original binary image.
+
+    >>> binary_image = grid[0].imshow(image, cmap='gray')
+    >>> cbar_binary_image = grid.cbar_axes[0].colorbar(binary_image)
+    >>> cbar_binary_image.set_ticks([0, 1])
+    >>> grid[0].set_title("Binary image: foreground in white")
+
+    The distance transform calculates the distance between foreground pixels
+    and the image background according to a distance metric. Available metrics
+    in `distance_transform_bf` are: ``euclidean`` (default), ``taxicab``
+    and ``chessboard``. The top right image contains the distance transform
+    based on the ``euclidean`` metric.
+
+    >>> distance_transform_euclidean = distance_transform_bf(image)
+    >>> euclidean_transform = grid[1].imshow(distance_transform_euclidean,
+    ...                                      cmap='gray')
+    >>> cbar_euclidean = grid.cbar_axes[1].colorbar(euclidean_transform)
+    >>> colorbar_ticks = [0, 10, 20]
+    >>> cbar_euclidean.set_ticks(colorbar_ticks)
+    >>> grid[1].set_title("Euclidean distance")
+
+    The lower left image contains the distance transform using the ``taxicab``
+    metric.
+
+    >>> distance_transform_taxicab = distance_transform_bf(image,
+    ...                                                    metric='taxicab')
+    >>> taxicab_transformation = grid[2].imshow(distance_transform_taxicab,
+    ...                                         cmap='gray')
+    >>> cbar_taxicab = grid.cbar_axes[2].colorbar(taxicab_transformation)
+    >>> cbar_taxicab.set_ticks(colorbar_ticks)
+    >>> grid[2].set_title("Taxicab distance")
+
+    Finally, the lower right image contains the distance transform using the
+    ``chessboard`` metric.
+
+    >>> distance_transform_cb = distance_transform_bf(image,
+    ...                                               metric='chessboard')
+    >>> chessboard_transformation = grid[3].imshow(distance_transform_cb,
+    ...                                            cmap='gray')
+    >>> cbar_taxicab = grid.cbar_axes[3].colorbar(chessboard_transformation)
+    >>> cbar_taxicab.set_ticks(colorbar_ticks)
+    >>> grid[3].set_title("Chessboard distance")
+    >>> plt.show()
+
+    """
+    ft_inplace = isinstance(indices, np.ndarray)
+    dt_inplace = isinstance(distances, np.ndarray)
+    _distance_tranform_arg_check(
+        dt_inplace, ft_inplace, return_distances, return_indices
+    )
+
+    tmp1 = np.asarray(input) != 0
+    struct = generate_binary_structure(tmp1.ndim, tmp1.ndim)
+    tmp2 = binary_dilation(tmp1, struct)
+    tmp2 = np.logical_xor(tmp1, tmp2)
+    tmp1 = tmp1.astype(np.int8) - tmp2.astype(np.int8)
+    metric = metric.lower()
+    if metric == 'euclidean':
+        metric = 1
+    elif metric in ['taxicab', 'cityblock', 'manhattan']:
+        metric = 2
+    elif metric == 'chessboard':
+        metric = 3
+    else:
+        raise RuntimeError('distance metric not supported')
+    if sampling is not None:
+        sampling = _ni_support._normalize_sequence(sampling, tmp1.ndim)
+        sampling = np.asarray(sampling, dtype=np.float64)
+        if not sampling.flags.contiguous:
+            sampling = sampling.copy()
+    if return_indices:
+        ft = np.zeros(tmp1.shape, dtype=np.int32)
+    else:
+        ft = None
+    if return_distances:
+        if distances is None:
+            if metric == 1:
+                dt = np.zeros(tmp1.shape, dtype=np.float64)
+            else:
+                dt = np.zeros(tmp1.shape, dtype=np.uint32)
+        else:
+            if distances.shape != tmp1.shape:
+                raise RuntimeError('distances array has wrong shape')
+            if metric == 1:
+                if distances.dtype.type != np.float64:
+                    raise RuntimeError('distances array must be float64')
+            else:
+                if distances.dtype.type != np.uint32:
+                    raise RuntimeError('distances array must be uint32')
+            dt = distances
+    else:
+        dt = None
+
+    _nd_image.distance_transform_bf(tmp1, metric, sampling, dt, ft)
+    if return_indices:
+        if isinstance(indices, np.ndarray):
+            if indices.dtype.type != np.int32:
+                raise RuntimeError('indices array must be int32')
+            if indices.shape != (tmp1.ndim,) + tmp1.shape:
+                raise RuntimeError('indices array has wrong shape')
+            tmp2 = indices
+        else:
+            tmp2 = np.indices(tmp1.shape, dtype=np.int32)
+        ft = np.ravel(ft)
+        for ii in range(tmp2.shape[0]):
+            rtmp = np.ravel(tmp2[ii, ...])[ft]
+            rtmp.shape = tmp1.shape
+            tmp2[ii, ...] = rtmp
+        ft = tmp2
+
+    # construct and return the result
+    result = []
+    if return_distances and not dt_inplace:
+        result.append(dt)
+    if return_indices and not ft_inplace:
+        result.append(ft)
+
+    if len(result) == 2:
+        return tuple(result)
+    elif len(result) == 1:
+        return result[0]
+    else:
+        return None
+
+
+def distance_transform_cdt(input, metric='chessboard', return_distances=True,
+                           return_indices=False, distances=None, indices=None):
+    """
+    Distance transform for chamfer type of transforms.
+
+    This function calculates the distance transform of the `input`, by
+    replacing each foreground (non-zero) element, with its
+    shortest distance to the background (any zero-valued element).
+
+    In addition to the distance transform, the feature transform can
+    be calculated. In this case the index of the closest background
+    element to each foreground element is returned in a separate array.
+
+    Parameters
+    ----------
+    input : array_like
+        Input. Values of 0 are treated as background.
+    metric : {'chessboard', 'taxicab'} or array_like, optional
+        The `metric` determines the type of chamfering that is done. If the
+        `metric` is equal to 'taxicab' a structure is generated using
+        `generate_binary_structure` with a squared distance equal to 1. If
+        the `metric` is equal to 'chessboard', a `metric` is generated
+        using `generate_binary_structure` with a squared distance equal to
+        the dimensionality of the array. These choices correspond to the
+        common interpretations of the 'taxicab' and the 'chessboard'
+        distance metrics in two dimensions.
+        A custom metric may be provided, in the form of a matrix where
+        each dimension has a length of three.
+        'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
+        The default is 'chessboard'.
+    return_distances : bool, optional
+        Whether to calculate the distance transform.
+        Default is True.
+    return_indices : bool, optional
+        Whether to calculate the feature transform.
+        Default is False.
+    distances : int32 ndarray, optional
+        An output array to store the calculated distance transform, instead of
+        returning it.
+        `return_distances` must be True.
+        It must be the same shape as `input`.
+    indices : int32 ndarray, optional
+        An output array to store the calculated feature transform, instead of
+        returning it.
+        `return_indicies` must be True.
+        Its shape must be ``(input.ndim,) + input.shape``.
+
+    Returns
+    -------
+    distances : int32 ndarray, optional
+        The calculated distance transform. Returned only when
+        `return_distances` is True, and `distances` is not supplied.
+        It will have the same shape as the input array.
+    indices : int32 ndarray, optional
+        The calculated feature transform. It has an input-shaped array for each
+        dimension of the input. See distance_transform_edt documentation for an
+        example.
+        Returned only when `return_indices` is True, and `indices` is not
+        supplied.
+
+    See Also
+    --------
+    distance_transform_edt : Fast distance transform for euclidean metric
+    distance_transform_bf : Distance transform for different metrics using
+                            a slower brute force algorithm
+
+    Examples
+    --------
+    Import the necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.ndimage import distance_transform_cdt
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.axes_grid1 import ImageGrid
+
+    First, we create a toy binary image.
+
+    >>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
+    ...     # fill circular area with 1
+    ...     xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
+    ...     circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
+    ...     circle_shape = np.sqrt(circle) < radius
+    ...     image[circle_shape] = fillvalue
+    ...     return image
+    >>> image = np.zeros((100, 100), dtype=np.uint8)
+    >>> image[35:65, 20:80] = 1
+    >>> image = add_circle(28, 65, 10, image)
+    >>> image = add_circle(37, 30, 10, image)
+    >>> image = add_circle(70, 45, 20, image)
+    >>> image = add_circle(45, 80, 10, image)
+
+    Next, we set up the figure.
+
+    >>> fig = plt.figure(figsize=(5, 15))
+    >>> grid = ImageGrid(fig, 111, nrows_ncols=(3, 1), axes_pad=(0.5, 0.3),
+    ...                  label_mode="1", share_all=True,
+    ...                  cbar_location="right", cbar_mode="each",
+    ...                  cbar_size="7%", cbar_pad="2%")
+    >>> for ax in grid:
+    ...     ax.axis('off')
+    >>> top, middle, bottom = grid
+    >>> colorbar_ticks = [0, 10, 20]
+
+    The top image contains the original binary image.
+
+    >>> binary_image = top.imshow(image, cmap='gray')
+    >>> cbar_binary_image = top.cax.colorbar(binary_image)
+    >>> cbar_binary_image.set_ticks([0, 1])
+    >>> top.set_title("Binary image: foreground in white")
+
+    The middle image contains the distance transform using the ``taxicab``
+    metric.
+
+    >>> distance_taxicab = distance_transform_cdt(image, metric="taxicab")
+    >>> taxicab_transform = middle.imshow(distance_taxicab, cmap='gray')
+    >>> cbar_taxicab = middle.cax.colorbar(taxicab_transform)
+    >>> cbar_taxicab.set_ticks(colorbar_ticks)
+    >>> middle.set_title("Taxicab metric")
+
+    The bottom image contains the distance transform using the ``chessboard``
+    metric.
+
+    >>> distance_chessboard = distance_transform_cdt(image,
+    ...                                              metric="chessboard")
+    >>> chessboard_transform = bottom.imshow(distance_chessboard, cmap='gray')
+    >>> cbar_chessboard = bottom.cax.colorbar(chessboard_transform)
+    >>> cbar_chessboard.set_ticks(colorbar_ticks)
+    >>> bottom.set_title("Chessboard metric")
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    ft_inplace = isinstance(indices, np.ndarray)
+    dt_inplace = isinstance(distances, np.ndarray)
+    _distance_tranform_arg_check(
+        dt_inplace, ft_inplace, return_distances, return_indices
+    )
+    input = np.asarray(input)
+    if isinstance(metric, str):
+        if metric in ['taxicab', 'cityblock', 'manhattan']:
+            rank = input.ndim
+            metric = generate_binary_structure(rank, 1)
+        elif metric == 'chessboard':
+            rank = input.ndim
+            metric = generate_binary_structure(rank, rank)
+        else:
+            raise ValueError('invalid metric provided')
+    else:
+        try:
+            metric = np.asarray(metric)
+        except Exception as e:
+            raise ValueError('invalid metric provided') from e
+        for s in metric.shape:
+            if s != 3:
+                raise ValueError('metric sizes must be equal to 3')
+
+    if not metric.flags.contiguous:
+        metric = metric.copy()
+    if dt_inplace:
+        if distances.dtype.type != np.int32:
+            raise ValueError('distances must be of int32 type')
+        if distances.shape != input.shape:
+            raise ValueError('distances has wrong shape')
+        dt = distances
+        dt[...] = np.where(input, -1, 0).astype(np.int32)
+    else:
+        dt = np.where(input, -1, 0).astype(np.int32)
+
+    rank = dt.ndim
+    if return_indices:
+        ft = np.arange(dt.size, dtype=np.int32)
+        ft.shape = dt.shape
+    else:
+        ft = None
+
+    _nd_image.distance_transform_op(metric, dt, ft)
+    dt = dt[tuple([slice(None, None, -1)] * rank)]
+    if return_indices:
+        ft = ft[tuple([slice(None, None, -1)] * rank)]
+    _nd_image.distance_transform_op(metric, dt, ft)
+    dt = dt[tuple([slice(None, None, -1)] * rank)]
+    if return_indices:
+        ft = ft[tuple([slice(None, None, -1)] * rank)]
+        ft = np.ravel(ft)
+        if ft_inplace:
+            if indices.dtype.type != np.int32:
+                raise ValueError('indices array must be int32')
+            if indices.shape != (dt.ndim,) + dt.shape:
+                raise ValueError('indices array has wrong shape')
+            tmp = indices
+        else:
+            tmp = np.indices(dt.shape, dtype=np.int32)
+        for ii in range(tmp.shape[0]):
+            rtmp = np.ravel(tmp[ii, ...])[ft]
+            rtmp.shape = dt.shape
+            tmp[ii, ...] = rtmp
+        ft = tmp
+
+    # construct and return the result
+    result = []
+    if return_distances and not dt_inplace:
+        result.append(dt)
+    if return_indices and not ft_inplace:
+        result.append(ft)
+
+    if len(result) == 2:
+        return tuple(result)
+    elif len(result) == 1:
+        return result[0]
+    else:
+        return None
+
+
+def distance_transform_edt(input, sampling=None, return_distances=True,
+                           return_indices=False, distances=None, indices=None):
+    """
+    Exact Euclidean distance transform.
+
+    This function calculates the distance transform of the `input`, by
+    replacing each foreground (non-zero) element, with its
+    shortest distance to the background (any zero-valued element).
+
+    In addition to the distance transform, the feature transform can
+    be calculated. In this case the index of the closest background
+    element to each foreground element is returned in a separate array.
+
+    Parameters
+    ----------
+    input : array_like
+        Input data to transform. Can be any type but will be converted
+        into binary: 1 wherever input equates to True, 0 elsewhere.
+    sampling : float, or sequence of float, optional
+        Spacing of elements along each dimension. If a sequence, must be of
+        length equal to the input rank; if a single number, this is used for
+        all axes. If not specified, a grid spacing of unity is implied.
+    return_distances : bool, optional
+        Whether to calculate the distance transform.
+        Default is True.
+    return_indices : bool, optional
+        Whether to calculate the feature transform.
+        Default is False.
+    distances : float64 ndarray, optional
+        An output array to store the calculated distance transform, instead of
+        returning it.
+        `return_distances` must be True.
+        It must be the same shape as `input`.
+    indices : int32 ndarray, optional
+        An output array to store the calculated feature transform, instead of
+        returning it.
+        `return_indicies` must be True.
+        Its shape must be ``(input.ndim,) + input.shape``.
+
+    Returns
+    -------
+    distances : float64 ndarray, optional
+        The calculated distance transform. Returned only when
+        `return_distances` is True and `distances` is not supplied.
+        It will have the same shape as the input array.
+    indices : int32 ndarray, optional
+        The calculated feature transform. It has an input-shaped array for each
+        dimension of the input. See example below.
+        Returned only when `return_indices` is True and `indices` is not
+        supplied.
+
+    Notes
+    -----
+    The Euclidean distance transform gives values of the Euclidean
+    distance::
+
+                    n
+      y_i = sqrt(sum (x[i]-b[i])**2)
+                    i
+
+    where b[i] is the background point (value 0) with the smallest
+    Euclidean distance to input points x[i], and n is the
+    number of dimensions.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.array(([0,1,1,1,1],
+    ...               [0,0,1,1,1],
+    ...               [0,1,1,1,1],
+    ...               [0,1,1,1,0],
+    ...               [0,1,1,0,0]))
+    >>> ndimage.distance_transform_edt(a)
+    array([[ 0.    ,  1.    ,  1.4142,  2.2361,  3.    ],
+           [ 0.    ,  0.    ,  1.    ,  2.    ,  2.    ],
+           [ 0.    ,  1.    ,  1.4142,  1.4142,  1.    ],
+           [ 0.    ,  1.    ,  1.4142,  1.    ,  0.    ],
+           [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])
+
+    With a sampling of 2 units along x, 1 along y:
+
+    >>> ndimage.distance_transform_edt(a, sampling=[2,1])
+    array([[ 0.    ,  1.    ,  2.    ,  2.8284,  3.6056],
+           [ 0.    ,  0.    ,  1.    ,  2.    ,  3.    ],
+           [ 0.    ,  1.    ,  2.    ,  2.2361,  2.    ],
+           [ 0.    ,  1.    ,  2.    ,  1.    ,  0.    ],
+           [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])
+
+    Asking for indices as well:
+
+    >>> edt, inds = ndimage.distance_transform_edt(a, return_indices=True)
+    >>> inds
+    array([[[0, 0, 1, 1, 3],
+            [1, 1, 1, 1, 3],
+            [2, 2, 1, 3, 3],
+            [3, 3, 4, 4, 3],
+            [4, 4, 4, 4, 4]],
+           [[0, 0, 1, 1, 4],
+            [0, 1, 1, 1, 4],
+            [0, 0, 1, 4, 4],
+            [0, 0, 3, 3, 4],
+            [0, 0, 3, 3, 4]]], dtype=int32)
+
+    With arrays provided for inplace outputs:
+
+    >>> indices = np.zeros(((np.ndim(a),) + a.shape), dtype=np.int32)
+    >>> ndimage.distance_transform_edt(a, return_indices=True, indices=indices)
+    array([[ 0.    ,  1.    ,  1.4142,  2.2361,  3.    ],
+           [ 0.    ,  0.    ,  1.    ,  2.    ,  2.    ],
+           [ 0.    ,  1.    ,  1.4142,  1.4142,  1.    ],
+           [ 0.    ,  1.    ,  1.4142,  1.    ,  0.    ],
+           [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])
+    >>> indices
+    array([[[0, 0, 1, 1, 3],
+            [1, 1, 1, 1, 3],
+            [2, 2, 1, 3, 3],
+            [3, 3, 4, 4, 3],
+            [4, 4, 4, 4, 4]],
+           [[0, 0, 1, 1, 4],
+            [0, 1, 1, 1, 4],
+            [0, 0, 1, 4, 4],
+            [0, 0, 3, 3, 4],
+            [0, 0, 3, 3, 4]]], dtype=int32)
+
+    """
+    ft_inplace = isinstance(indices, np.ndarray)
+    dt_inplace = isinstance(distances, np.ndarray)
+    _distance_tranform_arg_check(
+        dt_inplace, ft_inplace, return_distances, return_indices
+    )
+
+    # calculate the feature transform
+    input = np.atleast_1d(np.where(input, 1, 0).astype(np.int8))
+    if sampling is not None:
+        sampling = _ni_support._normalize_sequence(sampling, input.ndim)
+        sampling = np.asarray(sampling, dtype=np.float64)
+        if not sampling.flags.contiguous:
+            sampling = sampling.copy()
+
+    if ft_inplace:
+        ft = indices
+        if ft.shape != (input.ndim,) + input.shape:
+            raise RuntimeError('indices array has wrong shape')
+        if ft.dtype.type != np.int32:
+            raise RuntimeError('indices array must be int32')
+    else:
+        ft = np.zeros((input.ndim,) + input.shape, dtype=np.int32)
+
+    _nd_image.euclidean_feature_transform(input, sampling, ft)
+    # if requested, calculate the distance transform
+    if return_distances:
+        dt = ft - np.indices(input.shape, dtype=ft.dtype)
+        dt = dt.astype(np.float64)
+        if sampling is not None:
+            for ii in range(len(sampling)):
+                dt[ii, ...] *= sampling[ii]
+        np.multiply(dt, dt, dt)
+        if dt_inplace:
+            dt = np.add.reduce(dt, axis=0)
+            if distances.shape != dt.shape:
+                raise RuntimeError('distances array has wrong shape')
+            if distances.dtype.type != np.float64:
+                raise RuntimeError('distances array must be float64')
+            np.sqrt(dt, distances)
+        else:
+            dt = np.add.reduce(dt, axis=0)
+            dt = np.sqrt(dt)
+
+    # construct and return the result
+    result = []
+    if return_distances and not dt_inplace:
+        result.append(dt)
+    if return_indices and not ft_inplace:
+        result.append(ft)
+
+    if len(result) == 2:
+        return tuple(result)
+    elif len(result) == 1:
+        return result[0]
+    else:
+        return None
+
+
+def _distance_tranform_arg_check(distances_out, indices_out,
+                                 return_distances, return_indices):
+    """Raise a RuntimeError if the arguments are invalid"""
+    error_msgs = []
+    if (not return_distances) and (not return_indices):
+        error_msgs.append(
+            'at least one of return_distances/return_indices must be True')
+    if distances_out and not return_distances:
+        error_msgs.append(
+            'return_distances must be True if distances is supplied'
+        )
+    if indices_out and not return_indices:
+        error_msgs.append('return_indices must be True if indices is supplied')
+    if error_msgs:
+        raise RuntimeError(', '.join(error_msgs))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1673391726a4070af4814d04be16e29e01d9f29b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py
@@ -0,0 +1,16 @@
+"""This is the 'bare' ndimage API.
+
+This --- private! --- module only collects implementations of public ndimage API
+for _support_alternative_backends.
+The latter --- also private! --- module adds delegation to CuPy etc and
+re-exports decorated names to __init__.py
+"""
+
+from ._filters import *    # noqa: F403
+from ._fourier import *   # noqa: F403
+from ._interpolation import *   # noqa: F403
+from ._measurements import *   # noqa: F403
+from ._morphology import *   # noqa: F403
+
+# '@' due to pytest bug, scipy/scipy#22236
+__all__ = [s for s in dir() if not s.startswith(('_', '@'))]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c0d977500574b73f168296645fb36d10c1320de
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py
@@ -0,0 +1,210 @@
+"""Docstring components common to several ndimage functions."""
+from typing import Final
+
+from scipy._lib import doccer
+
+__all__ = ['docfiller']
+
+
+_input_doc = (
+"""input : array_like
+    The input array.""")
+_axis_doc = (
+"""axis : int, optional
+    The axis of `input` along which to calculate. Default is -1.""")
+_output_doc = (
+"""output : array or dtype, optional
+    The array in which to place the output, or the dtype of the
+    returned array. By default an array of the same dtype as input
+    will be created.""")
+_size_foot_doc = (
+"""size : scalar or tuple, optional
+    See footprint, below. Ignored if footprint is given.
+footprint : array, optional
+    Either `size` or `footprint` must be defined. `size` gives
+    the shape that is taken from the input array, at every element
+    position, to define the input to the filter function.
+    `footprint` is a boolean array that specifies (implicitly) a
+    shape, but also which of the elements within this shape will get
+    passed to the filter function. Thus ``size=(n,m)`` is equivalent
+    to ``footprint=np.ones((n,m))``.  We adjust `size` to the number
+    of dimensions of the input array, so that, if the input array is
+    shape (10,10,10), and `size` is 2, then the actual size used is
+    (2,2,2). When `footprint` is given, `size` is ignored.""")
+_mode_reflect_doc = (
+"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+    The `mode` parameter determines how the input array is extended
+    beyond its boundaries. Default is 'reflect'. Behavior for each valid
+    value is as follows:
+
+    'reflect' (`d c b a | a b c d | d c b a`)
+        The input is extended by reflecting about the edge of the last
+        pixel. This mode is also sometimes referred to as half-sample
+        symmetric.
+
+    'constant' (`k k k k | a b c d | k k k k`)
+        The input is extended by filling all values beyond the edge with
+        the same constant value, defined by the `cval` parameter.
+
+    'nearest' (`a a a a | a b c d | d d d d`)
+        The input is extended by replicating the last pixel.
+
+    'mirror' (`d c b | a b c d | c b a`)
+        The input is extended by reflecting about the center of the last
+        pixel. This mode is also sometimes referred to as whole-sample
+        symmetric.
+
+    'wrap' (`a b c d | a b c d | a b c d`)
+        The input is extended by wrapping around to the opposite edge.
+
+    For consistency with the interpolation functions, the following mode
+    names can also be used:
+
+    'grid-mirror'
+        This is a synonym for 'reflect'.
+
+    'grid-constant'
+        This is a synonym for 'constant'.
+
+    'grid-wrap'
+        This is a synonym for 'wrap'.""")
+
+_mode_interp_constant_doc = (
+"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \
+'mirror', 'grid-wrap', 'wrap'}, optional
+    The `mode` parameter determines how the input array is extended
+    beyond its boundaries. Default is 'constant'. Behavior for each valid
+    value is as follows (see additional plots and details on
+    :ref:`boundary modes `):
+
+    'reflect' (`d c b a | a b c d | d c b a`)
+        The input is extended by reflecting about the edge of the last
+        pixel. This mode is also sometimes referred to as half-sample
+        symmetric.
+
+    'grid-mirror'
+        This is a synonym for 'reflect'.
+
+    'constant' (`k k k k | a b c d | k k k k`)
+        The input is extended by filling all values beyond the edge with
+        the same constant value, defined by the `cval` parameter. No
+        interpolation is performed beyond the edges of the input.
+
+    'grid-constant' (`k k k k | a b c d | k k k k`)
+        The input is extended by filling all values beyond the edge with
+        the same constant value, defined by the `cval` parameter. Interpolation
+        occurs for samples outside the input's extent  as well.
+
+    'nearest' (`a a a a | a b c d | d d d d`)
+        The input is extended by replicating the last pixel.
+
+    'mirror' (`d c b | a b c d | c b a`)
+        The input is extended by reflecting about the center of the last
+        pixel. This mode is also sometimes referred to as whole-sample
+        symmetric.
+
+    'grid-wrap' (`a b c d | a b c d | a b c d`)
+        The input is extended by wrapping around to the opposite edge.
+
+    'wrap' (`d b c d | a b c d | b c a b`)
+        The input is extended by wrapping around to the opposite edge, but in a
+        way such that the last point and initial point exactly overlap. In this
+        case it is not well defined which sample will be chosen at the point of
+        overlap.""")
+_mode_interp_mirror_doc = (
+    _mode_interp_constant_doc.replace("Default is 'constant'",
+                                      "Default is 'mirror'")
+)
+assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \
+    'Default not replaced'
+
+_mode_multiple_doc = (
+"""mode : str or sequence, optional
+    The `mode` parameter determines how the input array is extended
+    when the filter overlaps a border. By passing a sequence of modes
+    with length equal to the number of dimensions of the input array,
+    different modes can be specified along each axis. Default value is
+    'reflect'. The valid values and their behavior is as follows:
+
+    'reflect' (`d c b a | a b c d | d c b a`)
+        The input is extended by reflecting about the edge of the last
+        pixel. This mode is also sometimes referred to as half-sample
+        symmetric.
+
+    'constant' (`k k k k | a b c d | k k k k`)
+        The input is extended by filling all values beyond the edge with
+        the same constant value, defined by the `cval` parameter.
+
+    'nearest' (`a a a a | a b c d | d d d d`)
+        The input is extended by replicating the last pixel.
+
+    'mirror' (`d c b | a b c d | c b a`)
+        The input is extended by reflecting about the center of the last
+        pixel. This mode is also sometimes referred to as whole-sample
+        symmetric.
+
+    'wrap' (`a b c d | a b c d | a b c d`)
+        The input is extended by wrapping around to the opposite edge.
+
+    For consistency with the interpolation functions, the following mode
+    names can also be used:
+
+    'grid-constant'
+        This is a synonym for 'constant'.
+
+    'grid-mirror'
+        This is a synonym for 'reflect'.
+
+    'grid-wrap'
+        This is a synonym for 'wrap'.""")
+_cval_doc = (
+"""cval : scalar, optional
+    Value to fill past edges of input if `mode` is 'constant'. Default
+    is 0.0.""")
+_origin_doc = (
+"""origin : int, optional
+    Controls the placement of the filter on the input array's pixels.
+    A value of 0 (the default) centers the filter over the pixel, with
+    positive values shifting the filter to the left, and negative ones
+    to the right.""")
+_origin_multiple_doc = (
+"""origin : int or sequence, optional
+    Controls the placement of the filter on the input array's pixels.
+    A value of 0 (the default) centers the filter over the pixel, with
+    positive values shifting the filter to the left, and negative ones
+    to the right. By passing a sequence of origins with length equal to
+    the number of dimensions of the input array, different shifts can
+    be specified along each axis.""")
+_extra_arguments_doc = (
+"""extra_arguments : sequence, optional
+    Sequence of extra positional arguments to pass to passed function.""")
+_extra_keywords_doc = (
+"""extra_keywords : dict, optional
+    dict of extra keyword arguments to pass to passed function.""")
+_prefilter_doc = (
+"""prefilter : bool, optional
+    Determines if the input array is prefiltered with `spline_filter`
+    before interpolation. The default is True, which will create a
+    temporary `float64` array of filtered values if ``order > 1``. If
+    setting this to False, the output will be slightly blurred if
+    ``order > 1``, unless the input is prefiltered, i.e. it is the result
+    of calling `spline_filter` on the original input.""")
+
+docdict = {
+    'input': _input_doc,
+    'axis': _axis_doc,
+    'output': _output_doc,
+    'size_foot': _size_foot_doc,
+    'mode_interp_constant': _mode_interp_constant_doc,
+    'mode_interp_mirror': _mode_interp_mirror_doc,
+    'mode_reflect': _mode_reflect_doc,
+    'mode_multiple': _mode_multiple_doc,
+    'cval': _cval_doc,
+    'origin': _origin_doc,
+    'origin_multiple': _origin_multiple_doc,
+    'extra_arguments': _extra_arguments_doc,
+    'extra_keywords': _extra_keywords_doc,
+    'prefilter': _prefilter_doc
+    }
+
+docfiller: Final = doccer.filldoc(docdict)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8d41d00d9edf8d347c4ffc95598210489fed5e9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py
@@ -0,0 +1,143 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# 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.
+
+from collections.abc import Iterable
+import operator
+import warnings
+import numpy as np
+
+
+def _extend_mode_to_code(mode, is_filter=False):
+    """Convert an extension mode to the corresponding integer code.
+    """
+    if mode == 'nearest':
+        return 0
+    elif mode == 'wrap':
+        return 1
+    elif mode in ['reflect', 'grid-mirror']:
+        return 2
+    elif mode == 'mirror':
+        return 3
+    elif mode == 'constant':
+        return 4
+    elif mode == 'grid-wrap' and is_filter:
+        return 1
+    elif mode == 'grid-wrap':
+        return 5
+    elif mode == 'grid-constant' and is_filter:
+        return 4
+    elif mode == 'grid-constant':
+        return 6
+    else:
+        raise RuntimeError('boundary mode not supported')
+
+
+def _normalize_sequence(input, rank):
+    """If input is a scalar, create a sequence of length equal to the
+    rank by duplicating the input. If input is a sequence,
+    check if its length is equal to the length of array.
+    """
+    is_str = isinstance(input, str)
+    if not is_str and np.iterable(input):
+        normalized = list(input)
+        if len(normalized) != rank:
+            err = "sequence argument must have length equal to input rank"
+            raise RuntimeError(err)
+    else:
+        normalized = [input] * rank
+    return normalized
+
+
+def _get_output(output, input, shape=None, complex_output=False):
+    if shape is None:
+        shape = input.shape
+    if output is None:
+        if not complex_output:
+            output = np.zeros(shape, dtype=input.dtype.name)
+        else:
+            complex_type = np.promote_types(input.dtype, np.complex64)
+            output = np.zeros(shape, dtype=complex_type)
+    elif isinstance(output, (type, np.dtype)):
+        # Classes (like `np.float32`) and dtypes are interpreted as dtype
+        if complex_output and np.dtype(output).kind != 'c':
+            warnings.warn("promoting specified output dtype to complex", stacklevel=3)
+            output = np.promote_types(output, np.complex64)
+        output = np.zeros(shape, dtype=output)
+    elif isinstance(output, str):
+        output = np.dtype(output)
+        if complex_output and output.kind != 'c':
+            raise RuntimeError("output must have complex dtype")
+        elif not issubclass(output.type, np.number):
+            raise RuntimeError("output must have numeric dtype")
+        output = np.zeros(shape, dtype=output)
+    else:
+        # output was supplied as an array
+        output = np.asarray(output)
+        if output.shape != shape:
+            raise RuntimeError("output shape not correct")
+        elif complex_output and output.dtype.kind != 'c':
+            raise RuntimeError("output must have complex dtype")
+    return output
+
+
+def _check_axes(axes, ndim):
+    if axes is None:
+        return tuple(range(ndim))
+    elif np.isscalar(axes):
+        axes = (operator.index(axes),)
+    elif isinstance(axes, Iterable):
+        for ax in axes:
+            axes = tuple(operator.index(ax) for ax in axes)
+            if ax < -ndim or ax > ndim - 1:
+                raise ValueError(f"specified axis: {ax} is out of range")
+        axes = tuple(ax % ndim if ax < 0 else ax for ax in axes)
+    else:
+        message = "axes must be an integer, iterable of integers, or None"
+        raise ValueError(message)
+    if len(tuple(set(axes))) != len(axes):
+        raise ValueError("axes must be unique")
+    return axes
+
+def _skip_if_dtype(arg):
+    """'array or dtype' polymorphism.
+
+    Return None for np.int8, dtype('float32') or 'f' etc
+           arg for np.empty(3) etc
+    """
+    if isinstance(arg, str):
+        return None
+    if type(arg) is type:
+        return None if issubclass(arg, np.generic) else arg
+    else:
+        return None if isinstance(arg, np.dtype) else arg
+
+
+def _skip_if_int(arg):
+    return None if (arg is None or isinstance(arg, int)) else arg
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..6d998aa648b493336d9871117e687e8f8d5279aa
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbb913b14c76873202fce8eaabe2d08f778abe94
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py
@@ -0,0 +1,72 @@
+import functools
+from scipy._lib._array_api import (
+    is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API
+)
+
+import numpy as np
+from ._ndimage_api import *   # noqa: F403
+from . import _ndimage_api
+from . import _delegators
+__all__ = _ndimage_api.__all__
+
+
+MODULE_NAME = 'ndimage'
+
+
+def delegate_xp(delegator, module_name):
+    def inner(func):
+        @functools.wraps(func)
+        def wrapper(*args, **kwds):
+            xp = delegator(*args, **kwds)
+
+            # try delegating to a cupyx/jax namesake
+            if is_cupy(xp):
+                # https://github.com/cupy/cupy/issues/8336
+                import importlib
+                cupyx_module = importlib.import_module(f"cupyx.scipy.{module_name}")
+                cupyx_func = getattr(cupyx_module, func.__name__)
+                return cupyx_func(*args, **kwds)
+            elif is_jax(xp) and func.__name__ == "map_coordinates":
+                spx = scipy_namespace_for(xp)
+                jax_module = getattr(spx, module_name)
+                jax_func = getattr(jax_module, func.__name__)
+                return jax_func(*args, **kwds)
+            else:
+                # the original function (does all np.asarray internally)
+                # XXX: output arrays
+                result = func(*args, **kwds)
+
+                if isinstance(result, (np.ndarray, np.generic)):
+                    # XXX: np.int32->np.array_0D
+                    return xp.asarray(result)
+                elif isinstance(result, int):
+                    return result
+                elif isinstance(result, dict):
+                    # value_indices: result is {np.int64(1): (array(0), array(1))} etc
+                    return {
+                        k.item(): tuple(xp.asarray(vv) for vv in v)
+                        for k,v in result.items()
+                    }
+                elif result is None:
+                    # inplace operations
+                    return result
+                else:
+                    # lists/tuples
+                    return type(result)(
+                        xp.asarray(x) if isinstance(x, np.ndarray) else x
+                        for x in result
+                    )
+        return wrapper
+    return inner
+
+# ### decorate ###
+for func_name in _ndimage_api.__all__:
+    bare_func = getattr(_ndimage_api, func_name)
+    delegator = getattr(_delegators, func_name + "_signature")
+
+    f = (delegate_xp(delegator, MODULE_NAME)(bare_func)
+         if SCIPY_ARRAY_API
+         else bare_func)
+
+    # add the decorated function to the namespace, to be imported in __init__.py
+    vars()[func_name] = f
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/filters.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..e16d9d279a9585b2454c46ee09cf22143de833a6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/filters.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'correlate1d', 'convolve1d', 'gaussian_filter1d',
+    'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace',
+    'laplace', 'gaussian_laplace', 'generic_gradient_magnitude',
+    'gaussian_gradient_magnitude', 'correlate', 'convolve',
+    'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
+    'maximum_filter1d', 'minimum_filter', 'maximum_filter',
+    'rank_filter', 'median_filter', 'percentile_filter',
+    'generic_filter1d', 'generic_filter'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='filters',
+                                   private_modules=['_filters'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/fourier.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..73c49bd52d9a446ce0fe25d9e15b8de68fbd46fb
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/fourier.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.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'fourier_gaussian', 'fourier_uniform',
+    'fourier_ellipsoid', 'fourier_shift'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='fourier',
+                                   private_modules=['_fourier'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/interpolation.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2739c60c51037487ae8892c407e2f3d7870d5da
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/interpolation.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.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'spline_filter1d', 'spline_filter',
+    'geometric_transform', 'map_coordinates',
+    'affine_transform', 'shift', 'zoom', 'rotate',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='interpolation',
+                                   private_modules=['_interpolation'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/measurements.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f76b01840ffb829205bd1d28a7ad1f9ac5db61
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/measurements.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.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'label', 'find_objects', 'labeled_comprehension',
+    'sum', 'mean', 'variance', 'standard_deviation',
+    'minimum', 'maximum', 'median', 'minimum_position',
+    'maximum_position', 'extrema', 'center_of_mass',
+    'histogram', 'watershed_ift', 'sum_labels'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='measurements',
+                                   private_modules=['_measurements'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/morphology.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..e522e7df3a4b06b7e04ed8c2d0ecaff2a98b951d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/morphology.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'iterate_structure', 'generate_binary_structure',
+    'binary_erosion', 'binary_dilation', 'binary_opening',
+    'binary_closing', 'binary_hit_or_miss', 'binary_propagation',
+    'binary_fill_holes', 'grey_erosion', 'grey_dilation',
+    'grey_opening', 'grey_closing', 'morphological_gradient',
+    'morphological_laplace', 'white_tophat', 'black_tophat',
+    'distance_transform_bf', 'distance_transform_cdt',
+    'distance_transform_edt'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='morphology',
+                                   private_modules=['_morphology'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d8fd292b537a84fe48d0c8ae8bee75bab2b3353
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py
@@ -0,0 +1,12 @@
+import numpy as np
+
+# list of numarray data types
+integer_types: list[str] = [
+    "int8", "uint8", "int16", "uint16",
+    "int32", "uint32", "int64", "uint64"]
+
+float_types: list[str] = ["float32", "float64"]
+
+complex_types: list[str] = ["complex64", "complex128"]
+
+types: list[str] = integer_types + float_types
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6c3cff3b12cec4ad050b31cc5d5c327f32784447
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt
@@ -0,0 +1,21 @@
+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 0 1 1 1
+1 1 0 0 0 1 1
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+1 1 0 0 0 1 1
+1 1 1 0 1 1 1
+1 0 1 1 1 0 1
+0 0 0 1 0 0 0
+1 0 0 1 0 0 1
+1 1 1 1 1 1 1
+1 0 0 1 0 0 1
+0 0 0 1 0 0 0
+1 0 1 1 1 0 1
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c239b0369c9df3e06df9a2fbf048faec2f84941f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt
@@ -0,0 +1,294 @@
+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 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
+2 2 2 2 2 2 2
+3 3 3 3 3 3 3
+4 4 4 4 4 4 4
+5 5 5 5 5 5 5
+6 6 6 6 6 6 6
+7 7 7 7 7 7 7
+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 2 3 4 5 6 7
+8 9 10 11 12 13 14
+15 16 17 18 19 20 21
+22 23 24 25 26 27 28
+29 30 31 32 33 34 35
+36 37 38 39 40 41 42
+43 44 45 46 47 48 49
+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 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 2 3 4 5 6 7
+8 1 2 3 4 5 6
+9 8 1 2 3 4 5
+10 9 8 1 2 3 4
+11 10 9 8 1 2 3
+12 11 10 9 8 1 2
+13 12 11 10 9 8 1
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+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 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 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+1 2 3 4 5 6 7
+2 3 4 5 6 7 8
+3 4 5 6 7 8 9
+4 5 6 7 8 9 10
+5 6 7 8 9 10 11
+6 7 8 9 10 11 12
+7 8 9 10 11 12 13
+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 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 2 0 4
+0 0 0 2 0 0 0
+5 0 2 0 6 0 7
+2 2 0 0 0 7 7
+2 2 2 0 7 7 7
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+3 0 1 0 4 0 2
+0 0 0 1 0 0 0
+5 0 6 0 1 0 7
+5 5 0 0 0 1 1
+5 5 5 0 1 1 1
+1 1 1 0 2 2 2
+3 3 0 0 0 4 4
+5 0 6 0 7 0 8
+0 0 0 9 0 0 0
+10 0 11 0 12 0 13
+14 14 0 0 0 15 15
+16 16 16 0 17 17 17
+1 1 1 0 2 3 3
+1 1 0 0 0 3 3
+1 0 4 0 3 0 3
+0 0 0 3 0 0 0
+3 0 3 0 5 0 6
+3 3 0 0 0 6 6
+3 3 7 0 6 6 6
+1 2 3 0 4 5 6
+7 8 0 0 0 9 10
+11 0 12 0 13 0 14
+0 0 0 15 0 0 0
+16 0 17 0 18 0 19
+20 21 0 0 0 22 23
+24 25 26 0 27 28 29
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 2 0 2
+0 0 0 2 0 0 0
+2 0 2 0 4 0 5
+2 2 0 0 0 5 5
+2 2 2 0 5 5 5
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 4 0 2
+0 0 0 5 0 0 0
+6 0 7 0 8 0 9
+6 6 0 0 0 9 9
+6 6 6 0 9 9 9
+1 2 3 0 4 5 6
+7 1 0 0 0 4 5
+8 0 1 0 9 0 4
+0 0 0 1 0 0 0
+10 0 11 0 1 0 12
+13 10 0 0 0 1 14
+15 13 10 0 16 17 1
+1 2 3 0 4 5 6
+1 2 0 0 0 5 6
+1 0 7 0 8 0 6
+0 0 0 9 0 0 0
+10 0 11 0 12 0 13
+10 14 0 0 0 15 13
+10 14 16 0 17 15 13
+1 1 1 0 1 1 1
+1 1 0 0 0 1 1
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+1 1 0 0 0 1 1
+1 1 1 0 1 1 1
+1 1 2 0 3 3 3
+1 1 0 0 0 3 3
+1 0 1 0 4 0 3
+0 0 0 1 0 0 0
+5 0 6 0 1 0 1
+5 5 0 0 0 1 1
+5 5 5 0 7 1 1
+1 2 1 0 1 3 1
+2 1 0 0 0 1 3
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+4 1 0 0 0 1 5
+1 4 1 0 1 5 1
+1 2 3 0 4 5 6
+2 3 0 0 0 6 7
+3 0 8 0 6 0 9
+0 0 0 6 0 0 0
+10 0 6 0 11 0 12
+13 6 0 0 0 12 14
+6 15 16 0 12 14 17
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 1 0 3 0 2
+0 0 0 1 0 0 0
+4 0 5 0 1 0 1
+4 4 0 0 0 1 1
+4 4 4 0 1 1 1
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+4 0 0 5 0 0 5
+5 5 5 5 5 5 5
+5 0 0 5 0 0 6
+0 0 0 7 0 0 0
+8 0 7 7 7 0 9
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+4 0 0 4 0 0 5
+4 4 4 4 4 4 4
+6 0 0 4 0 0 4
+0 0 0 7 0 0 0
+8 0 7 7 7 0 9
+1 0 2 2 2 0 3
+0 0 0 4 0 0 0
+5 0 0 6 0 0 7
+8 8 8 8 8 8 8
+9 0 0 10 0 0 11
+0 0 0 12 0 0 0
+13 0 14 14 14 0 15
+1 0 2 3 3 0 4
+0 0 0 3 0 0 0
+5 0 0 3 0 0 6
+5 5 3 3 3 6 6
+5 0 0 3 0 0 6
+0 0 0 3 0 0 0
+7 0 3 3 8 0 9
+1 0 2 3 4 0 5
+0 0 0 6 0 0 0
+7 0 0 8 0 0 9
+10 11 12 13 14 15 16
+17 0 0 18 0 0 19
+0 0 0 20 0 0 0
+21 0 22 23 24 0 25
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 3 4 0 5
+0 0 0 2 0 0 0
+6 0 0 7 0 0 8
+9 6 10 11 7 12 13
+14 0 0 10 0 0 12
+0 0 0 15 0 0 0
+16 0 17 18 15 0 19
+1 0 2 3 4 0 5
+0 0 0 3 0 0 0
+6 0 0 3 0 0 7
+6 8 9 3 10 11 7
+6 0 0 3 0 0 7
+0 0 0 3 0 0 0
+12 0 13 3 14 0 15
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 2 3 0 4
+0 0 0 2 0 0 0
+5 0 0 2 0 0 6
+5 5 2 2 2 6 6
+5 0 0 2 0 0 6
+0 0 0 2 0 0 0
+7 0 8 2 2 0 9
+1 0 2 3 2 0 4
+0 0 0 2 0 0 0
+5 0 0 6 0 0 7
+8 5 6 9 6 7 10
+5 0 0 6 0 0 7
+0 0 0 11 0 0 0
+12 0 11 13 11 0 14
+1 0 2 3 4 0 5
+0 0 0 4 0 0 0
+6 0 0 7 0 0 8
+9 10 7 11 12 8 13
+10 0 0 12 0 0 14
+0 0 0 15 0 0 0
+16 0 15 17 18 0 19
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..35ae8121364d4fb3292c11f2a72333f456fa9c0a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt
@@ -0,0 +1,42 @@
+0 0 1
+1 1 1
+1 0 0
+1 0 0
+1 1 1
+0 0 1
+0 0 0
+1 1 1
+0 0 0
+0 1 1
+0 1 0
+1 1 0
+0 0 0
+0 0 0
+0 0 0
+0 1 1
+1 1 1
+1 1 0
+0 1 0
+1 1 1
+0 1 0
+1 0 0
+0 1 0
+0 0 1
+0 1 0
+0 1 0
+0 1 0
+1 1 1
+1 1 1
+1 1 1
+1 1 0
+0 1 0
+0 1 1
+1 0 1
+0 1 0
+1 0 1
+0 0 1
+0 1 0
+1 0 0
+1 1 0
+1 1 1
+0 1 1
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..61a5a0f70262ef9f21fe8593a64f155bd583cab1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py
@@ -0,0 +1,102 @@
+import numpy as np
+from scipy._lib._array_api import xp_assert_close
+
+from scipy import ndimage
+from scipy.ndimage import _ctest
+from scipy.ndimage import _cytest
+from scipy._lib._ccallback import LowLevelCallable
+
+FILTER1D_FUNCTIONS = [
+    lambda filter_size: _ctest.filter1d(filter_size),
+    lambda filter_size: _cytest.filter1d(filter_size, with_signature=False),
+    lambda filter_size: LowLevelCallable(
+                            _cytest.filter1d(filter_size, with_signature=True)
+                        ),
+    lambda filter_size: LowLevelCallable.from_cython(
+                            _cytest, "_filter1d",
+                            _cytest.filter1d_capsule(filter_size),
+                        ),
+]
+
+FILTER2D_FUNCTIONS = [
+    lambda weights: _ctest.filter2d(weights),
+    lambda weights: _cytest.filter2d(weights, with_signature=False),
+    lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)),
+    lambda weights: LowLevelCallable.from_cython(_cytest,
+                                                 "_filter2d",
+                                                 _cytest.filter2d_capsule(weights),),
+]
+
+TRANSFORM_FUNCTIONS = [
+    lambda shift: _ctest.transform(shift),
+    lambda shift: _cytest.transform(shift, with_signature=False),
+    lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)),
+    lambda shift: LowLevelCallable.from_cython(_cytest,
+                                               "_transform",
+                                               _cytest.transform_capsule(shift),),
+]
+
+
+def test_generic_filter():
+    def filter2d(footprint_elements, weights):
+        return (weights*footprint_elements).sum()
+
+    def check(j):
+        func = FILTER2D_FUNCTIONS[j]
+
+        im = np.ones((20, 20))
+        im[:10,:10] = 0
+        footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
+        footprint_size = np.count_nonzero(footprint)
+        weights = np.ones(footprint_size)/footprint_size
+
+        res = ndimage.generic_filter(im, func(weights),
+                                     footprint=footprint)
+        std = ndimage.generic_filter(im, filter2d, footprint=footprint,
+                                     extra_arguments=(weights,))
+        xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+    for j, func in enumerate(FILTER2D_FUNCTIONS):
+        check(j)
+
+
+def test_generic_filter1d():
+    def filter1d(input_line, output_line, filter_size):
+        for i in range(output_line.size):
+            output_line[i] = 0
+            for j in range(filter_size):
+                output_line[i] += input_line[i+j]
+        output_line /= filter_size
+
+    def check(j):
+        func = FILTER1D_FUNCTIONS[j]
+
+        im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1))
+        filter_size = 3
+
+        res = ndimage.generic_filter1d(im, func(filter_size),
+                                       filter_size)
+        std = ndimage.generic_filter1d(im, filter1d, filter_size,
+                                       extra_arguments=(filter_size,))
+        xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+    for j, func in enumerate(FILTER1D_FUNCTIONS):
+        check(j)
+
+
+def test_geometric_transform():
+    def transform(output_coordinates, shift):
+        return output_coordinates[0] - shift, output_coordinates[1] - shift
+
+    def check(j):
+        func = TRANSFORM_FUNCTIONS[j]
+
+        im = np.arange(12).reshape(4, 3).astype(np.float64)
+        shift = 0.5
+
+        res = ndimage.geometric_transform(im, func(shift))
+        std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,))
+        xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+    for j, func in enumerate(TRANSFORM_FUNCTIONS):
+        check(j)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..a82de456bb92c96d5b9a599d4b33c987e134fdc8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py
@@ -0,0 +1,67 @@
+""" Testing data types for ndimage calls
+"""
+import numpy as np
+
+from scipy._lib._array_api import assert_array_almost_equal
+import pytest
+
+from scipy import ndimage
+
+
+def test_map_coordinates_dts():
+    # check that ndimage accepts different data types for interpolation
+    data = np.array([[4, 1, 3, 2],
+                     [7, 6, 8, 5],
+                     [3, 5, 3, 6]])
+    shifted_data = np.array([[0, 0, 0, 0],
+                             [0, 4, 1, 3],
+                             [0, 7, 6, 8]])
+    idx = np.indices(data.shape)
+    dts = (np.uint8, np.uint16, np.uint32, np.uint64,
+           np.int8, np.int16, np.int32, np.int64,
+           np.intp, np.uintp, np.float32, np.float64)
+    for order in range(0, 6):
+        for data_dt in dts:
+            these_data = data.astype(data_dt)
+            for coord_dt in dts:
+                # affine mapping
+                mat = np.eye(2, dtype=coord_dt)
+                off = np.zeros((2,), dtype=coord_dt)
+                out = ndimage.affine_transform(these_data, mat, off)
+                assert_array_almost_equal(these_data, out)
+                # map coordinates
+                coords_m1 = idx.astype(coord_dt) - 1
+                coords_p10 = idx.astype(coord_dt) + 10
+                out = ndimage.map_coordinates(these_data, coords_m1, order=order)
+                assert_array_almost_equal(out, shifted_data)
+                # check constant fill works
+                out = ndimage.map_coordinates(these_data, coords_p10, order=order)
+                assert_array_almost_equal(out, np.zeros((3,4)))
+            # check shift and zoom
+            out = ndimage.shift(these_data, 1)
+            assert_array_almost_equal(out, shifted_data)
+            out = ndimage.zoom(these_data, 1)
+            assert_array_almost_equal(these_data, out)
+
+
+@pytest.mark.xfail(True, reason="Broken on many platforms")
+def test_uint64_max():
+    # Test interpolation respects uint64 max.  Reported to fail at least on
+    # win32 (due to the 32 bit visual C compiler using signed int64 when
+    # converting between uint64 to double) and Debian on s390x.
+    # Interpolation is always done in double precision floating point, so
+    # we use the largest uint64 value for which int(float(big)) still fits
+    # in a uint64.
+    # This test was last enabled on macOS only, and there it started failing
+    # on arm64 as well (see gh-19117).
+    big = 2**64 - 1025
+    arr = np.array([big, big, big], dtype=np.uint64)
+    # Tests geometric transform (map_coordinates, affine_transform)
+    inds = np.indices(arr.shape) - 0.1
+    x = ndimage.map_coordinates(arr, inds)
+    assert x[1] == int(float(big))
+    assert x[2] == int(float(big))
+    # Tests zoom / shift
+    x = ndimage.shift(arr, 0.1)
+    assert x[1] == int(float(big))
+    assert x[2] == int(float(big))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d5cb39f566827f41037e34a5a63ce874996c36f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py
@@ -0,0 +1,2920 @@
+''' Some tests for filters '''
+import functools
+import itertools
+import re
+
+import numpy as np
+import pytest
+from numpy.testing import suppress_warnings, assert_allclose, assert_array_equal
+from hypothesis import strategies as st
+from hypothesis import given
+import hypothesis.extra.numpy as npst
+from pytest import raises as assert_raises
+from scipy import ndimage
+from scipy._lib._array_api import (
+    assert_almost_equal,
+    assert_array_almost_equal,
+    xp_assert_close,
+    xp_assert_equal,
+)
+from scipy._lib._array_api import is_cupy, is_numpy, is_torch, array_namespace
+from scipy.conftest import array_api_compatible
+from scipy.ndimage._filters import _gaussian_kernel1d
+
+from . import types, float_types, complex_types
+
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              pytest.mark.usefixtures("xfail_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy']),]
+
+
+def sumsq(a, b, xp=None):
+    xp = array_namespace(a, b) if xp is None else xp
+    return xp.sqrt(xp.sum((a - b)**2))
+
+
+def _complex_correlate(xp, array, kernel, real_dtype, convolve=False,
+                       mode="reflect", cval=0, ):
+    """Utility to perform a reference complex-valued convolutions.
+
+    When convolve==False, correlation is performed instead
+    """
+    array = xp.asarray(array)
+    kernel = xp.asarray(kernel)
+    isdtype = array_namespace(array, kernel).isdtype
+    complex_array = isdtype(array.dtype, 'complex floating')
+    complex_kernel = isdtype(kernel.dtype, 'complex floating')
+    if array.ndim == 1:
+        func = ndimage.convolve1d if convolve else ndimage.correlate1d
+    else:
+        func = ndimage.convolve if convolve else ndimage.correlate
+    if not convolve:
+        kernel = xp.conj(kernel)
+    if complex_array and complex_kernel:
+        # use: real(cval) for array.real component
+        #      imag(cval) for array.imag component
+        re_cval = cval.real if isinstance(cval, complex) else xp.real(cval)
+        im_cval = cval.imag if isinstance(cval, complex) else xp.imag(cval)
+
+        output = (
+            func(xp.real(array), xp.real(kernel), output=real_dtype,
+                 mode=mode, cval=re_cval) -
+            func(xp.imag(array), xp.imag(kernel), output=real_dtype,
+                 mode=mode, cval=im_cval) +
+            1j * func(xp.imag(array), xp.real(kernel), output=real_dtype,
+                      mode=mode, cval=im_cval) +
+            1j * func(xp.real(array), xp.imag(kernel), output=real_dtype,
+                      mode=mode, cval=re_cval)
+        )
+    elif complex_array:
+        re_cval = xp.real(cval)
+        re_cval = re_cval.item() if isinstance(re_cval, xp.ndarray) else re_cval
+        im_cval = xp.imag(cval)
+        im_cval = im_cval.item() if isinstance(im_cval, xp.ndarray) else im_cval
+
+        output = (
+            func(xp.real(array), kernel, output=real_dtype, mode=mode,
+                 cval=re_cval) +
+            1j * func(xp.imag(array), kernel, output=real_dtype, mode=mode,
+                      cval=im_cval)
+        )
+    elif complex_kernel:
+        # real array so cval is real too
+        output = (
+            func(array, xp.real(kernel), output=real_dtype, mode=mode, cval=cval) +
+            1j * func(array, xp.imag(kernel), output=real_dtype, mode=mode,
+                      cval=cval)
+        )
+    return output
+
+
+def _cases_axes_tuple_length_mismatch():
+    # Generate combinations of filter function, valid kwargs, and
+    # keyword-value pairs for which the value will become with mismatched
+    # (invalid) size
+    filter_func = ndimage.gaussian_filter
+    kwargs = dict(radius=3, mode='constant', sigma=1.0, order=0)
+    for key, val in kwargs.items():
+        yield filter_func, kwargs, key, val
+
+    filter_funcs = [ndimage.uniform_filter, ndimage.minimum_filter,
+                    ndimage.maximum_filter]
+    kwargs = dict(size=3, mode='constant', origin=0)
+    for filter_func in filter_funcs:
+        for key, val in kwargs.items():
+            yield filter_func, kwargs, key, val
+
+    filter_funcs = [ndimage.correlate, ndimage.convolve]
+    # sequence of mode not supported for correlate or convolve
+    kwargs = dict(origin=0)
+    for filter_func in filter_funcs:
+        for key, val in kwargs.items():
+            yield filter_func, kwargs, key, val
+
+
+class TestNdimageFilters:
+
+    def _validate_complex(self, xp, array, kernel, type2, mode='reflect',
+                          cval=0, check_warnings=True):
+        # utility for validating complex-valued correlations
+        real_dtype = xp.real(xp.asarray([], dtype=type2)).dtype
+        expected = _complex_correlate(
+            xp, array, kernel, real_dtype, convolve=False, mode=mode, cval=cval
+        )
+
+        if array.ndim == 1:
+            correlate = functools.partial(ndimage.correlate1d, axis=-1,
+                                          mode=mode, cval=cval)
+            convolve = functools.partial(ndimage.convolve1d, axis=-1,
+                                         mode=mode, cval=cval)
+        else:
+            correlate = functools.partial(ndimage.correlate, mode=mode,
+                                          cval=cval)
+            convolve = functools.partial(ndimage.convolve, mode=mode,
+                                          cval=cval)
+
+        # test correlate output dtype
+        output = correlate(array, kernel, output=type2)
+        assert_array_almost_equal(expected, output)
+        assert output.dtype.type == type2
+
+        # test correlate with pre-allocated output
+        output = xp.zeros_like(array, dtype=type2)
+        correlate(array, kernel, output=output)
+        assert_array_almost_equal(expected, output)
+
+        # test convolve output dtype
+        output = convolve(array, kernel, output=type2)
+        expected = _complex_correlate(
+            xp, array, kernel, real_dtype, convolve=True, mode=mode, cval=cval,
+        )
+        assert_array_almost_equal(expected, output)
+        assert output.dtype.type == type2
+
+        # convolve with pre-allocated output
+        convolve(array, kernel, output=output)
+        assert_array_almost_equal(expected, output)
+        assert output.dtype.type == type2
+
+        if check_warnings:
+            # warns if the output is not a complex dtype
+            with pytest.warns(UserWarning,
+                              match="promoting specified output dtype to "
+                              "complex"):
+                correlate(array, kernel, output=real_dtype)
+
+            with pytest.warns(UserWarning,
+                              match="promoting specified output dtype to "
+                              "complex"):
+                convolve(array, kernel, output=real_dtype)
+
+        # raises if output array is provided, but is not complex-valued
+        output_real = xp.zeros_like(array, dtype=real_dtype)
+        with assert_raises(RuntimeError):
+            correlate(array, kernel, output=output_real)
+
+        with assert_raises(RuntimeError):
+            convolve(array, kernel, output=output_real)
+
+    def test_correlate01(self, xp):
+        array = xp.asarray([1, 2])
+        weights = xp.asarray([2])
+        expected = xp.asarray([2, 4])
+
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+    @xfail_xp_backends('cupy', reason="Differs by a factor of two?")
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_correlate01_overlap(self, xp):
+        array = xp.reshape(xp.arange(256), (16, 16))
+        weights = xp.asarray([2])
+        expected = 2 * array
+
+        ndimage.correlate1d(array, weights, output=array)
+        assert_array_almost_equal(array, expected)
+
+    def test_correlate02(self, xp):
+        array = xp.asarray([1, 2, 3])
+        kernel = xp.asarray([1])
+
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(array, output)
+
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(array, output)
+
+        output = ndimage.correlate1d(array, kernel)
+        assert_array_almost_equal(array, output)
+
+        output = ndimage.convolve1d(array, kernel)
+        assert_array_almost_equal(array, output)
+
+    def test_correlate03(self, xp):
+        array = xp.asarray([1])
+        weights = xp.asarray([1, 1])
+        expected = xp.asarray([2])
+
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+    def test_correlate04(self, xp):
+        array = xp.asarray([1, 2])
+        tcor = xp.asarray([2, 3])
+        tcov = xp.asarray([3, 4])
+        weights = xp.asarray([1, 1])
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, tcov)
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, tcov)
+
+    def test_correlate05(self, xp):
+        array = xp.asarray([1, 2, 3])
+        tcor = xp.asarray([2, 3, 5])
+        tcov = xp.asarray([3, 5, 6])
+        kernel = xp.asarray([1, 1])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(tcor, output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(tcov, output)
+        output = ndimage.correlate1d(array, kernel)
+        assert_array_almost_equal(tcor, output)
+        output = ndimage.convolve1d(array, kernel)
+        assert_array_almost_equal(tcov, output)
+
+    def test_correlate06(self, xp):
+        array = xp.asarray([1, 2, 3])
+        tcor = xp.asarray([9, 14, 17])
+        tcov = xp.asarray([7, 10, 15])
+        weights = xp.asarray([1, 2, 3])
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, tcov)
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, tcov)
+
+    def test_correlate07(self, xp):
+        array = xp.asarray([1, 2, 3])
+        expected = xp.asarray([5, 8, 11])
+        weights = xp.asarray([1, 2, 1])
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, expected)
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, expected)
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, expected)
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+    def test_correlate08(self, xp):
+        array = xp.asarray([1, 2, 3])
+        tcor = xp.asarray([1, 2, 5])
+        tcov = xp.asarray([3, 6, 7])
+        weights = xp.asarray([1, 2, -1])
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, tcov)
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, tcov)
+
+    def test_correlate09(self, xp):
+        array = xp.asarray([])
+        kernel = xp.asarray([1, 1])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(array, output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(array, output)
+        output = ndimage.correlate1d(array, kernel)
+        assert_array_almost_equal(array, output)
+        output = ndimage.convolve1d(array, kernel)
+        assert_array_almost_equal(array, output)
+
+    def test_correlate10(self, xp):
+        array = xp.asarray([[]])
+        kernel = xp.asarray([[1, 1]])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(array, output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(array, output)
+
+    def test_correlate11(self, xp):
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]])
+        kernel = xp.asarray([[1, 1],
+                             [1, 1]])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(xp.asarray([[12, 16, 18], [18, 22, 24]]), output)
+
+    def test_correlate12(self, xp):
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]])
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_kernel', types)
+    def test_correlate13(self, dtype_array, dtype_kernel, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_kernel = getattr(xp, dtype_kernel)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel, output=dtype_kernel)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        assert output.dtype.type == dtype_kernel
+
+        output = ndimage.convolve(array, kernel,
+                                  output=dtype_kernel)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == dtype_kernel
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate14(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = xp.zeros(array.shape, dtype=dtype_output)
+        ndimage.correlate(array, kernel, output=output)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        assert output.dtype.type == dtype_output
+
+        ndimage.convolve(array, kernel, output=output)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == dtype_output
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    def test_correlate15(self, dtype_array, xp):
+        dtype_array = getattr(xp, dtype_array)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel, output=xp.float32)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        assert output.dtype.type == xp.float32
+
+        output = ndimage.convolve(array, kernel, output=xp.float32)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == xp.float32
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    def test_correlate16(self, dtype_array, xp):
+        dtype_array = getattr(xp, dtype_array)
+
+        kernel = xp.asarray([[0.5, 0],
+                             [0, 0.5]])
+        array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel, output=xp.float32)
+        assert_array_almost_equal(xp.asarray([[1, 1.5, 2.5], [2.5, 3, 4]]), output)
+        assert output.dtype.type == xp.float32
+
+        output = ndimage.convolve(array, kernel, output=xp.float32)
+        assert_array_almost_equal(xp.asarray([[3, 4, 4.5], [4.5, 5.5, 6]]), output)
+        assert output.dtype.type == xp.float32
+
+    def test_correlate17(self, xp):
+        array = xp.asarray([1, 2, 3])
+        tcor = xp.asarray([3, 5, 6])
+        tcov = xp.asarray([2, 3, 5])
+        kernel = xp.asarray([1, 1])
+        output = ndimage.correlate(array, kernel, origin=-1)
+        assert_array_almost_equal(tcor, output)
+        output = ndimage.convolve(array, kernel, origin=-1)
+        assert_array_almost_equal(tcov, output)
+        output = ndimage.correlate1d(array, kernel, origin=-1)
+        assert_array_almost_equal(tcor, output)
+        output = ndimage.convolve1d(array, kernel, origin=-1)
+        assert_array_almost_equal(tcov, output)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    def test_correlate18(self, dtype_array, xp):
+        dtype_array = getattr(xp, dtype_array)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel,
+                                   output=xp.float32,
+                                   mode='nearest', origin=-1)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == xp.float32
+
+        output = ndimage.convolve(array, kernel,
+                                  output=xp.float32,
+                                  mode='nearest', origin=-1)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        assert output.dtype.type == xp.float32
+
+    def test_correlate_mode_sequence(self, xp):
+        kernel = xp.ones((2, 2))
+        array = xp.ones((3, 3), dtype=xp.float64)
+        with assert_raises(RuntimeError):
+            ndimage.correlate(array, kernel, mode=['nearest', 'reflect'])
+        with assert_raises(RuntimeError):
+            ndimage.convolve(array, kernel, mode=['nearest', 'reflect'])
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    def test_correlate19(self, dtype_array, xp):
+        dtype_array = getattr(xp, dtype_array)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel,
+                                   output=xp.float32,
+                                   mode='nearest', origin=[-1, 0])
+        assert_array_almost_equal(xp.asarray([[5, 6, 8], [8, 9, 11]]), output)
+        assert output.dtype.type == xp.float32
+
+        output = ndimage.convolve(array, kernel,
+                                  output=xp.float32,
+                                  mode='nearest', origin=[-1, 0])
+        assert_array_almost_equal(xp.asarray([[3, 5, 6], [6, 8, 9]]), output)
+        assert output.dtype.type == xp.float32
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate20(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0, output=output)
+        assert_array_almost_equal(output, expected)
+        ndimage.convolve1d(array, weights, axis=0, output=output)
+        assert_array_almost_equal(output, expected)
+
+    def test_correlate21(self, xp):
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]])
+        expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+        weights = xp.asarray([1, 2, 1])
+        output = ndimage.correlate1d(array, weights, axis=0)
+        assert_array_almost_equal(output, expected)
+        output = ndimage.convolve1d(array, weights, axis=0)
+        assert_array_almost_equal(output, expected)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate22(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        expected = xp.asarray([[6, 12, 18], [6, 12, 18]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0,
+                            mode='wrap', output=output)
+        assert_array_almost_equal(output, expected)
+        ndimage.convolve1d(array, weights, axis=0,
+                           mode='wrap', output=output)
+        assert_array_almost_equal(output, expected)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate23(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0,
+                            mode='nearest', output=output)
+        assert_array_almost_equal(output, expected)
+        ndimage.convolve1d(array, weights, axis=0,
+                           mode='nearest', output=output)
+        assert_array_almost_equal(output, expected)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate24(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        tcor = xp.asarray([[7, 14, 21], [8, 16, 24]])
+        tcov = xp.asarray([[4, 8, 12], [5, 10, 15]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0,
+                            mode='nearest', output=output, origin=-1)
+        assert_array_almost_equal(output, tcor)
+        ndimage.convolve1d(array, weights, axis=0,
+                           mode='nearest', output=output, origin=-1)
+        assert_array_almost_equal(output, tcov)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate25(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        tcor = xp.asarray([[4, 8, 12], [5, 10, 15]])
+        tcov = xp.asarray([[7, 14, 21], [8, 16, 24]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0,
+                            mode='nearest', output=output, origin=1)
+        assert_array_almost_equal(output, tcor)
+        ndimage.convolve1d(array, weights, axis=0,
+                           mode='nearest', output=output, origin=1)
+        assert_array_almost_equal(output, tcov)
+
+    def test_correlate26(self, xp):
+        # test fix for gh-11661 (mirror extension of a length 1 signal)
+        y = ndimage.convolve1d(xp.ones(1), xp.ones(5), mode='mirror')
+        xp_assert_equal(y, xp.asarray([5.]))
+
+        y = ndimage.correlate1d(xp.ones(1), xp.ones(5), mode='mirror')
+        xp_assert_equal(y, xp.asarray([5.]))
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate_complex_kernel(self, dtype_input, dtype_kernel,
+                                      dtype_output, xp, num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype_kernel)
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    @pytest.mark.parametrize('mode', ['grid-constant', 'constant'])
+    def test_correlate_complex_kernel_cval(self, dtype_input, dtype_kernel,
+                                           dtype_output, mode, xp,
+                                           num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        if is_cupy(xp) and mode == 'grid-constant':
+            pytest.xfail('https://github.com/cupy/cupy/issues/8404')
+
+        # test use of non-zero cval with complex inputs
+        # also verifies that mode 'grid-constant' does not segfault
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype_kernel)
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output, mode=mode,
+                               cval=5.0,
+                               check_warnings=num_parallel_threads == 1)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.thread_unsafe
+    def test_correlate_complex_kernel_invalid_cval(self, dtype_input,
+                                                   dtype_kernel, xp):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+
+        # cannot give complex cval with a real image
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype_kernel)
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_input)
+        for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d,
+                     ndimage.correlate1d]:
+            with pytest.raises((ValueError, TypeError)):
+                func(array, kernel, mode='constant', cval=5.0 + 1.0j,
+                     output=xp.complex64)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_kernel(self, dtype_input, dtype_kernel,
+                                        dtype_output, xp, num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel)
+        array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_kernel_cval(self, dtype_input, dtype_kernel,
+                                             dtype_output, xp,
+                                             num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel)
+        array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+                               cval=5.0,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate_complex_input(self, dtype_input, dtype_kernel,
+                                     dtype_output, xp, num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]], dtype=dtype_kernel)
+        array = xp.asarray([[1, 2j, 3],
+                            [1 + 4j, 5, 6j]], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_input(self, dtype_input, dtype_kernel,
+                                       dtype_output, xp, num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel)
+        array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+    @skip_xp_backends(np_only=True,
+                      reason='output=dtype is numpy-specific',
+                      exceptions=['cupy'])
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_input_cval(self, dtype_input, dtype_kernel,
+                                            dtype_output, xp,
+                                            num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel)
+        array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+                               cval=5 - 3j,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate_complex_input_and_kernel(self, dtype, dtype_output, xp,
+                                                num_parallel_threads):
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype)
+        array = xp.asarray([[1, 2j, 3],
+                            [1 + 4j, 5, 6j]], dtype=dtype)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+    @skip_xp_backends(np_only=True,
+                      reason="output=dtype is numpy-specific",
+                      exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate_complex_input_and_kernel_cval(self, dtype,
+                                                     dtype_output, xp,
+                                                     num_parallel_threads):
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype)
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype)
+        self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+                               cval=5.0 + 2.0j,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason="output=dtype is numpy-specific")
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    @pytest.mark.thread_unsafe
+    def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output, xp,
+                                                  num_parallel_threads):
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 1 + 1j], dtype=dtype)
+        array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_input_and_kernel_cval(self, dtype,
+                                                       dtype_output, xp,
+                                                       num_parallel_threads):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8405")
+
+        kernel = xp.asarray([1, 1 + 1j], dtype=dtype)
+        array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype)
+        self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+                               cval=5.0 + 2.0j,
+                               check_warnings=num_parallel_threads == 1)
+
+    def test_gauss01(self, xp):
+        input = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=xp.float32)
+        output = ndimage.gaussian_filter(input, 0)
+        assert_array_almost_equal(output, input)
+
+    def test_gauss02(self, xp):
+        input = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=xp.float32)
+        output = ndimage.gaussian_filter(input, 1.0)
+        assert input.dtype == output.dtype
+        assert input.shape == output.shape
+
+    def test_gauss03(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8403")
+
+        # single precision data
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        output = ndimage.gaussian_filter(input, [1.0, 1.0])
+
+        assert input.dtype == output.dtype
+        assert input.shape == output.shape
+
+        # input.sum() is 49995000.0.  With single precision floats, we can't
+        # expect more than 8 digits of accuracy, so use decimal=0 in this test.
+        o_sum = xp.sum(output, dtype=xp.float64)
+        i_sum = xp.sum(input, dtype=xp.float64)
+        assert_almost_equal(o_sum, i_sum, decimal=0)
+        assert sumsq(input, output) > 1.0
+
+    def test_gauss04(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        otype = xp.float64
+        output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype)
+        assert output.dtype.type == xp.float64
+        assert input.shape == output.shape
+        assert sumsq(input, output) > 1.0
+
+    def test_gauss05(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        otype = xp.float64
+        output = ndimage.gaussian_filter(input, [1.0, 1.0],
+                                         order=1, output=otype)
+        assert output.dtype.type == xp.float64
+        assert input.shape == output.shape
+        assert sumsq(input, output) > 1.0
+
+    def test_gauss06(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        otype = xp.float64
+        output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype)
+        output2 = ndimage.gaussian_filter(input, 1.0, output=otype)
+        assert_array_almost_equal(output1, output2)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_gauss_memory_overlap(self, xp):
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        output1 = ndimage.gaussian_filter(input, 1.0)
+        ndimage.gaussian_filter(input, 1.0, output=input)
+        assert_array_almost_equal(output1, input)
+
+    @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'),
+                             [(ndimage.gaussian_filter, (), 0, 1.0),
+                              (ndimage.uniform_filter, (), 1, 3),
+                              (ndimage.minimum_filter, (), 1, 3),
+                              (ndimage.maximum_filter, (), 1, 3),
+                              (ndimage.median_filter, (), 1, 3),
+                              (ndimage.rank_filter, (1,), 1, 3),
+                              (ndimage.percentile_filter, (40,), 1, 3)])
+    @pytest.mark.parametrize(
+        'axes',
+        tuple(itertools.combinations(range(-3, 3), 1))
+        + tuple(itertools.combinations(range(-3, 3), 2))
+        + ((0, 1, 2),))
+    def test_filter_axes(self, filter_func, extra_args, size0, size, axes, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        # Note: `size` is called `sigma` in `gaussian_filter`
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+
+        if len(set(ax % array.ndim for ax in axes)) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError, match="axes must be unique"):
+                filter_func(array, *extra_args, size, axes=axes)
+            return
+        output = filter_func(array, *extra_args, size, axes=axes)
+
+        # result should be equivalent to sigma=0.0/size=1 on unfiltered axes
+        axes = xp.asarray(axes)
+        all_sizes = tuple(size if ax in (axes % array.ndim) else size0
+                          for ax in range(array.ndim))
+        expected = filter_func(array, *extra_args, all_sizes)
+        xp_assert_close(output, expected)
+
+    @skip_xp_backends("cupy",
+                      reason="these filters do not yet have axes support",
+    )
+    @pytest.mark.parametrize(('filter_func', 'kwargs'),
+                             [(ndimage.laplace, {}),
+                              (ndimage.gaussian_gradient_magnitude,
+                               {"sigma": 1.0}),
+                              (ndimage.gaussian_laplace, {"sigma": 0.5})])
+    def test_derivative_filter_axes(self, xp, filter_func, kwargs):
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+
+        # duplicate axes raises an error
+        with pytest.raises(ValueError, match="axes must be unique"):
+            filter_func(array, axes=(1, 1), **kwargs)
+
+        # compare results to manually looping over the non-filtered axes
+        output = filter_func(array, axes=(1, 2), **kwargs)
+        expected = xp.empty_like(output)
+        expected = []
+        for i in range(array.shape[0]):
+            expected.append(filter_func(array[i, ...], **kwargs))
+        expected = xp.stack(expected, axis=0)
+        xp_assert_close(output, expected)
+
+        output = filter_func(array, axes=(0, -1), **kwargs)
+        expected = []
+        for i in range(array.shape[1]):
+            expected.append(filter_func(array[:, i, :], **kwargs))
+        expected = xp.stack(expected, axis=1)
+        xp_assert_close(output, expected)
+
+        output = filter_func(array, axes=(1), **kwargs)
+        expected = []
+        for i in range(array.shape[0]):
+            exp_inner = []
+            for j in range(array.shape[2]):
+                exp_inner.append(filter_func(array[i, :, j], **kwargs))
+            expected.append(xp.stack(exp_inner, axis=-1))
+        expected = xp.stack(expected, axis=0)
+        xp_assert_close(output, expected)
+
+    @skip_xp_backends("cupy",
+                      reason="generic_filter does not yet have axes support",
+    )
+    @pytest.mark.parametrize(
+        'axes',
+        tuple(itertools.combinations(range(-3, 3), 1))
+        + tuple(itertools.combinations(range(-3, 3), 2))
+        + ((0, 1, 2),))
+    def test_generic_filter_axes(self, xp, axes):
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+        size = 3
+        if len(set(ax % array.ndim for ax in axes)) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError, match="axes must be unique"):
+                ndimage.generic_filter(array, np.amax, size=size, axes=axes)
+            return
+
+        # choose np.amax as the function so we can compare to maximum_filter
+        output = ndimage.generic_filter(array, np.amax, size=size, axes=axes)
+        expected = ndimage.maximum_filter(array, size=size, axes=axes)
+        xp_assert_close(output, expected)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8339",
+    )
+    @pytest.mark.parametrize('func', [ndimage.correlate, ndimage.convolve])
+    @pytest.mark.parametrize(
+        'dtype', [np.float32, np.float64, np.complex64, np.complex128]
+    )
+    @pytest.mark.parametrize(
+        'axes', tuple(itertools.combinations(range(-3, 3), 2))
+    )
+    @pytest.mark.parametrize('origin', [(0, 0), (-1, 1)])
+    def test_correlate_convolve_axes(self, xp, func, dtype, axes, origin):
+        array = xp.asarray(np.arange(6 * 8 * 12, dtype=dtype).reshape(6, 8, 12))
+        weights = xp.arange(3 * 5)
+        weights = xp.reshape(weights, (3, 5))
+        axes = tuple(ax % array.ndim for ax in axes)
+        if len(tuple(set(axes))) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError):
+                func(array, weights=weights, axes=axes, origin=origin)
+            return
+        output = func(array, weights=weights, axes=axes, origin=origin)
+
+        missing_axis = tuple(set(range(3)) - set(axes))[0]
+        # module 'torch' has no attribute 'expand_dims' so use reshape instead
+        #    weights_3d = xp.expand_dims(weights, axis=missing_axis)
+        shape_3d = (
+            weights.shape[:missing_axis] + (1,) + weights.shape[missing_axis:]
+        )
+        weights_3d = xp.reshape(weights, shape_3d)
+        origin_3d = [0, 0, 0]
+        for i, ax in enumerate(axes):
+            origin_3d[ax] = origin[i]
+        expected = func(array, weights=weights_3d, origin=origin_3d)
+        xp_assert_close(output, expected)
+
+    kwargs_gauss = dict(radius=[4, 2, 3], order=[0, 1, 2],
+                        mode=['reflect', 'nearest', 'constant'])
+    kwargs_other = dict(origin=(-1, 0, 1),
+                        mode=['reflect', 'nearest', 'constant'])
+    kwargs_rank = dict(origin=(-1, 0, 1))
+
+    @skip_xp_backends("array_api_strict",
+         reason="fancy indexing is only available in 2024 version",
+    )
+    @pytest.mark.parametrize("filter_func, size0, size, kwargs",
+                             [(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss),
+                              (ndimage.uniform_filter, 1, 3, kwargs_other),
+                              (ndimage.maximum_filter, 1, 3, kwargs_other),
+                              (ndimage.minimum_filter, 1, 3, kwargs_other),
+                              (ndimage.median_filter, 1, 3, kwargs_rank),
+                              (ndimage.rank_filter, 1, 3, kwargs_rank),
+                              (ndimage.percentile_filter, 1, 3, kwargs_rank)])
+    @pytest.mark.parametrize('axes', itertools.combinations(range(-3, 3), 2))
+    def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes, xp):
+
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+
+        kwargs = {key: np.array(val) for key, val in kwargs.items()}
+        axes = np.array(axes)
+        n_axes = axes.size
+
+        if filter_func == ndimage.rank_filter:
+            args = (2,)  # (rank,)
+        elif filter_func == ndimage.percentile_filter:
+            args = (30,)  # (percentile,)
+        else:
+            args = ()
+
+        # form kwargs that specify only the axes in `axes`
+        reduced_kwargs = {key: val[axes] for key, val in kwargs.items()}
+        if len(set(axes % array.ndim)) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError, match="axes must be unique"):
+                filter_func(array, *args, [size]*n_axes, axes=axes,
+                            **reduced_kwargs)
+            return
+
+        output = filter_func(array, *args, [size]*n_axes, axes=axes,
+                             **reduced_kwargs)
+
+        # result should be equivalent to sigma=0.0/size=1 on unfiltered axes
+        size_3d = np.full(array.ndim, fill_value=size0)
+        size_3d[axes] = size
+        size_3d = [size_3d[i] for i in range(size_3d.shape[0])]
+        if 'origin' in kwargs:
+            # origin should be zero on the axis that has size 0
+            origin = np.asarray([0, 0, 0])
+            origin[axes] = reduced_kwargs['origin']
+            origin = xp.asarray(origin)
+            kwargs['origin'] = origin
+        expected = filter_func(array, *args, size_3d, **kwargs)
+        xp_assert_close(output, expected)
+
+
+    @pytest.mark.parametrize("filter_func, kwargs",
+                             [(ndimage.convolve, {}),
+                              (ndimage.correlate, {}),
+                              (ndimage.minimum_filter, {}),
+                              (ndimage.maximum_filter, {}),
+                              (ndimage.median_filter, {}),
+                              (ndimage.rank_filter, {"rank": 1}),
+                              (ndimage.percentile_filter, {"percentile": 30})])
+    def test_filter_weights_subset_axes_origins(self, filter_func, kwargs, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        axes = (-2, -1)
+        origins = (0, 1)
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+
+        # weights with ndim matching len(axes)
+        footprint = np.ones((3, 5), dtype=bool)
+        footprint[0, 1] = 0  # make non-separable
+        footprint = xp.asarray(footprint)
+
+        if filter_func in (ndimage.convolve, ndimage.correlate):
+            kwargs["weights"] = footprint
+        else:
+            kwargs["footprint"] = footprint
+        kwargs["axes"] = axes
+
+        output = filter_func(array, origin=origins, **kwargs)
+
+        output0 = filter_func(array, origin=0, **kwargs)
+
+        # output has origin shift on last axis relative to output0, so
+        # expect shifted arrays to be equal.
+        if filter_func == ndimage.convolve:
+            # shift is in the opposite direction for convolve because it
+            # flips the weights array and negates the origin values.
+            xp_assert_equal(
+                output[:, :, :-origins[1]], output0[:, :, origins[1]:])
+        else:
+            xp_assert_equal(
+                output[:, :, origins[1]:], output0[:, :, :-origins[1]])
+
+
+    @pytest.mark.parametrize(
+        'filter_func, args',
+        [(ndimage.convolve, (np.ones((3, 3, 3)),)),  # args = (weights,)
+         (ndimage.correlate,(np.ones((3, 3, 3)),)),  # args = (weights,)
+         (ndimage.gaussian_filter, (1.0,)),      # args = (sigma,)
+         (ndimage.uniform_filter, (3,)),         # args = (size,)
+         (ndimage.minimum_filter, (3,)),         # args = (size,)
+         (ndimage.maximum_filter, (3,)),         # args = (size,)
+         (ndimage.median_filter, (3,)),          # args = (size,)
+         (ndimage.rank_filter, (2, 3)),          # args = (rank, size)
+         (ndimage.percentile_filter, (30, 3))])  # args = (percentile, size)
+    @pytest.mark.parametrize(
+        'axes', [(1.5,), (0, 1, 2, 3), (3,), (-4,)]
+    )
+    def test_filter_invalid_axes(self, filter_func, args, axes, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+        args = [
+            xp.asarray(arg) if isinstance(arg, np.ndarray) else arg
+            for arg in args
+        ]
+        if any(isinstance(ax, float) for ax in axes):
+            error_class = TypeError
+            match = "cannot be interpreted as an integer"
+        else:
+            error_class = ValueError
+            match = "out of range"
+        with pytest.raises(error_class, match=match):
+            filter_func(array, *args, axes=axes)
+
+    @pytest.mark.parametrize(
+        'filter_func, kwargs',
+        [(ndimage.convolve, {}),
+         (ndimage.correlate, {}),
+         (ndimage.minimum_filter, {}),
+         (ndimage.maximum_filter, {}),
+         (ndimage.median_filter, {}),
+         (ndimage.rank_filter, dict(rank=3)),
+         (ndimage.percentile_filter, dict(percentile=30))])
+    @pytest.mark.parametrize(
+        'axes', [(0, ), (1, 2), (0, 1, 2)]
+    )
+    @pytest.mark.parametrize('separable_footprint', [False, True])
+    def test_filter_invalid_footprint_ndim(self, filter_func, kwargs, axes,
+                                           separable_footprint, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+        # create a footprint with one too many dimensions
+        footprint = np.ones((3,) * (len(axes) + 1))
+        if not separable_footprint:
+            footprint[(0,) * footprint.ndim] = 0
+        footprint = xp.asarray(footprint)
+        if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter]
+            and separable_footprint):
+            match = "sequence argument must have length equal to input rank"
+        elif filter_func in [ndimage.convolve, ndimage.correlate]:
+            match = re.escape(f"weights.ndim ({footprint.ndim}) must match "
+                              f"len(axes) ({len(axes)})")
+        else:
+            match = re.escape(f"footprint.ndim ({footprint.ndim}) must match "
+                              f"len(axes) ({len(axes)})")
+        if filter_func in [ndimage.convolve, ndimage.correlate]:
+            kwargs["weights"] = footprint
+        else:
+            kwargs["footprint"] = footprint
+        with pytest.raises(RuntimeError, match=match):
+            filter_func(array, axes=axes, **kwargs)
+
+    @pytest.mark.parametrize('n_mismatch', [1, 3])
+    @pytest.mark.parametrize('filter_func, kwargs, key, val',
+                             _cases_axes_tuple_length_mismatch())
+    def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func,
+                                          kwargs, key, val, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        # Test for the intended RuntimeError when a kwargs has an invalid size
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+        axes = (0, 1)
+        kwargs = dict(**kwargs, axes=axes)
+        kwargs[key] = (val,) * n_mismatch
+        if filter_func in [ndimage.convolve, ndimage.correlate]:
+            kwargs["weights"] = xp.ones((5,) * len(axes))
+        err_msg = "sequence argument must have length equal to input rank"
+        with pytest.raises(RuntimeError, match=err_msg):
+            filter_func(array, **kwargs)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1)
+        output = ndimage.prewitt(array, 0)
+        assert_array_almost_equal(t, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt02(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1)
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.prewitt(array, 0, output)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt03(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp) and dtype in [xp.uint32, xp.uint64]:
+            pytest.xfail("uint UB? XXX")
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 0)
+        output = ndimage.prewitt(array, 1)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt04(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.prewitt(array, -1)
+        output = ndimage.prewitt(array, 1)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1)
+        output = ndimage.sobel(array, 0)
+        assert_array_almost_equal(t, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.",)
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel02(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1)
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.sobel(array, 0, output)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel03(self, dtype, xp):
+        if is_cupy(xp) and dtype in ["uint32", "uint64"]:
+            pytest.xfail("uint UB? XXX")
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 0)
+        output = xp.zeros(array.shape, dtype=dtype)
+        output = ndimage.sobel(array, 1)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel04(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.sobel(array, -1)
+        output = ndimage.sobel(array, 1)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_laplace01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0)
+        tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1)
+        output = ndimage.laplace(array)
+        assert_array_almost_equal(tmp1 + tmp2, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only",)
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_laplace02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0)
+        tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1)
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.laplace(array, output=output)
+        assert_array_almost_equal(tmp1 + tmp2, output)
+
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_gaussian_laplace01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0])
+        tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2])
+        output = ndimage.gaussian_laplace(array, 1.0)
+        assert_array_almost_equal(tmp1 + tmp2, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_gaussian_laplace02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0])
+        tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2])
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.gaussian_laplace(array, 1.0, output)
+        assert_array_almost_equal(tmp1 + tmp2, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_generic_laplace01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        def derivative2(input, axis, output, mode, cval, a, b):
+            sigma = np.asarray([a, b / 2.0])
+            order = [0] * input.ndim
+            order[axis] = 2
+            return ndimage.gaussian_filter(input, sigma, order,
+                                           output, mode, cval)
+
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = xp.zeros(array.shape, dtype=dtype)
+        tmp = ndimage.generic_laplace(array, derivative2,
+                                      extra_arguments=(1.0,),
+                                      extra_keywords={'b': 2.0})
+        ndimage.gaussian_laplace(array, 1.0, output)
+        assert_array_almost_equal(tmp, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_gaussian_gradient_magnitude01(self, dtype, xp):
+        is_int_dtype = dtype == "int32"
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0])
+        tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1])
+        output = ndimage.gaussian_gradient_magnitude(array, 1.0)
+        expected = tmp1 * tmp1 + tmp2 * tmp2
+
+        astype = array_namespace(expected).astype
+        expected_float = astype(expected, xp.float64) if is_int_dtype else expected
+        expected = astype(xp.sqrt(expected_float), dtype)
+        xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_gaussian_gradient_magnitude02(self, dtype, xp):
+        is_int_dtype = dtype == 'int32'
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0])
+        tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1])
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.gaussian_gradient_magnitude(array, 1.0, output)
+        expected = tmp1 * tmp1 + tmp2 * tmp2
+
+        astype = array_namespace(expected).astype
+        fl_expected = astype(expected, xp.float64) if is_int_dtype else expected
+
+        expected = astype(xp.sqrt(fl_expected), dtype)
+        xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+    def test_generic_gradient_magnitude01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=xp.float64)
+
+        def derivative(input, axis, output, mode, cval, a, b):
+            sigma = [a, b / 2.0]
+            order = [0] * input.ndim
+            order[axis] = 1
+            return ndimage.gaussian_filter(input, sigma, order, output, mode, cval)
+
+        tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0)
+        tmp2 = ndimage.generic_gradient_magnitude(
+            array, derivative, extra_arguments=(1.0,),
+            extra_keywords={'b': 2.0})
+        assert_array_almost_equal(tmp1, tmp2)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    def test_uniform01(self, xp):
+        array = xp.asarray([2, 4, 6])
+        size = 2
+        output = ndimage.uniform_filter1d(array, size, origin=-1)
+        assert_array_almost_equal(xp.asarray([3, 5, 6]), output)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    def test_uniform01_complex(self, xp):
+        array = xp.asarray([2 + 1j, 4 + 2j, 6 + 3j], dtype=xp.complex128)
+        size = 2
+        output = ndimage.uniform_filter1d(array, size, origin=-1)
+        assert_array_almost_equal(xp.real(output), xp.asarray([3., 5, 6]))
+        assert_array_almost_equal(xp.imag(output), xp.asarray([1.5, 2.5, 3]))
+
+    def test_uniform02(self, xp):
+        array = xp.asarray([1, 2, 3])
+        filter_shape = [0]
+        output = ndimage.uniform_filter(array, filter_shape)
+        assert_array_almost_equal(array, output)
+
+    def test_uniform03(self, xp):
+        array = xp.asarray([1, 2, 3])
+        filter_shape = [1]
+        output = ndimage.uniform_filter(array, filter_shape)
+        assert_array_almost_equal(array, output)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    def test_uniform04(self, xp):
+        array = xp.asarray([2, 4, 6])
+        filter_shape = [2]
+        output = ndimage.uniform_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([2, 3, 5]), output)
+
+    def test_uniform05(self, xp):
+        array = xp.asarray([])
+        filter_shape = [1]
+        output = ndimage.uniform_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([]), output)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_uniform06(self, dtype_array, dtype_output, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        filter_shape = [2, 2]
+        array = xp.asarray([[4, 8, 12],
+                            [16, 20, 24]], dtype=dtype_array)
+        output = ndimage.uniform_filter(
+            array, filter_shape, output=dtype_output)
+        assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output)
+        assert output.dtype.type == dtype_output
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    @pytest.mark.parametrize('dtype_array', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_uniform06_complex(self, dtype_array, dtype_output, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        filter_shape = [2, 2]
+        array = xp.asarray([[4, 8 + 5j, 12],
+                            [16, 20, 24]], dtype=dtype_array)
+        output = ndimage.uniform_filter(
+            array, filter_shape, output=dtype_output)
+        assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output.real)
+        assert output.dtype.type == dtype_output
+
+    def test_minimum_filter01(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        filter_shape = xp.asarray([2])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output)
+
+    def test_minimum_filter02(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        filter_shape = xp.asarray([3])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output)
+
+    def test_minimum_filter03(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        filter_shape = xp.asarray([2])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([3, 2, 2, 1, 1]), output)
+
+    def test_minimum_filter04(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        filter_shape = xp.asarray([3])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([2, 2, 1, 1, 1]), output)
+
+    def test_minimum_filter05(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        filter_shape = xp.asarray([2, 3])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 2, 1, 1, 1],
+                                              [5, 3, 3, 1, 1]]), output)
+
+    @skip_xp_backends("jax.numpy", reason="assignment destination is read-only")
+    def test_minimum_filter05_overlap(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        filter_shape = xp.asarray([2, 3])
+        ndimage.minimum_filter(array, filter_shape, output=array)
+        assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 2, 1, 1, 1],
+                                              [5, 3, 3, 1, 1]]), array)
+
+    def test_minimum_filter06(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 1, 1], [1, 1, 1]])
+        output = ndimage.minimum_filter(array, footprint=footprint)
+        assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 2, 1, 1, 1],
+                                              [5, 3, 3, 1, 1]]), output)
+        # separable footprint should allow mode sequence
+        output2 = ndimage.minimum_filter(array, footprint=footprint,
+                                         mode=['reflect', 'reflect'])
+        assert_array_almost_equal(output2, output)
+
+    def test_minimum_filter07(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.minimum_filter(array, footprint=footprint)
+        assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1]]), output)
+        with assert_raises(RuntimeError):
+            ndimage.minimum_filter(array, footprint=footprint,
+                                   mode=['reflect', 'constant'])
+
+    def test_minimum_filter08(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.minimum_filter(array, footprint=footprint, origin=-1)
+        assert_array_almost_equal(xp.asarray([[3, 1, 3, 1, 1],
+                                              [5, 3, 3, 1, 1],
+                                              [3, 3, 1, 1, 1]]), output)
+
+    def test_minimum_filter09(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.minimum_filter(array, footprint=footprint,
+                                        origin=[-1, 0])
+        assert_array_almost_equal(xp.asarray([[2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1],
+                                              [5, 3, 3, 1, 1]]), output)
+
+    def test_maximum_filter01(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        filter_shape = xp.asarray([2])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([1, 2, 3, 4, 5]), output)
+
+    def test_maximum_filter02(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        filter_shape = xp.asarray([3])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([2, 3, 4, 5, 5]), output)
+
+    def test_maximum_filter03(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        filter_shape = xp.asarray([2])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+
+    def test_maximum_filter04(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        filter_shape = xp.asarray([3])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([3, 5, 5, 5, 4]), output)
+
+    def test_maximum_filter05(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        filter_shape = xp.asarray([2, 3])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+                                              [7, 9, 9, 9, 5],
+                                              [8, 9, 9, 9, 7]]), output)
+
+    def test_maximum_filter06(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 1, 1], [1, 1, 1]])
+        output = ndimage.maximum_filter(array, footprint=footprint)
+        assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+                                              [7, 9, 9, 9, 5],
+                                              [8, 9, 9, 9, 7]]), output)
+        # separable footprint should allow mode sequence
+        output2 = ndimage.maximum_filter(array, footprint=footprint,
+                                         mode=['reflect', 'reflect'])
+        assert_array_almost_equal(output2, output)
+
+    def test_maximum_filter07(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.maximum_filter(array, footprint=footprint)
+        assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+                                              [7, 7, 9, 9, 5],
+                                              [7, 9, 8, 9, 7]]), output)
+        # non-separable footprint should not allow mode sequence
+        with assert_raises(RuntimeError):
+            ndimage.maximum_filter(array, footprint=footprint,
+                                   mode=['reflect', 'reflect'])
+
+    def test_maximum_filter08(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.maximum_filter(array, footprint=footprint, origin=-1)
+        assert_array_almost_equal(xp.asarray([[7, 9, 9, 5, 5],
+                                              [9, 8, 9, 7, 5],
+                                              [8, 8, 7, 7, 7]]), output)
+
+    def test_maximum_filter09(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.maximum_filter(array, footprint=footprint,
+                                        origin=[-1, 0])
+        assert_array_almost_equal(xp.asarray([[7, 7, 9, 9, 5],
+                                              [7, 9, 8, 9, 7],
+                                              [8, 8, 8, 7, 7]]), output)
+
+    @pytest.mark.parametrize(
+        'axes', tuple(itertools.combinations(range(-3, 3), 2))
+    )
+    @pytest.mark.parametrize(
+        'filter_func, kwargs',
+        [(ndimage.minimum_filter, {}),
+         (ndimage.maximum_filter, {}),
+         (ndimage.median_filter, {}),
+         (ndimage.rank_filter, dict(rank=3)),
+         (ndimage.percentile_filter, dict(percentile=60))]
+    )
+    def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        array = xp.arange(6 * 8 * 12, dtype=xp.float32)
+        array = xp.reshape(array, (6, 8, 12))
+        # use 2D triangular footprint because it is non-separable
+        footprint = xp.asarray(np.tri(5))
+        axes = np.asarray(axes)
+
+        if len(set(axes % array.ndim)) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError):
+                filter_func(array, footprint=footprint, axes=axes, **kwargs)
+            return
+        output = filter_func(array, footprint=footprint, axes=axes, **kwargs)
+
+        missing_axis = tuple(set(range(3)) - set(axes % array.ndim))[0]
+
+        expand_dims = array_namespace(footprint).expand_dims
+        footprint_3d = expand_dims(footprint, axis=missing_axis)
+        expected = filter_func(array, footprint=footprint_3d, **kwargs)
+        xp_assert_close(output, expected)
+
+    def test_rank01(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        output = ndimage.rank_filter(array, 1, size=2)
+        xp_assert_equal(array, output)
+        output = ndimage.percentile_filter(array, 100, size=2)
+        xp_assert_equal(array, output)
+        output = ndimage.median_filter(array, 2)
+        xp_assert_equal(array, output)
+
+    def test_rank02(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        output = ndimage.rank_filter(array, 1, size=[3])
+        xp_assert_equal(array, output)
+        output = ndimage.percentile_filter(array, 50, size=3)
+        xp_assert_equal(array, output)
+        output = ndimage.median_filter(array, (3,))
+        xp_assert_equal(array, output)
+
+    def test_rank03(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        output = ndimage.rank_filter(array, 1, size=[2])
+        xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+        output = ndimage.percentile_filter(array, 100, size=2)
+        xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+
+    def test_rank04(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        expected = xp.asarray([3, 3, 2, 4, 4])
+        output = ndimage.rank_filter(array, 1, size=3)
+        xp_assert_equal(expected, output)
+        output = ndimage.percentile_filter(array, 50, size=3)
+        xp_assert_equal(expected, output)
+        output = ndimage.median_filter(array, size=3)
+        xp_assert_equal(expected, output)
+
+    def test_rank05(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        expected = xp.asarray([3, 3, 2, 4, 4])
+        output = ndimage.rank_filter(array, -2, size=3)
+        xp_assert_equal(expected, output)
+
+    def test_rank06(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+        expected = [[2, 2, 1, 1, 1],
+                    [3, 3, 2, 1, 1],
+                    [5, 5, 3, 3, 1]]
+        expected = xp.asarray(expected)
+        output = ndimage.rank_filter(array, 1, size=[2, 3])
+        xp_assert_equal(expected, output)
+        output = ndimage.percentile_filter(array, 17, size=(2, 3))
+        xp_assert_equal(expected, output)
+
+    @skip_xp_backends("jax.numpy",
+        reason="assignment destination is read-only",
+    )
+    def test_rank06_overlap(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8406")
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+
+        asarray = array_namespace(array).asarray
+        array_copy = asarray(array, copy=True)
+        expected = [[2, 2, 1, 1, 1],
+                    [3, 3, 2, 1, 1],
+                    [5, 5, 3, 3, 1]]
+        expected = xp.asarray(expected)
+        ndimage.rank_filter(array, 1, size=[2, 3], output=array)
+        xp_assert_equal(expected, array)
+
+        ndimage.percentile_filter(array_copy, 17, size=(2, 3),
+                                  output=array_copy)
+        xp_assert_equal(expected, array_copy)
+
+    def test_rank07(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+        expected = [[3, 5, 5, 5, 4],
+                    [5, 5, 7, 5, 4],
+                    [6, 8, 8, 7, 5]]
+        expected = xp.asarray(expected)
+        output = ndimage.rank_filter(array, -2, size=[2, 3])
+        xp_assert_equal(expected, output)
+
+    def test_rank08(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+        expected = [[3, 3, 2, 4, 4],
+                    [5, 5, 5, 4, 4],
+                    [5, 6, 7, 5, 5]]
+        expected = xp.asarray(expected)
+        output = ndimage.percentile_filter(array, 50.0, size=(2, 3))
+        xp_assert_equal(expected, output)
+        output = ndimage.rank_filter(array, 3, size=(2, 3))
+        xp_assert_equal(expected, output)
+        output = ndimage.median_filter(array, size=(2, 3))
+        xp_assert_equal(expected, output)
+
+        # non-separable: does not allow mode sequence
+        with assert_raises(RuntimeError):
+            ndimage.percentile_filter(array, 50.0, size=(2, 3),
+                                      mode=['reflect', 'constant'])
+        with assert_raises(RuntimeError):
+            ndimage.rank_filter(array, 3, size=(2, 3), mode=['reflect']*2)
+        with assert_raises(RuntimeError):
+            ndimage.median_filter(array, size=(2, 3), mode=['reflect']*2)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank09(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[3, 3, 2, 4, 4],
+                    [3, 5, 2, 5, 1],
+                    [5, 5, 8, 3, 5]]
+        expected = xp.asarray(expected)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 1, footprint=footprint)
+        assert_array_almost_equal(expected, output)
+        output = ndimage.percentile_filter(array, 35, footprint=footprint)
+        assert_array_almost_equal(expected, output)
+
+    def test_rank10(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        expected = [[2, 2, 1, 1, 1],
+                    [2, 3, 1, 3, 1],
+                    [5, 5, 3, 3, 1]]
+        expected = xp.asarray(expected)
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.rank_filter(array, 0, footprint=footprint)
+        xp_assert_equal(expected, output)
+        output = ndimage.percentile_filter(array, 0.0, footprint=footprint)
+        xp_assert_equal(expected, output)
+
+    def test_rank11(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        expected = [[3, 5, 5, 5, 4],
+                    [7, 7, 9, 9, 5],
+                    [7, 9, 8, 9, 7]]
+        expected = xp.asarray(expected)
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.rank_filter(array, -1, footprint=footprint)
+        xp_assert_equal(expected, output)
+        output = ndimage.percentile_filter(array, 100.0, footprint=footprint)
+        xp_assert_equal(expected, output)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank12(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        expected = [[3, 3, 2, 4, 4],
+                    [3, 5, 2, 5, 1],
+                    [5, 5, 8, 3, 5]]
+        expected = xp.asarray(expected, dtype=dtype)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 1, footprint=footprint)
+        assert_array_almost_equal(expected, output)
+        output = ndimage.percentile_filter(array, 50.0,
+                                           footprint=footprint)
+        xp_assert_equal(expected, output)
+        output = ndimage.median_filter(array, footprint=footprint)
+        xp_assert_equal(expected, output)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank13(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        expected = [[5, 2, 5, 1, 1],
+                    [5, 8, 3, 5, 5],
+                    [6, 6, 5, 5, 5]]
+        expected = xp.asarray(expected, dtype=dtype)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 1, footprint=footprint,
+                                     origin=-1)
+        xp_assert_equal(expected, output)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank14(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        expected = [[3, 5, 2, 5, 1],
+                    [5, 5, 8, 3, 5],
+                    [5, 6, 6, 5, 5]]
+        expected = xp.asarray(expected, dtype=dtype)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 1, footprint=footprint,
+                                     origin=[-1, 0])
+        xp_assert_equal(expected, output)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank15(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        expected = [[2, 3, 1, 4, 1],
+                    [5, 3, 7, 1, 1],
+                    [5, 5, 3, 3, 3]]
+        expected = xp.asarray(expected, dtype=dtype)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 0, footprint=footprint,
+                                     origin=[-1, 0])
+        xp_assert_equal(expected, output)
+
+    def test_rank16(self, xp):
+        # test that lists are accepted and interpreted as numpy arrays
+        array = [3, 2, 5, 1, 4]
+        # expected values are: median(3, 2, 5) = 3, median(2, 5, 1) = 2, etc
+        expected = np.asarray([3, 3, 2, 4, 4])
+        output = ndimage.rank_filter(array, -2, size=3)
+        xp_assert_equal(expected, output)
+
+    def test_rank17(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        if not hasattr(array, 'flags'):
+            return
+        array.flags.writeable = False
+        expected = xp.asarray([3, 3, 2, 4, 4])
+        output = ndimage.rank_filter(array, -2, size=3)
+        xp_assert_equal(expected, output)
+
+    def test_rank18(self, xp):
+        # module 'array_api_strict' has no attribute 'float16'
+        tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64',
+                         'uint8', 'uint16', 'uint32', 'uint64']
+        for dtype_str in tested_dtypes:
+            dtype = getattr(xp, dtype_str)
+            x = xp.asarray([3, 2, 5, 1, 4], dtype=dtype)
+            y = ndimage.rank_filter(x, -2, size=3)
+            assert y.dtype == x.dtype
+
+    def test_rank19(self, xp):
+        # module 'array_api_strict' has no attribute 'float16'
+        tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64',
+                         'uint8', 'uint16', 'uint32', 'uint64']
+        for dtype_str in tested_dtypes:
+            dtype = getattr(xp, dtype_str)
+            x = xp.asarray([[3, 2, 5, 1, 4], [3, 2, 5, 1, 4]], dtype=dtype)
+            y = ndimage.rank_filter(x, -2, size=3)
+            assert y.dtype == x.dtype
+
+    @skip_xp_backends(np_only=True, reason="off-by-ones on alt backends")
+    @pytest.mark.parametrize('dtype', types)
+    def test_generic_filter1d01(self, dtype, xp):
+        weights = xp.asarray([1.1, 2.2, 3.3])
+
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not support extra_arguments")
+
+        def _filter_func(input, output, fltr, total):
+            fltr = fltr / total
+            for ii in range(input.shape[0] - 2):
+                output[ii] = input[ii] * fltr[0]
+                output[ii] += input[ii + 1] * fltr[1]
+                output[ii] += input[ii + 2] * fltr[2]
+        a = np.arange(12, dtype=dtype).reshape(3, 4)
+        a = xp.asarray(a)
+        dtype = getattr(xp, dtype)
+
+        r1 = ndimage.correlate1d(a, weights / xp.sum(weights), 0, origin=-1)
+        r2 = ndimage.generic_filter1d(
+            a, _filter_func, 3, axis=0, origin=-1,
+            extra_arguments=(weights,),
+            extra_keywords={'total': xp.sum(weights)})
+        assert_array_almost_equal(r1, r2)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_generic_filter01(self, dtype, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not support extra_arguments")
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype_str = dtype
+        dtype = getattr(xp, dtype_str)
+
+        filter_ = xp.asarray([[1.0, 2.0], [3.0, 4.0]])
+        footprint = xp.asarray([[1.0, 0.0], [0.0, 1.0]])
+        cf = xp.asarray([1., 4.])
+
+        def _filter_func(buffer, weights, total=1.0):
+            weights = np.asarray(cf) / np.asarray(total)
+            return np.sum(buffer * weights)
+
+        a = np.arange(12, dtype=dtype_str).reshape(3, 4)
+        a = xp.asarray(a)
+        r1 = ndimage.correlate(a, filter_ * footprint)
+        if dtype_str in float_types:
+            r1 /= 5
+        else:
+            r1 //= 5
+        r2 = ndimage.generic_filter(
+            a, _filter_func, footprint=footprint, extra_arguments=(cf,),
+            extra_keywords={'total': xp.sum(cf)})
+        assert_array_almost_equal(r1, r2)
+
+        # generic_filter doesn't allow mode sequence
+        with assert_raises(RuntimeError):
+            r2 = ndimage.generic_filter(
+                a, _filter_func, mode=['reflect', 'reflect'],
+                footprint=footprint, extra_arguments=(cf,),
+                extra_keywords={'total': xp.sum(cf)})
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [1, 1, 2]),
+         ('wrap', [3, 1, 2]),
+         ('reflect', [1, 1, 2]),
+         ('mirror', [2, 1, 2]),
+         ('constant', [0, 1, 2])]
+    )
+    def test_extend01(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([1, 0])
+        output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [1, 1, 1]),
+         ('wrap', [3, 1, 2]),
+         ('reflect', [3, 3, 2]),
+         ('mirror', [1, 2, 3]),
+         ('constant', [0, 0, 0])]
+    )
+    def test_extend02(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([1, 0, 0, 0, 0, 0, 0, 0])
+        output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [2, 3, 3]),
+         ('wrap', [2, 3, 1]),
+         ('reflect', [2, 3, 3]),
+         ('mirror', [2, 3, 2]),
+         ('constant', [2, 3, 0])]
+    )
+    def test_extend03(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([0, 0, 1])
+        output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [3, 3, 3]),
+         ('wrap', [2, 3, 1]),
+         ('reflect', [2, 1, 1]),
+         ('mirror', [1, 2, 3]),
+         ('constant', [0, 0, 0])]
+    )
+    def test_extend04(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+        output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]),
+         ('wrap', [[9, 7, 8], [3, 1, 2], [6, 4, 5]]),
+         ('reflect', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]),
+         ('mirror', [[5, 4, 5], [2, 1, 2], [5, 4, 5]]),
+         ('constant', [[0, 0, 0], [0, 1, 2], [0, 4, 5]])]
+    )
+    def test_extend05(self, mode, expected_value, xp):
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6],
+                            [7, 8, 9]])
+        weights = xp.asarray([[1, 0], [0, 0]])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]),
+         ('wrap', [[5, 6, 4], [8, 9, 7], [2, 3, 1]]),
+         ('reflect', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]),
+         ('mirror', [[5, 6, 5], [8, 9, 8], [5, 6, 5]]),
+         ('constant', [[5, 6, 0], [8, 9, 0], [0, 0, 0]])]
+    )
+    def test_extend06(self, mode, expected_value, xp):
+        array = xp.asarray([[1, 2, 3],
+                          [4, 5, 6],
+                          [7, 8, 9]])
+        weights = xp.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [3, 3, 3]),
+         ('wrap', [2, 3, 1]),
+         ('reflect', [2, 1, 1]),
+         ('mirror', [1, 2, 3]),
+         ('constant', [0, 0, 0])]
+    )
+    def test_extend07(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [[3], [3], [3]]),
+         ('wrap', [[2], [3], [1]]),
+         ('reflect', [[2], [1], [1]]),
+         ('mirror', [[1], [2], [3]]),
+         ('constant', [[0], [0], [0]])]
+    )
+    def test_extend08(self, mode, expected_value, xp):
+        array = xp.asarray([[1], [2], [3]])
+        weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [3, 3, 3]),
+         ('wrap', [2, 3, 1]),
+         ('reflect', [2, 1, 1]),
+         ('mirror', [1, 2, 3]),
+         ('constant', [0, 0, 0])]
+    )
+    def test_extend09(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [[3], [3], [3]]),
+         ('wrap', [[2], [3], [1]]),
+         ('reflect', [[2], [1], [1]]),
+         ('mirror', [[1], [2], [3]]),
+         ('constant', [[0], [0], [0]])]
+    )
+    def test_extend10(self, mode, expected_value, xp):
+        array = xp.asarray([[1], [2], [3]])
+        weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+
+def test_ticket_701(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy raises a TypeError.")
+
+    # Test generic filter sizes
+    arr = xp.asarray(np.arange(4).reshape(2, 2))
+    def func(x):
+        return np.min(x)  # NB: np.min not xp.min for callables
+    res = ndimage.generic_filter(arr, func, size=(1, 1))
+    # The following raises an error unless ticket 701 is fixed
+    res2 = ndimage.generic_filter(arr, func, size=1)
+    xp_assert_equal(res, res2)
+
+
+def test_gh_5430():
+    # 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.
+    sigma = np.int32(1)
+    out = ndimage._ni_support._normalize_sequence(sigma, 1)
+    assert out == [sigma]
+    sigma = np.int64(1)
+    out = ndimage._ni_support._normalize_sequence(sigma, 1)
+    assert out == [sigma]
+    # This worked before; make sure it still works
+    sigma = 1
+    out = ndimage._ni_support._normalize_sequence(sigma, 1)
+    assert out == [sigma]
+    # This worked before; make sure it still works
+    sigma = [1, 1]
+    out = ndimage._ni_support._normalize_sequence(sigma, 2)
+    assert out == sigma
+    # Also include the OPs original example to make sure we fixed the issue
+    x = np.random.normal(size=(256, 256))
+    perlin = np.zeros_like(x)
+    for i in 2**np.arange(6):
+        perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2
+    # This also fixes gh-4106, show that the OPs example now runs.
+    x = np.int64(21)
+    ndimage._ni_support._normalize_sequence(x, 0)
+
+
+def test_gaussian_kernel1d(xp):
+    if is_cupy(xp):
+        pytest.skip("This test tests a private scipy utility.")
+    radius = 10
+    sigma = 2
+    sigma2 = sigma * sigma
+    x = np.arange(-radius, radius + 1, dtype=np.float64)
+    x = xp.asarray(x)
+    phi_x = xp.exp(-0.5 * x * x / sigma2)
+    phi_x /= xp.sum(phi_x)
+    xp_assert_close(phi_x,
+                    xp.asarray(_gaussian_kernel1d(sigma, 0, radius)))
+    xp_assert_close(-phi_x * x / sigma2,
+                    xp.asarray(_gaussian_kernel1d(sigma, 1, radius)))
+    xp_assert_close(phi_x * (x * x / sigma2 - 1) / sigma2,
+                    xp.asarray(_gaussian_kernel1d(sigma, 2, radius)))
+    xp_assert_close(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2),
+                    xp.asarray(_gaussian_kernel1d(sigma, 3, radius)))
+
+
+def test_orders_gauss(xp):
+    # Check order inputs to Gaussians
+    arr = xp.zeros((1,))
+    xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=0), xp.asarray([0.]))
+    xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=3), xp.asarray([0.]))
+    assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1)
+    xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0),
+                    xp.asarray([0.]))
+    xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3),
+                    xp.asarray([0.]))
+    assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1)
+
+
+def test_valid_origins(xp):
+    """Regression test for #1311."""
+    if is_cupy(xp):
+        pytest.xfail("CuPy raises a TypeError.")
+
+    def func(x):
+        return xp.mean(x)
+    data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64)
+    assert_raises(ValueError, ndimage.generic_filter, data, func, size=3,
+                  origin=2)
+    assert_raises(ValueError, ndimage.generic_filter1d, data, func,
+                  filter_size=3, origin=2)
+    assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3,
+                  origin=2)
+
+    for filter in [ndimage.uniform_filter, ndimage.minimum_filter,
+                   ndimage.maximum_filter, ndimage.maximum_filter1d,
+                   ndimage.median_filter, ndimage.minimum_filter1d]:
+        # This should work, since for size == 3, the valid range for origin is
+        # -1 to 1.
+        list(filter(data, 3, origin=-1))
+        list(filter(data, 3, origin=1))
+        # Just check this raises an error instead of silently accepting or
+        # segfaulting.
+        assert_raises(ValueError, filter, data, 3, origin=2)
+
+
+def test_bad_convolve_and_correlate_origins(xp):
+    """Regression test for gh-822."""
+    # Before gh-822 was fixed, these would generate seg. faults or
+    # other crashes on many system.
+    assert_raises(ValueError, ndimage.correlate1d,
+                  [0, 1, 2, 3, 4, 5], [1, 1, 2, 0], origin=2)
+    assert_raises(ValueError, ndimage.correlate,
+                  [0, 1, 2, 3, 4, 5], [0, 1, 2], origin=[2])
+    assert_raises(ValueError, ndimage.correlate,
+                  xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, 1])
+
+    assert_raises(ValueError, ndimage.convolve1d,
+                  xp.arange(10), xp.ones(3), origin=-2)
+    assert_raises(ValueError, ndimage.convolve,
+                  xp.arange(10), xp.ones(3), origin=[-2])
+    assert_raises(ValueError, ndimage.convolve,
+                  xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, -2])
+
+@skip_xp_backends("cupy",
+                  reason="https://github.com/cupy/cupy/pull/8430",
+)
+def test_multiple_modes(xp):
+    # Test that the filters with multiple mode capabilities for different
+    # dimensions give the same result as applying a single mode.
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    mode1 = 'reflect'
+    mode2 = ['reflect', 'reflect']
+
+    xp_assert_equal(ndimage.gaussian_filter(arr, 1, mode=mode1),
+                 ndimage.gaussian_filter(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.prewitt(arr, mode=mode1),
+                 ndimage.prewitt(arr, mode=mode2))
+    xp_assert_equal(ndimage.sobel(arr, mode=mode1),
+                 ndimage.sobel(arr, mode=mode2))
+    xp_assert_equal(ndimage.laplace(arr, mode=mode1),
+                 ndimage.laplace(arr, mode=mode2))
+    xp_assert_equal(ndimage.gaussian_laplace(arr, 1, mode=mode1),
+                 ndimage.gaussian_laplace(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.maximum_filter(arr, size=5, mode=mode1),
+                 ndimage.maximum_filter(arr, size=5, mode=mode2))
+    xp_assert_equal(ndimage.minimum_filter(arr, size=5, mode=mode1),
+                 ndimage.minimum_filter(arr, size=5, mode=mode2))
+    xp_assert_equal(ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode1),
+                 ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.uniform_filter(arr, 5, mode=mode1),
+                 ndimage.uniform_filter(arr, 5, mode=mode2))
+
+
+@skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8430")
+@skip_xp_backends("jax.numpy", reason="output array is read-only.")
+def test_multiple_modes_sequentially(xp):
+    # Test that the filters with multiple mode capabilities for different
+    # dimensions give the same result as applying the filters with
+    # different modes sequentially
+    arr = xp.asarray([[1., 0., 0.],
+                    [1., 1., 0.],
+                    [0., 0., 0.]])
+
+    modes = ['reflect', 'wrap']
+
+    expected = ndimage.gaussian_filter1d(arr, 1, axis=0, mode=modes[0])
+    expected = ndimage.gaussian_filter1d(expected, 1, axis=1, mode=modes[1])
+    xp_assert_equal(expected,
+                 ndimage.gaussian_filter(arr, 1, mode=modes))
+
+    expected = ndimage.uniform_filter1d(arr, 5, axis=0, mode=modes[0])
+    expected = ndimage.uniform_filter1d(expected, 5, axis=1, mode=modes[1])
+    xp_assert_equal(expected,
+                 ndimage.uniform_filter(arr, 5, mode=modes))
+
+    expected = ndimage.maximum_filter1d(arr, size=5, axis=0, mode=modes[0])
+    expected = ndimage.maximum_filter1d(expected, size=5, axis=1,
+                                        mode=modes[1])
+    xp_assert_equal(expected,
+                 ndimage.maximum_filter(arr, size=5, mode=modes))
+
+    expected = ndimage.minimum_filter1d(arr, size=5, axis=0, mode=modes[0])
+    expected = ndimage.minimum_filter1d(expected, size=5, axis=1,
+                                        mode=modes[1])
+    xp_assert_equal(expected,
+                 ndimage.minimum_filter(arr, size=5, mode=modes))
+
+
+def test_multiple_modes_prewitt(xp):
+    # Test prewitt filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[1., -3., 2.],
+                           [1., -2., 1.],
+                           [1., -1., 0.]])
+
+    modes = ['reflect', 'wrap']
+
+    xp_assert_equal(expected,
+                 ndimage.prewitt(arr, mode=modes))
+
+
+def test_multiple_modes_sobel(xp):
+    # Test sobel filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[1., -4., 3.],
+                           [2., -3., 1.],
+                           [1., -1., 0.]])
+
+    modes = ['reflect', 'wrap']
+
+    xp_assert_equal(expected,
+                 ndimage.sobel(arr, mode=modes))
+
+
+def test_multiple_modes_laplace(xp):
+    # Test laplace filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[-2., 2., 1.],
+                           [-2., -3., 2.],
+                           [1., 1., 0.]])
+
+    modes = ['reflect', 'wrap']
+
+    xp_assert_equal(expected,
+                 ndimage.laplace(arr, mode=modes))
+
+
+def test_multiple_modes_gaussian_laplace(xp):
+    # Test gaussian_laplace filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[-0.28438687, 0.01559809, 0.19773499],
+                           [-0.36630503, -0.20069774, 0.07483620],
+                           [0.15849176, 0.18495566, 0.21934094]])
+
+    modes = ['reflect', 'wrap']
+
+    assert_almost_equal(expected,
+                        ndimage.gaussian_laplace(arr, 1, mode=modes))
+
+
+def test_multiple_modes_gaussian_gradient_magnitude(xp):
+    # Test gaussian_gradient_magnitude filter for multiple
+    # extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[0.04928965, 0.09745625, 0.06405368],
+                           [0.23056905, 0.14025305, 0.04550846],
+                           [0.19894369, 0.14950060, 0.06796850]])
+
+    modes = ['reflect', 'wrap']
+
+    calculated = ndimage.gaussian_gradient_magnitude(arr, 1, mode=modes)
+
+    assert_almost_equal(expected, calculated)
+
+@skip_xp_backends("cupy",
+                  reason="https://github.com/cupy/cupy/pull/8430",
+)
+def test_multiple_modes_uniform(xp):
+    # Test uniform filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[0.32, 0.40, 0.48],
+                           [0.20, 0.28, 0.32],
+                           [0.28, 0.32, 0.40]])
+
+    modes = ['reflect', 'wrap']
+
+    assert_almost_equal(expected,
+                        ndimage.uniform_filter(arr, 5, mode=modes))
+
+
+def _count_nonzero(arr):
+    # XXX: a simplified count_nonzero replacement; replace once
+    # https://github.com/data-apis/array-api/pull/803/ is in
+
+    # this assumes arr.dtype == xp.bool
+    xp = array_namespace(arr)
+    return xp.sum(xp.astype(arr, xp.int8))
+
+
+def test_gaussian_truncate(xp):
+    # Test that Gaussian filters can be truncated at different widths.
+    # These tests only check that the result has the expected number
+    # of nonzero elements.
+    arr = np.zeros((100, 100), dtype=np.float64)
+    arr[50, 50] = 1
+    arr = xp.asarray(arr)
+    num_nonzeros_2 = _count_nonzero(ndimage.gaussian_filter(arr, 5, truncate=2) > 0)
+    assert num_nonzeros_2 == 21**2
+
+    num_nonzeros_5 = _count_nonzero(
+        ndimage.gaussian_filter(arr, 5, truncate=5) > 0
+    )
+    assert num_nonzeros_5 == 51**2
+
+    nnz_kw = {'as_tuple': True} if is_torch(xp) else {}
+
+    # Test truncate when sigma is a sequence.
+    f = ndimage.gaussian_filter(arr, [0.5, 2.5], truncate=3.5)
+    fpos = f > 0
+    n0 = _count_nonzero(xp.any(fpos, axis=0))
+    assert n0 == 19
+    n1 = _count_nonzero(xp.any(fpos, axis=1))
+    assert n1 == 5
+
+    # Test gaussian_filter1d.
+    x = np.zeros(51)
+    x[25] = 1
+    x = xp.asarray(x)
+    f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5)
+    n = _count_nonzero(f > 0)
+    assert n == 15
+
+    # Test gaussian_laplace
+    y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5)
+    nonzero_indices = xp.nonzero(y != 0, **nnz_kw)[0]
+
+    n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+    assert n == 15
+
+    # Test gaussian_gradient_magnitude
+    y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5)
+    nonzero_indices = xp.nonzero(y != 0, **nnz_kw)[0]
+    n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+    assert n == 15
+
+
+def test_gaussian_radius(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8402")
+
+    # Test that Gaussian filters with radius argument produce the same
+    # results as the filters with corresponding truncate argument.
+    # radius = int(truncate * sigma + 0.5)
+    # Test gaussian_filter1d
+    x = np.zeros(7)
+    x[3] = 1
+    x = xp.asarray(x)
+    f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5)
+    f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3)
+    xp_assert_equal(f1, f2)
+
+    # Test gaussian_filter when sigma is a number.
+    a = np.zeros((9, 9))
+    a[4, 4] = 1
+    a = xp.asarray(a)
+    f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5)
+    f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2)
+    xp_assert_equal(f1, f2)
+
+    # Test gaussian_filter when sigma is a sequence.
+    a = np.zeros((50, 50))
+    a[25, 25] = 1
+    a = xp.asarray(a)
+    f1 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], truncate=3.5)
+    f2 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], radius=[2, 9])
+    xp_assert_equal(f1, f2)
+
+
+def test_gaussian_radius_invalid(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8402")
+
+    # radius must be a nonnegative integer
+    with assert_raises(ValueError):
+        ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=-1)
+    with assert_raises(ValueError):
+        ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=1.1)
+
+
+@skip_xp_backends("jax.numpy", reason="output array is read-only")
+class TestThreading:
+    def check_func_thread(self, n, fun, args, out):
+        from threading import Thread
+        thrds = [Thread(target=fun, args=args, kwargs={'output': out[x, ...]})
+                 for x in range(n)]
+        [t.start() for t in thrds]
+        [t.join() for t in thrds]
+
+    def check_func_serial(self, n, fun, args, out):
+        for i in range(n):
+            fun(*args, output=out[i, ...])
+
+    def test_correlate1d(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = np.random.randn(5000)
+        os = np.empty((4, d.size))
+        ot = np.empty_like(os)
+        d = xp.asarray(d)
+        os = xp.asarray(os)
+        ot = xp.asarray(ot)
+        k = xp.arange(5)
+        self.check_func_serial(4, ndimage.correlate1d, (d, k), os)
+        self.check_func_thread(4, ndimage.correlate1d, (d, k), ot)
+        xp_assert_equal(os, ot)
+
+    def test_correlate(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = xp.asarray(np.random.randn(500, 500))
+        k = xp.asarray(np.random.randn(10, 10))
+        os = xp.empty([4] + list(d.shape))
+        ot = xp.empty_like(os)
+        self.check_func_serial(4, ndimage.correlate, (d, k), os)
+        self.check_func_thread(4, ndimage.correlate, (d, k), ot)
+        xp_assert_equal(os, ot)
+
+    def test_median_filter(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = xp.asarray(np.random.randn(500, 500))
+        os = xp.empty([4] + list(d.shape))
+        ot = xp.empty_like(os)
+        self.check_func_serial(4, ndimage.median_filter, (d, 3), os)
+        self.check_func_thread(4, ndimage.median_filter, (d, 3), ot)
+        xp_assert_equal(os, ot)
+
+    def test_uniform_filter1d(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = np.random.randn(5000)
+        os = np.empty((4, d.size))
+        ot = np.empty_like(os)
+        d = xp.asarray(d)
+        os = xp.asarray(os)
+        ot = xp.asarray(ot)
+        self.check_func_serial(4, ndimage.uniform_filter1d, (d, 5), os)
+        self.check_func_thread(4, ndimage.uniform_filter1d, (d, 5), ot)
+        xp_assert_equal(os, ot)
+
+    def test_minmax_filter(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = xp.asarray(np.random.randn(500, 500))
+        os = xp.empty([4] + list(d.shape))
+        ot = xp.empty_like(os)
+        self.check_func_serial(4, ndimage.maximum_filter, (d, 3), os)
+        self.check_func_thread(4, ndimage.maximum_filter, (d, 3), ot)
+        xp_assert_equal(os, ot)
+        self.check_func_serial(4, ndimage.minimum_filter, (d, 3), os)
+        self.check_func_thread(4, ndimage.minimum_filter, (d, 3), ot)
+        xp_assert_equal(os, ot)
+
+
+def test_minmaximum_filter1d(xp):
+    # Regression gh-3898
+    in_ = xp.arange(10)
+    out = ndimage.minimum_filter1d(in_, 1)
+    xp_assert_equal(in_, out)
+    out = ndimage.maximum_filter1d(in_, 1)
+    xp_assert_equal(in_, out)
+    # Test reflect
+    out = ndimage.minimum_filter1d(in_, 5, mode='reflect')
+    xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out)
+    out = ndimage.maximum_filter1d(in_, 5, mode='reflect')
+    xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+    # Test constant
+    out = ndimage.minimum_filter1d(in_, 5, mode='constant', cval=-1)
+    xp_assert_equal(xp.asarray([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1]), out)
+    out = ndimage.maximum_filter1d(in_, 5, mode='constant', cval=10)
+    xp_assert_equal(xp.asarray([10, 10, 4, 5, 6, 7, 8, 9, 10, 10]), out)
+    # Test nearest
+    out = ndimage.minimum_filter1d(in_, 5, mode='nearest')
+    xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out)
+    out = ndimage.maximum_filter1d(in_, 5, mode='nearest')
+    xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+    # Test wrap
+    out = ndimage.minimum_filter1d(in_, 5, mode='wrap')
+    xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 0, 0]), out)
+    out = ndimage.maximum_filter1d(in_, 5, mode='wrap')
+    xp_assert_equal(xp.asarray([9, 9, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+
+
+def test_uniform_filter1d_roundoff_errors(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8401")
+    # gh-6930
+    in_ = np.repeat([0, 1, 0], [9, 9, 9])
+    in_ = xp.asarray(in_)
+
+    for filter_size in range(3, 10):
+        out = ndimage.uniform_filter1d(in_, filter_size)
+        xp_assert_equal(xp.sum(out), xp.asarray(10 - filter_size), check_0d=False)
+
+
+def test_footprint_all_zeros(xp):
+    # regression test for gh-6876: footprint of all zeros segfaults
+    arr = xp.asarray(np.random.randint(0, 100, (100, 100)))
+    kernel = xp.asarray(np.zeros((3, 3), dtype=bool))
+    with assert_raises(ValueError):
+        ndimage.maximum_filter(arr, footprint=kernel)
+
+
+def test_gaussian_filter(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not raise")
+
+    if not hasattr(xp, "float16"):
+        pytest.xfail(f"{xp} does not have float16")
+
+    # Test gaussian filter with xp.float16
+    # gh-8207
+    data = xp.asarray([1], dtype=xp.float16)
+    sigma = 1.0
+    with assert_raises(RuntimeError):
+        ndimage.gaussian_filter(data, sigma)
+
+
+def test_rank_filter_noninteger_rank(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not raise")
+
+    # regression test for issue 9388: ValueError for
+    # non integer rank when performing rank_filter
+    arr = xp.asarray(np.random.random((10, 20, 30)))
+    footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool))
+    assert_raises(TypeError, ndimage.rank_filter, arr, 0.5,
+                  footprint=footprint)
+
+
+def test_size_footprint_both_set(xp):
+    # test for input validation, expect user warning when
+    # size and footprint is set
+    with suppress_warnings() as sup:
+        sup.filter(UserWarning,
+                   "ignoring size because footprint is set")
+        arr = xp.asarray(np.random.random((10, 20, 30)))
+        footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool))
+        ndimage.rank_filter(
+            arr, 5, size=2, footprint=footprint
+        )
+
+
+@skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+def test_byte_order_median(xp):
+    """Regression test for #413: median_filter does not handle bytes orders."""
+    a = xp.arange(9, dtype='1 makes sense too
+     (3,
+      np.array([0.25266576, 0.30958242, 0.27894721, 0.27894721, 0.27894721, 0.30445588,
+                0.31442572, 0.30445588, 0.18015438, 0.14831921, 0.18015438, 0.25754605,
+                0.32910465, 0.25754605, 0.17736568, 0.17736568, 0.09089549, 0.22183391,
+                0.25266576, 0.30958242]),
+     ),
+     (15,
+      np.array([0.27894721, 0.25266576, 0.25266576, 0.25266576, 0.27894721, 0.27894721,
+                0.27894721, 0.27894721, 0.25754605, 0.25754605, 0.22183391, 0.22183391,
+                0.25266576, 0.25266576, 0.22183391, 0.22183391, 0.25266576, 0.25266576,
+                0.25754605, 0.25754605]),
+     ),
+])
+def test_gh_22250(filter_size, exp):
+    rng = np.random.default_rng(42)
+    image = np.zeros((20,))
+    noisy_image = image + 0.4 * rng.random(image.shape)
+    result = ndimage.median_filter(noisy_image, size=filter_size, mode='wrap')
+    assert_allclose(result, exp)
+
+
+def test_gh_22333():
+    x = np.array([272, 58, 67, 163, 463, 608, 87, 108, 1378])
+    expected = [58, 67, 87, 108, 163, 108, 108, 108, 87]
+    actual = ndimage.median_filter(x, size=9, mode='constant')
+    assert_array_equal(actual, expected)
+
+
+@given(x=npst.arrays(dtype=np.float64,
+                     shape=st.integers(min_value=1, max_value=1000)),
+       size=st.integers(min_value=1, max_value=50),
+       mode=st.sampled_from(["constant", "mirror", "wrap", "reflect",
+                             "nearest"]),
+      )
+def test_gh_22586_crash_property(x, size, mode):
+    # property-based test for median_filter resilience to hard crashing
+    ndimage.median_filter(x, size=size, mode=mode)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..be544eaab9ce00b2e9802cf8f9a4819c4f1d2731
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py
@@ -0,0 +1,189 @@
+import math
+import numpy as np
+
+from scipy._lib._array_api import (
+    xp_assert_equal,
+    assert_array_almost_equal,
+    assert_almost_equal,
+    is_cupy,
+)
+
+import pytest
+
+from scipy import ndimage
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+@skip_xp_backends('jax.numpy', reason="jax-ml/jax#23827")
+class TestNdimageFourier:
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+    def test_fourier_gaussian_real01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.rfft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.irfft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
+    def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.fft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.ifft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+    def test_fourier_uniform_real01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.rfft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.irfft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
+    def test_fourier_uniform_complex01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.fft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.ifft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)])
+    def test_fourier_shift_real01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
+        expected = xp.asarray(expected)
+
+        a = fft.rfft(expected, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_shift(a, [1, 1], shape[0], 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.irfft(a, n=shape[0], axis=0)
+        assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)])
+    def test_fourier_shift_complex01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
+        expected = xp.asarray(expected)
+
+        a = fft.fft(expected, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_shift(a, [1, 1], -1, 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.ifft(a, n=shape[0], axis=0)
+        assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec)
+        assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)])
+    def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.rfft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.irfft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)])
+    def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.fft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.ifft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    def test_fourier_ellipsoid_unimplemented_ndim(self, xp):
+        # arrays with ndim > 3 raise NotImplementedError
+        x = xp.ones((4, 6, 8, 10), dtype=xp.complex128)
+        with pytest.raises(NotImplementedError):
+            ndimage.fourier_ellipsoid(x, 3)
+
+    def test_fourier_ellipsoid_1d_complex(self, xp):
+        # expected result of 1d ellipsoid is the same as for fourier_uniform
+        for shape in [(32, ), (31, )]:
+            for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]):
+                x = xp.ones(shape, dtype=type_)
+                a = ndimage.fourier_ellipsoid(x, 5, -1, 0)
+                b = ndimage.fourier_uniform(x, 5, -1, 0)
+                assert_array_almost_equal(a, b, decimal=dec)
+
+    @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)])
+    @pytest.mark.parametrize('dtype', ["float32", "float64",
+                                       "complex64", "complex128"])
+    @pytest.mark.parametrize('test_func',
+                             [ndimage.fourier_ellipsoid,
+                              ndimage.fourier_gaussian,
+                              ndimage.fourier_uniform])
+    def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp):
+        if is_cupy(xp):
+           if (test_func.__name__ == "fourier_ellipsoid" and
+               math.prod(shape) == 0):
+               pytest.xfail(
+                   "CuPy's fourier_ellipsoid does not accept size==0 arrays"
+               )
+        dtype = getattr(xp, dtype)
+        a = xp.ones(shape, dtype=dtype)
+        b = test_func(a, 3)
+        xp_assert_equal(a, b)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..51e8441e244f46642a07102e297b4d72513514d0
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py
@@ -0,0 +1,1484 @@
+import sys
+
+import numpy as np
+from numpy.testing import suppress_warnings
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close,
+    assert_array_almost_equal,
+)
+from scipy._lib._array_api import is_cupy, is_jax, _asarray, array_namespace
+
+import pytest
+from pytest import raises as assert_raises
+import scipy.ndimage as ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+eps = 1e-12
+
+ndimage_to_numpy_mode = {
+    'mirror': 'reflect',
+    'reflect': 'symmetric',
+    'grid-mirror': 'symmetric',
+    'grid-wrap': 'wrap',
+    'nearest': 'edge',
+    'grid-constant': 'constant',
+}
+
+
+class TestBoundaries:
+
+    @skip_xp_backends("cupy", reason="CuPy does not have geometric_transform")
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]),
+         ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]),
+         ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]),
+         ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]),
+         ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]),
+         ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]),
+         ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])]
+    )
+    def test_boundaries(self, mode, expected_value, xp):
+        def shift(x):
+            return (x[0] + 0.5,)
+
+        data = xp.asarray([1, 2, 3, 4.])
+        xp_assert_equal(
+            ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
+                                        output_shape=(7,), order=1),
+            xp.asarray(expected_value))
+
+    @skip_xp_backends("cupy", reason="CuPy does not have geometric_transform")
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [1, 1, 2, 3]),
+         ('wrap', [3, 1, 2, 3]),
+         ('grid-wrap', [4, 1, 2, 3]),
+         ('mirror', [2, 1, 2, 3]),
+         ('reflect', [1, 1, 2, 3]),
+         ('constant', [-1, 1, 2, 3]),
+         ('grid-constant', [-1, 1, 2, 3])]
+    )
+    def test_boundaries2(self, mode, expected_value, xp):
+        def shift(x):
+            return (x[0] - 0.9,)
+
+        data = xp.asarray([1, 2, 3, 4])
+        xp_assert_equal(
+            ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
+                                        output_shape=(4,)),
+            xp.asarray(expected_value))
+
+    @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror',
+                                      'grid-wrap', 'grid-constant',
+                                      'nearest'])
+    @pytest.mark.parametrize('order', range(6))
+    def test_boundary_spline_accuracy(self, mode, order, xp):
+        """Tests based on examples from gh-2640"""
+        if (is_jax(xp) and
+            (mode not in ['mirror', 'reflect', 'constant', 'wrap', 'nearest']
+             or order > 1)
+        ):
+            pytest.xfail("Jax does not support grid- modes or order > 1")
+
+        np_data = np.arange(-6, 7, dtype=np.float64)
+        data = xp.asarray(np_data)
+        x = xp.asarray(np.linspace(-8, 15, num=1000))
+        newaxis = array_namespace(x).newaxis
+        y = ndimage.map_coordinates(data, x[newaxis, ...], order=order, mode=mode)
+
+        # compute expected value using explicit padding via np.pad
+        npad = 32
+        pad_mode = ndimage_to_numpy_mode.get(mode)
+        padded = xp.asarray(np.pad(np_data, npad, mode=pad_mode))
+        coords = xp.asarray(npad + x)[newaxis, ...]
+        expected = ndimage.map_coordinates(padded, coords, order=order, mode=mode)
+
+        atol = 1e-5 if mode == 'grid-constant' else 1e-12
+        xp_assert_close(y, expected, rtol=1e-7, atol=atol)
+
+
+@pytest.mark.parametrize('order', range(2, 6))
+@pytest.mark.parametrize('dtype', types)
+class TestSpline:
+
+    def test_spline01(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.spline_filter(data, order=order)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    def test_spline02(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([1], dtype=dtype)
+        out = ndimage.spline_filter(data, order=order)
+        assert_array_almost_equal(out, xp.asarray([1]))
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    def test_spline03(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.spline_filter(data, order, output=dtype)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    def test_spline04(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([4], dtype=dtype)
+        out = ndimage.spline_filter(data, order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
+
+    def test_spline05(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([4, 4], dtype=dtype)
+        out = ndimage.spline_filter(data, order=order)
+        expected = xp.asarray([[1, 1, 1, 1],
+                               [1, 1, 1, 1],
+                               [1, 1, 1, 1],
+                               [1, 1, 1, 1]])
+        assert_array_almost_equal(out, expected)
+
+
+@skip_xp_backends("cupy", reason="CuPy does not have geometric_transform")
+@pytest.mark.parametrize('order', range(0, 6))
+class TestGeometricTransform:
+
+    def test_geometric_transform01(self, order, xp):
+        data = xp.asarray([1])
+
+        def mapping(x):
+            return x
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
+
+    def test_geometric_transform02(self, order, xp):
+        data = xp.ones([4])
+
+        def mapping(x):
+            return x
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
+
+    def test_geometric_transform03(self, order, xp):
+        data = xp.ones([4])
+
+        def mapping(x):
+            return (x[0] - 1,)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1], dtype=out.dtype))
+
+    def test_geometric_transform04(self, order, xp):
+        data = xp.asarray([4, 1, 3, 2])
+
+        def mapping(x):
+            return (x[0] - 1,)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3], dtype=out.dtype))
+
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_geometric_transform05(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[1, 1, 1, 1],
+                           [1, 1, 1, 1],
+                           [1, 1, 1, 1]], dtype=dtype)
+        expected = xp.asarray([[0, 1, 1, 1],
+                               [0, 1, 1, 1],
+                               [0, 1, 1, 1]], dtype=dtype)
+
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+
+        def mapping(x):
+            return (x[0], x[1] - 1)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform06(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+
+        def mapping(x):
+            return (x[0], x[1] - 1)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        expected = xp.asarray([[0, 4, 1, 3],
+                               [0, 7, 6, 8],
+                               [0, 3, 5, 3]], dtype=out.dtype)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform07(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+
+        def mapping(x):
+            return (x[0] - 1, x[1])
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [4, 1, 3, 2],
+                               [7, 6, 8, 5]], dtype=out.dtype)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform08(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+
+        def mapping(x):
+            return (x[0] - 1, x[1] - 1)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 4, 1, 3],
+                               [0, 7, 6, 8]], dtype=out.dtype)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform10(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+
+        def mapping(x):
+            return (x[0] - 1, x[1] - 1)
+
+        if (order > 1):
+            filtered = ndimage.spline_filter(data, order=order)
+        else:
+            filtered = data
+        out = ndimage.geometric_transform(filtered, mapping, data.shape,
+                                          order=order, prefilter=False)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 4, 1, 3],
+                               [0, 7, 6, 8]], dtype=out.dtype)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform13(self, order, xp):
+        data = xp.ones([2], dtype=xp.float64)
+
+        def mapping(x):
+            return (x[0] // 2,)
+
+        out = ndimage.geometric_transform(data, mapping, [4], order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
+
+    def test_geometric_transform14(self, order, xp):
+        data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
+
+        def mapping(x):
+            return (2 * x[0],)
+
+        out = ndimage.geometric_transform(data, mapping, [4], order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4], dtype=out.dtype))
+
+    def test_geometric_transform15(self, order, xp):
+        data = [1, 2, 3, 4]
+
+        def mapping(x):
+            return (x[0] / 2,)
+
+        out = ndimage.geometric_transform(data, mapping, [8], order=order)
+        assert_array_almost_equal(out[::2], [1, 2, 3, 4])
+
+    def test_geometric_transform16(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9.0, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0], x[1] * 2)
+
+        out = ndimage.geometric_transform(data, mapping, (3, 2),
+                                          order=order)
+        assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]])
+
+    def test_geometric_transform17(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0] * 2, x[1])
+
+        out = ndimage.geometric_transform(data, mapping, (1, 4),
+                                          order=order)
+        assert_array_almost_equal(out, [[1, 2, 3, 4]])
+
+    def test_geometric_transform18(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0] * 2, x[1] * 2)
+
+        out = ndimage.geometric_transform(data, mapping, (1, 2),
+                                          order=order)
+        assert_array_almost_equal(out, [[1, 3]])
+
+    def test_geometric_transform19(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0], x[1] / 2)
+
+        out = ndimage.geometric_transform(data, mapping, (3, 8),
+                                          order=order)
+        assert_array_almost_equal(out[..., ::2], data)
+
+    def test_geometric_transform20(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0] / 2, x[1])
+
+        out = ndimage.geometric_transform(data, mapping, (6, 4),
+                                          order=order)
+        assert_array_almost_equal(out[::2, ...], data)
+
+    def test_geometric_transform21(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0] / 2, x[1] / 2)
+
+        out = ndimage.geometric_transform(data, mapping, (6, 8),
+                                          order=order)
+        assert_array_almost_equal(out[::2, ::2], data)
+
+    def test_geometric_transform22(self, order, xp):
+        data = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]], dtype=xp.float64)
+
+        def mapping1(x):
+            return (x[0] / 2, x[1] / 2)
+
+        def mapping2(x):
+            return (x[0] * 2, x[1] * 2)
+
+        out = ndimage.geometric_transform(data, mapping1,
+                                          (6, 8), order=order)
+        out = ndimage.geometric_transform(out, mapping2,
+                                          (3, 4), order=order)
+        assert_array_almost_equal(out, data)
+
+    def test_geometric_transform23(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (1, x[0] * 2)
+
+        out = ndimage.geometric_transform(data, mapping, (2,), order=order)
+        out = out.astype(np.int32)
+        assert_array_almost_equal(out, [5, 7])
+
+    def test_geometric_transform24(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x, a, b):
+            return (a, x[0] * b)
+
+        out = ndimage.geometric_transform(
+            data, mapping, (2,), order=order, extra_arguments=(1,),
+            extra_keywords={'b': 2})
+        assert_array_almost_equal(out, [5, 7])
+
+
+@skip_xp_backends("cupy", reason="CuPy does not have geometric_transform")
+class TestGeometricTransformExtra:
+
+    def test_geometric_transform_grid_constant_order1(self, xp):
+
+        # verify interpolation outside the original bounds
+        x = xp.asarray([[1, 2, 3],
+                        [4, 5, 6]], dtype=xp.float64)
+
+        def mapping(x):
+            return (x[0] - 0.5), (x[1] - 0.5)
+
+        expected_result = xp.asarray([[0.25, 0.75, 1.25],
+                                      [1.25, 3.00, 4.00]])
+        assert_array_almost_equal(
+            ndimage.geometric_transform(x, mapping, mode='grid-constant',
+                                        order=1),
+            expected_result,
+        )
+
+    @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
+                                      'mirror', 'reflect'])
+    @pytest.mark.parametrize('order', range(6))
+    def test_geometric_transform_vs_padded(self, order, mode, xp):
+
+        def mapping(x):
+            return (x[0] - 0.4), (x[1] + 2.3)
+
+        # Manually pad and then extract center after the transform to get the
+        # expected result.
+        x = np.arange(144, dtype=float).reshape(12, 12)
+        npad = 24
+        pad_mode = ndimage_to_numpy_mode.get(mode)
+        x_padded = np.pad(x, npad, mode=pad_mode)
+
+        x = xp.asarray(x)
+        x_padded = xp.asarray(x_padded)
+
+        center_slice = tuple([slice(npad, -npad)] * x.ndim)
+        expected_result = ndimage.geometric_transform(
+            x_padded, mapping, mode=mode, order=order)[center_slice]
+
+        xp_assert_close(
+            ndimage.geometric_transform(x, mapping, mode=mode,
+                                        order=order),
+            expected_result,
+            rtol=1e-7,
+        )
+
+    @skip_xp_backends(np_only=True, reason='endianness is numpy-specific')
+    def test_geometric_transform_endianness_with_output_parameter(self, xp):
+        # geometric transform given output ndarray or dtype with
+        # non-native endianness. see issue #4127
+        data = np.asarray([1])
+
+        def mapping(x):
+            return x
+
+        for out in [data.dtype, data.dtype.newbyteorder(),
+                    np.empty_like(data),
+                    np.empty_like(data).astype(data.dtype.newbyteorder())]:
+            returned = ndimage.geometric_transform(data, mapping, data.shape,
+                                                   output=out)
+            result = out if returned is None else returned
+            assert_array_almost_equal(result, [1])
+
+    @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+    def test_geometric_transform_with_string_output(self, xp):
+        data = xp.asarray([1])
+
+        def mapping(x):
+            return x
+
+        out = ndimage.geometric_transform(data, mapping, output='f')
+        assert out.dtype is np.dtype('f')
+        assert_array_almost_equal(out, [1])
+
+
+class TestMapCoordinates:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+    def test_map_coordinates01(self, order, dtype, xp):
+        if is_jax(xp) and order > 1:
+            pytest.xfail("jax map_coordinates requires order <= 1")
+
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 4, 1, 3],
+                               [0, 7, 6, 8]])
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data = data - 1j * data
+            expected = expected - 1j * expected
+
+        idx = np.indices(data.shape)
+        idx -= 1
+        idx = xp.asarray(idx)
+
+        out = ndimage.map_coordinates(data, idx, order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_map_coordinates02(self, order, xp):
+        if is_jax(xp):
+            if order > 1:
+               pytest.xfail("jax map_coordinates requires order <= 1")
+            if order == 1:
+               pytest.xfail("output differs. jax bug?")
+
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        idx = np.indices(data.shape, np.float64)
+        idx -= 0.5
+        idx = xp.asarray(idx)
+
+        out1 = ndimage.shift(data, 0.5, order=order)
+        out2 = ndimage.map_coordinates(data, idx, order=order)
+        assert_array_almost_equal(out1, out2)
+
+    @skip_xp_backends("jax.numpy", reason="`order` is required in jax")
+    def test_map_coordinates03(self, xp):
+        data = _asarray([[4, 1, 3, 2],
+                         [7, 6, 8, 5],
+                         [3, 5, 3, 6]], order='F', xp=xp)
+        idx = np.indices(data.shape) - 1
+        idx = xp.asarray(idx)
+        out = ndimage.map_coordinates(data, idx)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 4, 1, 3],
+                               [0, 7, 6, 8]])
+        assert_array_almost_equal(out, expected)
+        assert_array_almost_equal(out, ndimage.shift(data, (1, 1)))
+
+        idx = np.indices(data[::2, ...].shape) - 1
+        idx = xp.asarray(idx)
+        out = ndimage.map_coordinates(data[::2, ...], idx)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3]]))
+        assert_array_almost_equal(out, ndimage.shift(data[::2, ...], (1, 1)))
+
+        idx = np.indices(data[:, ::2].shape) - 1
+        idx = xp.asarray(idx)
+        out = ndimage.map_coordinates(data[:, ::2], idx)
+        assert_array_almost_equal(out, xp.asarray([[0, 0], [0, 4], [0, 7]]))
+        assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1)))
+
+    @skip_xp_backends(np_only=True)
+    def test_map_coordinates_endianness_with_output_parameter(self, xp):
+        # output parameter given as array or dtype with either endianness
+        # see issue #4127
+        # NB: NumPy-only
+
+        data = np.asarray([[1, 2], [7, 6]])
+        expected = np.asarray([[0, 0], [0, 1]])
+        idx = np.indices(data.shape)
+        idx -= 1
+        for out in [
+            data.dtype,
+            data.dtype.newbyteorder(),
+            np.empty_like(expected),
+            np.empty_like(expected).astype(expected.dtype.newbyteorder())
+        ]:
+            returned = ndimage.map_coordinates(data, idx, output=out)
+            result = out if returned is None else returned
+            assert_array_almost_equal(result, expected)
+
+    @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+    def test_map_coordinates_with_string_output(self, xp):
+        data = xp.asarray([[1]])
+        idx = np.indices(data.shape)
+        idx = xp.asarray(idx)
+        out = ndimage.map_coordinates(data, idx, output='f')
+        assert out.dtype is np.dtype('f')
+        assert_array_almost_equal(out, xp.asarray([[1]]))
+
+    @pytest.mark.skipif('win32' in sys.platform or np.intp(0).itemsize < 8,
+                        reason='do not run on 32 bit or windows '
+                               '(no sparse memory)')
+    def test_map_coordinates_large_data(self, xp):
+        # check crash on large data
+        try:
+            n = 30000
+            # a = xp.reshape(xp.empty(n**2, dtype=xp.float32), (n, n))
+            a = np.empty(n**2, dtype=np.float32).reshape(n, n)
+            # fill the part we might read
+            a[n - 3:, n - 3:] = 0
+            ndimage.map_coordinates(
+                xp.asarray(a), xp.asarray([[n - 1.5], [n - 1.5]]), order=1
+            )
+        except MemoryError as e:
+            raise pytest.skip('Not enough memory available') from e
+
+
+class TestAffineTransform:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform01(self, order, xp):
+        data = xp.asarray([1])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
+        assert_array_almost_equal(out, xp.asarray([1]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform02(self, order, xp):
+        data = xp.ones([4])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform03(self, order, xp):
+        data = xp.ones([4])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform04(self, order, xp):
+        data = xp.asarray([4, 1, 3, 2])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_affine_transform05(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[1, 1, 1, 1],
+                           [1, 1, 1, 1],
+                           [1, 1, 1, 1]], dtype=dtype)
+        expected = xp.asarray([[0, 1, 1, 1],
+                               [0, 1, 1, 1],
+                               [0, 1, 1, 1]], dtype=dtype)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+                                       [0, -1], order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform06(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+                                       [0, -1], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
+                                                   [0, 7, 6, 8],
+                                                   [0, 3, 5, 3]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform07(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+                                       [-1, 0], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [4, 1, 3, 2],
+                                                   [7, 6, 8, 5]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform08(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+                                       [-1, -1], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3],
+                                                   [0, 7, 6, 8]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform09(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        if (order > 1):
+            filtered = ndimage.spline_filter(data, order=order)
+        else:
+            filtered = data
+        out = ndimage.affine_transform(filtered, xp.asarray([[1, 0], [0, 1]]),
+                                       [-1, -1], order=order,
+                                       prefilter=False)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3],
+                                                   [0, 7, 6, 8]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform10(self, order, xp):
+        data = xp.ones([2], dtype=xp.float64)
+        out = ndimage.affine_transform(data, xp.asarray([[0.5]]), output_shape=(4,),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform11(self, order, xp):
+        data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
+        out = ndimage.affine_transform(data, xp.asarray([[2]]), 0, (4,), order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform12(self, order, xp):
+        data = xp.asarray([1, 2, 3, 4])
+        out = ndimage.affine_transform(data, xp.asarray([[0.5]]), 0, (8,), order=order)
+        assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform13(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9.0, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 2]]), 0, (3, 2),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform14(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 1]]), 0, (1, 4),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform15(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 2]]), 0, (1, 2),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([[1, 3]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform16(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0.0], [0, 0.5]]), 0,
+                                       (3, 8), order=order)
+        assert_array_almost_equal(out[..., ::2], data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform17(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 1]]), 0,
+                                       (6, 4), order=order)
+        assert_array_almost_equal(out[::2, ...], data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform18(self, order, xp):
+        data = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]])
+        out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
+                                       (6, 8), order=order)
+        assert_array_almost_equal(out[::2, ::2], data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform19(self, order, xp):
+        data = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]], dtype=xp.float64)
+        out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
+                                       (6, 8), order=order)
+        out = ndimage.affine_transform(out, xp.asarray([[2.0, 0], [0, 2.0]]), 0,
+                                       (3, 4), order=order)
+        assert_array_almost_equal(out, data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform20(self, order, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8394")
+
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[0], [2]]), 0, (2,),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 3]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform21(self, order, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8394")
+
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[2], [0]]), 0, (2,),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 9]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform22(self, order, xp):
+        # shift and offset interaction; see issue #1547
+        data = xp.asarray([4, 1, 3, 2])
+        out = ndimage.affine_transform(data, xp.asarray([[2]]), [-1], (3,),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 2]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform23(self, order, xp):
+        # shift and offset interaction; see issue #1547
+        data = xp.asarray([4, 1, 3, 2])
+        out = ndimage.affine_transform(data, xp.asarray([[0.5]]), [-1], (8,),
+                                       order=order)
+        assert_array_almost_equal(out[::2], xp.asarray([0, 4, 1, 3]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform24(self, order, xp):
+        # consistency between diagonal and non-diagonal case; see issue #1547
+        data = xp.asarray([4, 1, 3, 2])
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            out1 = ndimage.affine_transform(data, xp.asarray([2]), -1, order=order)
+        out2 = ndimage.affine_transform(data, xp.asarray([[2]]), -1, order=order)
+        assert_array_almost_equal(out1, out2)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform25(self, order, xp):
+        # consistency between diagonal and non-diagonal case; see issue #1547
+        data = xp.asarray([4, 1, 3, 2])
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            out1 = ndimage.affine_transform(data, xp.asarray([0.5]), -1, order=order)
+        out2 = ndimage.affine_transform(data, xp.asarray([[0.5]]), -1, order=order)
+        assert_array_almost_equal(out1, out2)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform26(self, order, xp):
+        # test homogeneous coordinates
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        if (order > 1):
+            filtered = ndimage.spline_filter(data, order=order)
+        else:
+            filtered = data
+        tform_original = xp.eye(2)
+        offset_original = -xp.ones((2, 1))
+
+        concat = array_namespace(tform_original, offset_original).concat
+        tform_h1 = concat((tform_original, offset_original), axis=1)  # hstack
+        tform_h2 = concat( (tform_h1, xp.asarray([[0.0, 0, 1]])), axis=0)  # vstack
+
+        offs = [float(x) for x in xp.reshape(offset_original, (-1,))]
+
+        out1 = ndimage.affine_transform(filtered, tform_original,
+                                        offs,
+                                        order=order, prefilter=False)
+        out2 = ndimage.affine_transform(filtered, tform_h1, order=order,
+                                        prefilter=False)
+        out3 = ndimage.affine_transform(filtered, tform_h2, order=order,
+                                        prefilter=False)
+        for out in [out1, out2, out3]:
+            assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                       [0, 4, 1, 3],
+                                                       [0, 7, 6, 8]]))
+
+    def test_affine_transform27(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not raise")
+
+        # test valid homogeneous transformation matrix
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        concat = array_namespace(data).concat
+        tform_h1 = concat( (xp.eye(2), -xp.ones((2, 1))) , axis=1)  # vstack
+        tform_h2 = concat((tform_h1, xp.asarray([[5.0, 2, 1]])), axis=0)  # hstack
+
+        assert_raises(ValueError, ndimage.affine_transform, data, tform_h2)
+
+    @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+    def test_affine_transform_1d_endianness_with_output_parameter(self, xp):
+        # 1d affine transform given output ndarray or dtype with
+        # either endianness. see issue #7388
+        data = xp.ones((2, 2))
+        for out in [xp.empty_like(data),
+                    xp.empty_like(data).astype(data.dtype.newbyteorder()),
+                    data.dtype, data.dtype.newbyteorder()]:
+            with suppress_warnings() as sup:
+                sup.filter(UserWarning,
+                           'The behavior of affine_transform with a 1-D array '
+                           '.* has changed')
+                matrix = xp.asarray([1, 1])
+                returned = ndimage.affine_transform(data, matrix, output=out)
+            result = out if returned is None else returned
+            assert_array_almost_equal(result, xp.asarray([[1, 1], [1, 1]]))
+
+    @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+    def test_affine_transform_multi_d_endianness_with_output_parameter(self, xp):
+        # affine transform given output ndarray or dtype with either endianness
+        # see issue #4127
+        # NB: byteorder is numpy-specific
+        data = np.asarray([1])
+        for out in [data.dtype, data.dtype.newbyteorder(),
+                    np.empty_like(data),
+                    np.empty_like(data).astype(data.dtype.newbyteorder())]:
+            returned = ndimage.affine_transform(data, np.asarray([[1]]), output=out)
+            result = out if returned is None else returned
+            assert_array_almost_equal(result, np.asarray([1]))
+
+    @skip_xp_backends(np_only=True,
+        reason='`out` of a different size is numpy-specific'
+    )
+    def test_affine_transform_output_shape(self, xp):
+        # don't require output_shape when out of a different size is given
+        data = xp.arange(8, dtype=xp.float64)
+        out = xp.ones((16,))
+
+        ndimage.affine_transform(data, xp.asarray([[1]]), output=out)
+        assert_array_almost_equal(out[:8], data)
+
+        # mismatched output shape raises an error
+        with pytest.raises(RuntimeError):
+            ndimage.affine_transform(
+                data, [[1]], output=out, output_shape=(12,))
+
+    @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+    def test_affine_transform_with_string_output(self, xp):
+        data = xp.asarray([1])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), output='f')
+        assert out.dtype is np.dtype('f')
+        assert_array_almost_equal(out, xp.asarray([1]))
+
+    @pytest.mark.parametrize('shift',
+                             [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform_shift_via_grid_wrap(self, shift, order, xp):
+        # For mode 'grid-wrap', integer shifts should match np.roll
+        x = np.asarray([[0, 1],
+                        [2, 3]])
+        affine = np.zeros((2, 3))
+        affine[:2, :2] = np.eye(2)
+        affine[:, 2] = np.asarray(shift)
+
+        expected = np.roll(x, shift, axis=(0, 1))
+
+        x = xp.asarray(x)
+        affine = xp.asarray(affine)
+        expected = xp.asarray(expected)
+
+        assert_array_almost_equal(
+            ndimage.affine_transform(x, affine, mode='grid-wrap', order=order),
+            expected
+        )
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform_shift_reflect(self, order, xp):
+        # shift by x.shape results in reflection
+        x = np.asarray([[0, 1, 2],
+                        [3, 4, 5]])
+        expected = x[::-1, ::-1].copy()   # strides >0 for torch
+        x = xp.asarray(x)
+        expected = xp.asarray(expected)
+
+        affine = np.zeros([2, 3])
+        affine[:2, :2] = np.eye(2)
+        affine[:, 2] = np.asarray(x.shape)
+        affine = xp.asarray(affine)
+
+        assert_array_almost_equal(
+            ndimage.affine_transform(x, affine, mode='reflect', order=order),
+            expected,
+        )
+
+
+class TestShift:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift01(self, order, xp):
+        data = xp.asarray([1])
+        out = ndimage.shift(data, [1], order=order)
+        assert_array_almost_equal(out, xp.asarray([0]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift02(self, order, xp):
+        data = xp.ones([4])
+        out = ndimage.shift(data, [1], order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift03(self, order, xp):
+        data = xp.ones([4])
+        out = ndimage.shift(data, -1, order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift04(self, order, xp):
+        data = xp.asarray([4, 1, 3, 2])
+        out = ndimage.shift(data, 1, order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_shift05(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[1, 1, 1, 1],
+                           [1, 1, 1, 1],
+                           [1, 1, 1, 1]], dtype=dtype)
+        expected = xp.asarray([[0, 1, 1, 1],
+                               [0, 1, 1, 1],
+                               [0, 1, 1, 1]], dtype=dtype)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+        out = ndimage.shift(data, [0, 1], order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('mode', ['constant', 'grid-constant'])
+    @pytest.mark.parametrize('dtype', ['float64', 'complex128'])
+    def test_shift_with_nonzero_cval(self, order, mode, dtype, xp):
+        data = np.asarray([[1, 1, 1, 1],
+                           [1, 1, 1, 1],
+                           [1, 1, 1, 1]], dtype=dtype)
+
+        expected = np.asarray([[0, 1, 1, 1],
+                               [0, 1, 1, 1],
+                               [0, 1, 1, 1]], dtype=dtype)
+
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+        cval = 5.0
+        expected[:, 0] = cval  # specific to shift of [0, 1] used below
+
+        data = xp.asarray(data)
+        expected = xp.asarray(expected)
+        out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift06(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.shift(data, [0, 1], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
+                                                   [0, 7, 6, 8],
+                                                   [0, 3, 5, 3]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift07(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.shift(data, [1, 0], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [4, 1, 3, 2],
+                                                   [7, 6, 8, 5]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift08(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.shift(data, [1, 1], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3],
+                                                   [0, 7, 6, 8]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift09(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        if (order > 1):
+            filtered = ndimage.spline_filter(data, order=order)
+        else:
+            filtered = data
+        out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3],
+                                                   [0, 7, 6, 8]]))
+
+    @pytest.mark.parametrize('shift',
+                             [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift_grid_wrap(self, shift, order, xp):
+        # For mode 'grid-wrap', integer shifts should match np.roll
+        x = np.asarray([[0, 1],
+                        [2, 3]])
+        expected = np.roll(x, shift, axis=(0,1))
+
+        x = xp.asarray(x)
+        expected = xp.asarray(expected)
+
+        assert_array_almost_equal(
+            ndimage.shift(x, shift, mode='grid-wrap', order=order),
+            expected
+        )
+
+    @pytest.mark.parametrize('shift',
+                             [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift_grid_constant1(self, shift, order, xp):
+        # For integer shifts, 'constant' and 'grid-constant' should be equal
+        x = xp.reshape(xp.arange(20), (5, 4))
+        assert_array_almost_equal(
+            ndimage.shift(x, shift, mode='grid-constant', order=order),
+            ndimage.shift(x, shift, mode='constant', order=order),
+        )
+
+    def test_shift_grid_constant_order1(self, xp):
+        x = xp.asarray([[1, 2, 3],
+                        [4, 5, 6]], dtype=xp.float64)
+        expected_result = xp.asarray([[0.25, 0.75, 1.25],
+                                      [1.25, 3.00, 4.00]])
+        assert_array_almost_equal(
+            ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1),
+            expected_result,
+        )
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift_reflect(self, order, xp):
+        # shift by x.shape results in reflection
+        x = np.asarray([[0, 1, 2],
+                        [3, 4, 5]])
+        expected = x[::-1, ::-1].copy()   # strides > 0 for torch
+
+        x = xp.asarray(x)
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(
+            ndimage.shift(x, x.shape, mode='reflect', order=order),
+            expected,
+        )
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('prefilter', [False, True])
+    def test_shift_nearest_boundary(self, order, prefilter, xp):
+        # verify that shifting at least order // 2 beyond the end of the array
+        # gives a value equal to the edge value.
+        x = xp.arange(16)
+        kwargs = dict(mode='nearest', order=order, prefilter=prefilter)
+        assert_array_almost_equal(
+            ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0],
+        )
+        assert_array_almost_equal(
+            ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1],
+        )
+
+    @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
+                                      'mirror', 'reflect'])
+    @pytest.mark.parametrize('order', range(6))
+    def test_shift_vs_padded(self, order, mode, xp):
+        x_np = np.arange(144, dtype=float).reshape(12, 12)
+        shift = (0.4, -2.3)
+
+        # manually pad and then extract center to get expected result
+        npad = 32
+        pad_mode = ndimage_to_numpy_mode.get(mode)
+        x_padded = xp.asarray(np.pad(x_np, npad, mode=pad_mode))
+        x = xp.asarray(x_np)
+
+        center_slice = tuple([slice(npad, -npad)] * x.ndim)
+        expected_result = ndimage.shift(
+            x_padded, shift, mode=mode, order=order)[center_slice]
+
+        xp_assert_close(
+            ndimage.shift(x, shift, mode=mode, order=order),
+            expected_result,
+            rtol=1e-7,
+        )
+
+
+class TestZoom:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_zoom1(self, order, xp):
+        for z in [2, [2, 2]]:
+            arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5))
+            arr = ndimage.zoom(arr, z, order=order)
+            assert arr.shape == (10, 10)
+            assert xp.all(arr[-1, :] != 0)
+            assert xp.all(arr[-1, :] >= (20 - eps))
+            assert xp.all(arr[0, :] <= (5 + eps))
+            assert xp.all(arr >= (0 - eps))
+            assert xp.all(arr <= (24 + eps))
+
+    def test_zoom2(self, xp):
+        arr = xp.reshape(xp.arange(12), (3, 4))
+        out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5)
+        xp_assert_equal(out, arr)
+
+    def test_zoom3(self, xp):
+        arr = xp.asarray([[1, 2]])
+        out1 = ndimage.zoom(arr, (2, 1))
+        out2 = ndimage.zoom(arr, (1, 2))
+
+        assert_array_almost_equal(out1, xp.asarray([[1, 2], [1, 2]]))
+        assert_array_almost_equal(out2, xp.asarray([[1, 1, 2, 2]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_zoom_affine01(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]], dtype=dtype)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            out = ndimage.affine_transform(data, xp.asarray([0.5, 0.5]), 0,
+                                           (6, 8), order=order)
+        assert_array_almost_equal(out[::2, ::2], data)
+
+    def test_zoom_infinity(self, xp):
+        # Ticket #1419 regression test
+        dim = 8
+        ndimage.zoom(xp.zeros((dim, dim)), 1. / dim, mode='nearest')
+
+    def test_zoom_zoomfactor_one(self, xp):
+        # Ticket #1122 regression test
+        arr = xp.zeros((1, 5, 5))
+        zoom = (1.0, 2.0, 2.0)
+
+        out = ndimage.zoom(arr, zoom, cval=7)
+        ref = xp.zeros((1, 10, 10))
+        assert_array_almost_equal(out, ref)
+
+    def test_zoom_output_shape_roundoff(self, xp):
+        arr = xp.zeros((3, 11, 25))
+        zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25)
+        out = ndimage.zoom(arr, zoom)
+        assert out.shape == (4, 15, 29)
+
+    @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
+    @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect',
+                                      'mirror', 'grid-wrap', 'grid-mirror',
+                                      'grid-constant'])
+    def test_zoom_by_int_order0(self, zoom, mode, xp):
+        # order 0 zoom should be the same as replication via np.kron
+        # Note: This is not True for general x shapes when grid_mode is False,
+        #       but works here for all modes because the size ratio happens to
+        #       always be an integer when x.shape = (2, 2).
+        x_np = np.asarray([[0, 1],
+                           [2, 3]], dtype=np.float64)
+        expected = np.kron(x_np, np.ones(zoom))
+
+        x = xp.asarray(x_np)
+        expected = xp.asarray(expected)
+
+        assert_array_almost_equal(
+            ndimage.zoom(x, zoom, order=0, mode=mode),
+            expected
+        )
+
+    @pytest.mark.parametrize('shape', [(2, 3), (4, 4)])
+    @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
+    @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror',
+                                      'grid-wrap', 'grid-constant'])
+    def test_zoom_grid_by_int_order0(self, shape, zoom, mode, xp):
+        # When grid_mode is True,  order 0 zoom should be the same as
+        # replication via np.kron. The only exceptions to this are the
+        # non-grid modes 'constant' and 'wrap'.
+        x_np = np.arange(np.prod(shape), dtype=float).reshape(shape)
+
+        x = xp.asarray(x_np)
+        assert_array_almost_equal(
+            ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True),
+            xp.asarray(np.kron(x_np, np.ones(zoom)))
+        )
+
+    @pytest.mark.parametrize('mode', ['constant', 'wrap'])
+    @pytest.mark.thread_unsafe
+    def test_zoom_grid_mode_warnings(self, mode, xp):
+        # Warn on use of non-grid modes when grid_mode is True
+        x = xp.reshape(xp.arange(9, dtype=xp.float64), (3, 3))
+        with pytest.warns(UserWarning,
+                          match="It is recommended to use mode"):
+            ndimage.zoom(x, 2, mode=mode, grid_mode=True),
+
+    @skip_xp_backends(np_only=True, reason='inplace output= is numpy-specific')
+    def test_zoom_output_shape(self, xp):
+        """Ticket #643"""
+        x = xp.reshape(xp.arange(12), (3, 4))
+        ndimage.zoom(x, 2, output=xp.zeros((6, 8)))
+
+    def test_zoom_0d_array(self, xp):
+        # Ticket #21670 regression test
+        a = xp.arange(10.)
+        factor = 2
+        actual = ndimage.zoom(a, np.array(factor))
+        expected = ndimage.zoom(a, factor)
+        xp_assert_close(actual, expected)
+
+
+class TestRotate:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate01(self, order, xp):
+        data = xp.asarray([[0, 0, 0, 0],
+                           [0, 1, 1, 0],
+                           [0, 0, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 0, order=order)
+        assert_array_almost_equal(out, data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate02(self, order, xp):
+        data = xp.asarray([[0, 0, 0, 0],
+                           [0, 1, 0, 0],
+                           [0, 0, 0, 0]], dtype=xp.float64)
+        expected = xp.asarray([[0, 0, 0],
+                               [0, 0, 0],
+                               [0, 1, 0],
+                               [0, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 90, order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_rotate03(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0]], dtype=dtype)
+        expected = xp.asarray([[0, 0, 0],
+                               [0, 0, 0],
+                               [0, 1, 0],
+                               [0, 1, 0],
+                               [0, 0, 0]], dtype=dtype)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+        out = ndimage.rotate(data, 90, order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate04(self, order, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0]], dtype=xp.float64)
+        expected = xp.asarray([[0, 0, 0, 0, 0],
+                               [0, 0, 1, 0, 0],
+                               [0, 0, 1, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 90, reshape=False, order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate05(self, order, xp):
+        data = np.empty((4, 3, 3))
+        for i in range(3):
+            data[:, :, i] = np.asarray([[0, 0, 0],
+                                        [0, 1, 0],
+                                        [0, 1, 0],
+                                        [0, 0, 0]], dtype=np.float64)
+        data = xp.asarray(data)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 1, 1, 0],
+                               [0, 0, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 90, order=order)
+        for i in range(3):
+            assert_array_almost_equal(out[:, :, i], expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate06(self, order, xp):
+        data = np.empty((3, 4, 3))
+        for i in range(3):
+            data[:, :, i] = np.asarray([[0, 0, 0, 0],
+                                        [0, 1, 1, 0],
+                                        [0, 0, 0, 0]], dtype=np.float64)
+        data = xp.asarray(data)
+        expected = xp.asarray([[0, 0, 0],
+                               [0, 1, 0],
+                               [0, 1, 0],
+                               [0, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 90, order=order)
+        for i in range(3):
+            assert_array_almost_equal(out[:, :, i], expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate07(self, order, xp):
+        data = xp.asarray([[[0, 0, 0, 0, 0],
+                            [0, 1, 1, 0, 0],
+                            [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+        permute_dims = array_namespace(data).permute_dims
+        data = permute_dims(data, (2, 1, 0))
+        expected = xp.asarray([[[0, 0, 0],
+                                [0, 1, 0],
+                                [0, 1, 0],
+                                [0, 0, 0],
+                                [0, 0, 0]]] * 2, dtype=xp.float64)
+        expected = permute_dims(expected, (2, 1, 0))
+        out = ndimage.rotate(data, 90, axes=(0, 1), order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate08(self, order, xp):
+        data = xp.asarray([[[0, 0, 0, 0, 0],
+                            [0, 1, 1, 0, 0],
+                            [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+        permute_dims = array_namespace(data).permute_dims
+        data = permute_dims(data, (2, 1, 0))  # == np.transpose
+        expected = xp.asarray([[[0, 0, 1, 0, 0],
+                                [0, 0, 1, 0, 0],
+                                [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+        permute_dims = array_namespace(data).permute_dims
+        expected = permute_dims(expected, (2, 1, 0))
+        out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order)
+        assert_array_almost_equal(out, expected)
+
+    def test_rotate09(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0]] * 2, dtype=xp.float64)
+        with assert_raises(ValueError):
+            ndimage.rotate(data, 90, axes=(0, data.ndim))
+
+    def test_rotate10(self, xp):
+        data = xp.reshape(xp.arange(45, dtype=xp.float64), (3, 5, 3))
+
+	# The output of ndimage.rotate before refactoring
+        expected = xp.asarray([[[0.0, 0.0, 0.0],
+                                [0.0, 0.0, 0.0],
+                                [6.54914793, 7.54914793, 8.54914793],
+                                [10.84520162, 11.84520162, 12.84520162],
+                                [0.0, 0.0, 0.0]],
+                               [[6.19286575, 7.19286575, 8.19286575],
+                                [13.4730712, 14.4730712, 15.4730712],
+                                [21.0, 22.0, 23.0],
+                                [28.5269288, 29.5269288, 30.5269288],
+                                [35.80713425, 36.80713425, 37.80713425]],
+                               [[0.0, 0.0, 0.0],
+                                [31.15479838, 32.15479838, 33.15479838],
+                                [35.45085207, 36.45085207, 37.45085207],
+                                [0.0, 0.0, 0.0],
+                                [0.0, 0.0, 0.0]]], dtype=xp.float64)
+
+        out = ndimage.rotate(data, angle=12, reshape=False)
+        #assert_array_almost_equal(out, expected)
+        xp_assert_close(out, expected, rtol=1e-6, atol=2e-6)
+
+    def test_rotate_exact_180(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8400")
+
+        a = np.tile(xp.arange(5), (5, 1))
+        b = ndimage.rotate(ndimage.rotate(a, 180), -180)
+        xp_assert_equal(a, b)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8175ba309dd223a6d0fd46df017ea1fbc797a4e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py
@@ -0,0 +1,1609 @@
+import os
+import os.path
+
+import numpy as np
+from numpy.testing import suppress_warnings
+
+from scipy._lib._array_api import (
+    is_jax,
+    is_torch,
+    array_namespace,
+    xp_assert_equal,
+    xp_assert_close,
+    assert_array_almost_equal,
+    assert_almost_equal,
+)
+
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.ndimage as ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+IS_WINDOWS_AND_NP1 = os.name == 'nt' and np.__version__ < '2'
+
+
+@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
+class Test_measurements_stats:
+    """ndimage._measurements._stats() is a utility used by other functions.
+
+        Since internal ndimage/_measurements.py code is NumPy-only,
+        so is this this test class.
+    """
+    def test_a(self, xp):
+        x = [0, 1, 2, 6]
+        labels = [0, 0, 1, 1]
+        index = [0, 1]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums = ndimage._measurements._stats(
+                x, labels=labels, index=index)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+
+    def test_b(self, xp):
+        # Same data as test_a, but different labels.  The label 9 exceeds the
+        # length of 'labels', so this test will follow a different code path.
+        x = [0, 1, 2, 6]
+        labels = [0, 0, 9, 9]
+        index = [0, 9]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums = ndimage._measurements._stats(
+                x, labels=labels, index=index)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+
+    def test_a_centered(self, xp):
+        x = [0, 1, 2, 6]
+        labels = [0, 0, 1, 1]
+        index = [0, 1]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums, centers = ndimage._measurements._stats(
+                x, labels=labels, index=index, centered=True)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+            xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+    def test_b_centered(self, xp):
+        x = [0, 1, 2, 6]
+        labels = [0, 0, 9, 9]
+        index = [0, 9]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums, centers = ndimage._measurements._stats(
+                x, labels=labels, index=index, centered=True)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+            xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+    def test_nonint_labels(self, xp):
+        x = [0, 1, 2, 6]
+        labels = [0.0, 0.0, 9.0, 9.0]
+        index = [0.0, 9.0]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums, centers = ndimage._measurements._stats(
+                x, labels=labels, index=index, centered=True)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+            xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+
+class Test_measurements_select:
+    """ndimage._measurements._select() is a utility used by other functions."""
+
+    def test_basic(self, xp):
+        x = [0, 1, 6, 2]
+        cases = [
+            ([0, 0, 1, 1], [0, 1]),           # "Small" integer labels
+            ([0, 0, 9, 9], [0, 9]),           # A label larger than len(labels)
+            ([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]),   # Non-integer labels
+        ]
+        for labels, index in cases:
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index)
+            assert len(result) == 0
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index, find_max=True)
+            assert len(result) == 1
+            xp_assert_equal(result[0], [1, 6])
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index, find_min=True)
+            assert len(result) == 1
+            xp_assert_equal(result[0], [0, 2])
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index, find_min=True,
+                find_min_positions=True)
+            assert len(result) == 2
+            xp_assert_equal(result[0], [0, 2])
+            xp_assert_equal(result[1], [0, 3])
+            assert result[1].dtype.kind == 'i'
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index, find_max=True,
+                find_max_positions=True)
+            assert len(result) == 2
+            xp_assert_equal(result[0], [1, 6])
+            xp_assert_equal(result[1], [1, 2])
+            assert result[1].dtype.kind == 'i'
+
+
+def test_label01(xp):
+    data = xp.ones([])
+    out, n = ndimage.label(data)
+    assert out == 1
+    assert n == 1
+
+
+def test_label02(xp):
+    data = xp.zeros([])
+    out, n = ndimage.label(data)
+    assert out == 0
+    assert n == 0
+
+
+@pytest.mark.thread_unsafe  # due to Cython fused types, see cython#6506
+def test_label03(xp):
+    data = xp.ones([1])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([1]))
+    assert n == 1
+
+
+def test_label04(xp):
+    data = xp.zeros([1])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([0]))
+    assert n == 0
+
+
+def test_label05(xp):
+    data = xp.ones([5])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+    assert n == 1
+
+
+def test_label06(xp):
+    data = xp.asarray([1, 0, 1, 1, 0, 1])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([1, 0, 2, 2, 0, 3]))
+    assert n == 3
+
+
+def test_label07(xp):
+    data = xp.asarray([[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]])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray(
+                                    [[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]]))
+    assert n == 0
+
+
+def test_label08(xp):
+    data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                       [0, 0, 1, 1, 0, 0],
+                       [0, 0, 1, 1, 1, 0],
+                       [1, 1, 0, 0, 0, 0],
+                       [1, 1, 0, 0, 0, 0],
+                       [0, 0, 0, 1, 1, 0]])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
+                                               [0, 0, 2, 2, 0, 0],
+                                               [0, 0, 2, 2, 2, 0],
+                                               [3, 3, 0, 0, 0, 0],
+                                               [3, 3, 0, 0, 0, 0],
+                                               [0, 0, 0, 4, 4, 0]]))
+    assert n == 4
+
+
+def test_label09(xp):
+    data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                       [0, 0, 1, 1, 0, 0],
+                       [0, 0, 1, 1, 1, 0],
+                       [1, 1, 0, 0, 0, 0],
+                       [1, 1, 0, 0, 0, 0],
+                       [0, 0, 0, 1, 1, 0]])
+    struct = ndimage.generate_binary_structure(2, 2)
+    struct = xp.asarray(struct)
+    out, n = ndimage.label(data, struct)
+    assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
+                                               [0, 0, 2, 2, 0, 0],
+                                               [0, 0, 2, 2, 2, 0],
+                                               [2, 2, 0, 0, 0, 0],
+                                               [2, 2, 0, 0, 0, 0],
+                                               [0, 0, 0, 3, 3, 0]]))
+    assert n == 3
+
+
+def test_label10(xp):
+    data = xp.asarray([[0, 0, 0, 0, 0, 0],
+                       [0, 1, 1, 0, 1, 0],
+                       [0, 1, 1, 1, 1, 0],
+                       [0, 0, 0, 0, 0, 0]])
+    struct = ndimage.generate_binary_structure(2, 2)
+    struct = xp.asarray(struct)
+    out, n = ndimage.label(data, struct)
+    assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0, 0, 0],
+                                               [0, 1, 1, 0, 1, 0],
+                                               [0, 1, 1, 1, 1, 0],
+                                               [0, 0, 0, 0, 0, 0]]))
+    assert n == 1
+
+
+def test_label11(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0],
+                           [1, 1, 0, 0, 0, 0],
+                           [1, 1, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 0]], dtype=dtype)
+        out, n = ndimage.label(data)
+        expected = [[1, 0, 0, 0, 0, 0],
+                    [0, 0, 2, 2, 0, 0],
+                    [0, 0, 2, 2, 2, 0],
+                    [3, 3, 0, 0, 0, 0],
+                    [3, 3, 0, 0, 0, 0],
+                    [0, 0, 0, 4, 4, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+        assert n == 4
+
+
+@skip_xp_backends(np_only=True, reason='inplace output is numpy-specific')
+def test_label11_inplace(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0],
+                           [1, 1, 0, 0, 0, 0],
+                           [1, 1, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 0]], dtype=dtype)
+        n = ndimage.label(data, output=data)
+        expected = [[1, 0, 0, 0, 0, 0],
+                    [0, 0, 2, 2, 0, 0],
+                    [0, 0, 2, 2, 2, 0],
+                    [3, 3, 0, 0, 0, 0],
+                    [3, 3, 0, 0, 0, 0],
+                    [0, 0, 0, 4, 4, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(data, expected)
+        assert n == 4
+
+
+def test_label12(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        data = xp.asarray([[0, 0, 0, 0, 1, 1],
+                           [0, 0, 0, 0, 0, 1],
+                           [0, 0, 1, 0, 1, 1],
+                           [0, 0, 1, 1, 1, 1],
+                           [0, 0, 0, 1, 1, 0]], dtype=dtype)
+        out, n = ndimage.label(data)
+        expected = [[0, 0, 0, 0, 1, 1],
+                    [0, 0, 0, 0, 0, 1],
+                    [0, 0, 1, 0, 1, 1],
+                    [0, 0, 1, 1, 1, 1],
+                    [0, 0, 0, 1, 1, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+        assert n == 1
+
+
+def test_label13(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        data = xp.asarray([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
+                           [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
+                           [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+                           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],
+                          dtype=dtype)
+        out, n = ndimage.label(data)
+        expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
+                    [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
+                    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+        assert n == 1
+
+
+@skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+def test_label_output_typed(xp):
+    data = xp.ones([5])
+    for t in types:
+        dtype = getattr(xp, t)
+        output = xp.zeros([5], dtype=dtype)
+        n = ndimage.label(data, output=output)
+        assert_array_almost_equal(output,
+                                  xp.ones(output.shape, dtype=output.dtype))
+        assert n == 1
+
+
+@skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+def test_label_output_dtype(xp):
+    data = xp.ones([5])
+    for t in types:
+        dtype = getattr(xp, t)
+        output, n = ndimage.label(data, output=dtype)
+        assert_array_almost_equal(output,
+                                  xp.ones(output.shape, dtype=output.dtype))
+        assert output.dtype == t
+
+
+def test_label_output_wrong_size(xp):
+    if is_jax(xp):
+        pytest.xfail("JAX does not raise")
+
+    data = xp.ones([5])
+    for t in types:
+        dtype = getattr(xp, t)
+        output = xp.zeros([10], dtype=dtype)
+        # TypeError is from non-numpy arrays as output
+        assert_raises((ValueError, TypeError),
+                      ndimage.label, data, output=output)
+
+
+def test_label_structuring_elements(xp):
+    data = np.loadtxt(os.path.join(os.path.dirname(
+        __file__), "data", "label_inputs.txt"))
+    strels = np.loadtxt(os.path.join(
+        os.path.dirname(__file__), "data", "label_strels.txt"))
+    results = np.loadtxt(os.path.join(
+        os.path.dirname(__file__), "data", "label_results.txt"))
+    data = data.reshape((-1, 7, 7))
+    strels = strels.reshape((-1, 3, 3))
+    results = results.reshape((-1, 7, 7))
+
+    data = xp.asarray(data)
+    strels = xp.asarray(strels)
+    results = xp.asarray(results)
+    r = 0
+    for i in range(data.shape[0]):
+        d = data[i, :, :]
+        for j in range(strels.shape[0]):
+            s = strels[j, :, :]
+            xp_assert_equal(ndimage.label(d, s)[0], results[r, :, :], check_dtype=False)
+            r += 1
+
+@skip_xp_backends("cupy",
+                  reason="`cupyx.scipy.ndimage` does not have `find_objects`"
+)
+def test_ticket_742(xp):
+    def SE(img, thresh=.7, size=4):
+        mask = img > thresh
+        rank = len(mask.shape)
+        struct = ndimage.generate_binary_structure(rank, rank)
+        struct = xp.asarray(struct)
+        la, co = ndimage.label(mask,
+                               struct)
+        _ = ndimage.find_objects(la)
+
+    if np.dtype(np.intp) != np.dtype('i'):
+        shape = (3, 1240, 1240)
+        a = np.random.rand(np.prod(shape)).reshape(shape)
+        a = xp.asarray(a)
+        # shouldn't crash
+        SE(a)
+
+
+def test_gh_issue_3025(xp):
+    """Github issue #3025 - improper merging of labels"""
+    d = np.zeros((60, 320))
+    d[:, :257] = 1
+    d[:, 260:] = 1
+    d[36, 257] = 1
+    d[35, 258] = 1
+    d[35, 259] = 1
+    d = xp.asarray(d)
+    assert ndimage.label(d, xp.ones((3, 3)))[1] == 1
+
+
+@skip_xp_backends("cupy", reason="cupyx.scipy.ndimage does not have find_object")
+class TestFindObjects:
+    def test_label_default_dtype(self, xp):
+        test_array = np.random.rand(10, 10)
+        test_array = xp.asarray(test_array)
+        label, no_features = ndimage.label(test_array > 0.5)
+        assert label.dtype in (xp.int32, xp.int64)
+        # Shouldn't raise an exception
+        ndimage.find_objects(label)
+
+
+    def test_find_objects01(self, xp):
+        data = xp.ones([], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == [()]
+
+
+    def test_find_objects02(self, xp):
+        data = xp.zeros([], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == []
+
+
+    def test_find_objects03(self, xp):
+        data = xp.ones([1], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 1, None),)]
+
+
+    def test_find_objects04(self, xp):
+        data = xp.zeros([1], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == []
+
+
+    def test_find_objects05(self, xp):
+        data = xp.ones([5], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 5, None),)]
+
+
+    def test_find_objects06(self, xp):
+        data = xp.asarray([1, 0, 2, 2, 0, 3])
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 1, None),),
+                       (slice(2, 4, None),),
+                       (slice(5, 6, None),)]
+
+
+    def test_find_objects07(self, xp):
+        data = xp.asarray([[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]])
+        out = ndimage.find_objects(data)
+        assert out == []
+
+
+    def test_find_objects08(self, xp):
+        data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                           [0, 0, 2, 2, 0, 0],
+                           [0, 0, 2, 2, 2, 0],
+                           [3, 3, 0, 0, 0, 0],
+                           [3, 3, 0, 0, 0, 0],
+                           [0, 0, 0, 4, 4, 0]])
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 1, None), slice(0, 1, None)),
+                           (slice(1, 3, None), slice(2, 5, None)),
+                           (slice(3, 5, None), slice(0, 2, None)),
+                           (slice(5, 6, None), slice(3, 5, None))]
+
+
+    def test_find_objects09(self, xp):
+        data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                           [0, 0, 2, 2, 0, 0],
+                           [0, 0, 2, 2, 2, 0],
+                           [0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 4, 4, 0]])
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 1, None), slice(0, 1, None)),
+                           (slice(1, 3, None), slice(2, 5, None)),
+                           None,
+                           (slice(5, 6, None), slice(3, 5, None))]
+
+
+def test_value_indices01(xp):
+    "Test dictionary keys and entries"
+    data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                       [0, 0, 2, 2, 0, 0],
+                       [0, 0, 2, 2, 2, 0],
+                       [0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 4, 4, 0]])
+    vi = ndimage.value_indices(data, ignore_value=0)
+    true_keys = [1, 2, 4]
+    assert list(vi.keys()) == true_keys
+
+    nnz_kwd = {'as_tuple': True} if is_torch(xp) else {}
+
+    truevi = {}
+    for k in true_keys:
+        truevi[k] = xp.nonzero(data == k, **nnz_kwd)
+
+    vi = ndimage.value_indices(data, ignore_value=0)
+    assert vi.keys() == truevi.keys()
+    for key in vi.keys():
+        assert len(vi[key]) == len(truevi[key])
+        for v, true_v in zip(vi[key], truevi[key]):
+            xp_assert_equal(v, true_v)
+
+
+def test_value_indices02(xp):
+    "Test input checking"
+    data = xp.zeros((5, 4), dtype=xp.float32)
+    msg = "Parameter 'arr' must be an integer array"
+    with assert_raises(ValueError, match=msg):
+        ndimage.value_indices(data)
+
+
+def test_value_indices03(xp):
+    "Test different input array shapes, from 1-D to 4-D"
+    for shape in [(36,), (18, 2), (3, 3, 4), (3, 3, 2, 2)]:
+        a = xp.asarray((12*[1]+12*[2]+12*[3]), dtype=xp.int32)
+        a = xp.reshape(a, shape)
+
+        nnz_kwd = {'as_tuple': True} if is_torch(xp) else {}
+
+        unique_values = array_namespace(a).unique_values
+        trueKeys = unique_values(a)
+        vi = ndimage.value_indices(a)
+        assert list(vi.keys()) == list(trueKeys)
+        for k in [int(x) for x in trueKeys]:
+            trueNdx = xp.nonzero(a == k, **nnz_kwd)
+            assert len(vi[k]) == len(trueNdx)
+            for vik, true_vik in zip(vi[k], trueNdx):
+                xp_assert_equal(vik, true_vik)
+
+
+def test_sum01(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([], dtype=dtype)
+        output = ndimage.sum(input)
+        assert output == 0
+
+
+def test_sum02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.zeros([0, 4], dtype=dtype)
+        output = ndimage.sum(input)
+        assert output == 0
+
+
+def test_sum03(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.ones([], dtype=dtype)
+        output = ndimage.sum(input)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_sum04(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 2], dtype=dtype)
+        output = ndimage.sum(input)
+        assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+def test_sum05(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.sum(input)
+        assert_almost_equal(output, xp.asarray(10.0), check_0d=False)
+
+
+def test_sum06(xp):
+    labels = np.asarray([], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([], dtype=dtype)
+        output = ndimage.sum(input, labels=labels)
+        assert output == 0
+
+
+def test_sum07(xp):
+    labels = np.ones([0, 4], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.zeros([0, 4], dtype=dtype)
+        output = ndimage.sum(input, labels=labels)
+        assert output == 0
+
+
+def test_sum08(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 2], dtype=dtype)
+        output = ndimage.sum(input, labels=labels)
+        assert output == 1
+
+
+def test_sum09(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.sum(input, labels=labels)
+        assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
+
+
+def test_sum10(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    input = np.asarray([[1, 2], [3, 4]], dtype=bool)
+
+    labels = xp.asarray(labels)
+    input = xp.asarray(input)
+    output = ndimage.sum(input, labels=labels)
+    assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+def test_sum11(xp):
+    labels = xp.asarray([1, 2], dtype=xp.int8)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.sum(input, labels=labels,
+                             index=2)
+        assert_almost_equal(output, xp.asarray(6.0), check_0d=False)
+
+
+def test_sum12(xp):
+    labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
+        assert_array_almost_equal(output, xp.asarray([4.0, 0.0, 5.0]))
+
+
+def test_sum_labels(xp):
+    labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output_sum = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
+        output_labels = ndimage.sum_labels(
+            input, labels=labels, index=xp.asarray([4, 8, 2]))
+
+        assert xp.all(output_sum == output_labels)
+        assert_array_almost_equal(output_labels, xp.asarray([4.0, 0.0, 5.0]))
+
+
+def test_mean01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.mean(input, labels=labels)
+        assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+def test_mean02(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    input = np.asarray([[1, 2], [3, 4]], dtype=bool)
+
+    labels = xp.asarray(labels)
+    input = xp.asarray(input)
+    output = ndimage.mean(input, labels=labels)
+    assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_mean03(xp):
+    labels = xp.asarray([1, 2])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.mean(input, labels=labels,
+                              index=2)
+        assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+def test_mean04(xp):
+    labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+            output = ndimage.mean(input, labels=labels,
+                                  index=xp.asarray([4, 8, 2]))
+            # XXX: output[[0, 2]] does not work in array-api-strict; annoying
+            # assert_array_almost_equal(output[[0, 2]], xp.asarray([4.0, 2.5]))
+            assert output[0] == 4.0
+            assert output[2] == 2.5
+            assert xp.isnan(output[1])
+
+
+def test_minimum01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.minimum(input, labels=labels)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_minimum02(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    input = np.asarray([[2, 2], [2, 4]], dtype=bool)
+
+    labels = xp.asarray(labels)
+    input = xp.asarray(input)
+    output = ndimage.minimum(input, labels=labels)
+    assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_minimum03(xp):
+    labels = xp.asarray([1, 2])
+    for type in types:
+        dtype = getattr(xp, type)
+
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.minimum(input, labels=labels,
+                                 index=2)
+        assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+def test_minimum04(xp):
+    labels = xp.asarray([[1, 2], [2, 3]])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.minimum(input, labels=labels,
+                                 index=xp.asarray([2, 3, 8]))
+        assert_array_almost_equal(output, xp.asarray([2.0, 4.0, 0.0]))
+
+
+def test_maximum01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.maximum(input, labels=labels)
+        assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+def test_maximum02(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    input = np.asarray([[2, 2], [2, 4]], dtype=bool)
+    labels = xp.asarray(labels)
+    input = xp.asarray(input)
+    output = ndimage.maximum(input, labels=labels)
+    assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_maximum03(xp):
+    labels = xp.asarray([1, 2])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.maximum(input, labels=labels,
+                                 index=2)
+        assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
+
+
+def test_maximum04(xp):
+    labels = xp.asarray([[1, 2], [2, 3]])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.maximum(input, labels=labels,
+                                 index=xp.asarray([2, 3, 8]))
+        assert_array_almost_equal(output, xp.asarray([3.0, 4.0, 0.0]))
+
+
+def test_maximum05(xp):
+    # Regression test for ticket #501 (Trac)
+    x = xp.asarray([-3, -2, -1])
+    assert ndimage.maximum(x) == -1
+
+
+def test_median01(xp):
+    a = xp.asarray([[1, 2, 0, 1],
+                    [5, 3, 0, 4],
+                    [0, 0, 0, 7],
+                    [9, 3, 0, 0]])
+    labels = xp.asarray([[1, 1, 0, 2],
+                         [1, 1, 0, 2],
+                         [0, 0, 0, 2],
+                         [3, 3, 0, 0]])
+    output = ndimage.median(a, labels=labels, index=xp.asarray([1, 2, 3]))
+    assert_array_almost_equal(output, xp.asarray([2.5, 4.0, 6.0]))
+
+
+def test_median02(xp):
+    a = xp.asarray([[1, 2, 0, 1],
+                    [5, 3, 0, 4],
+                    [0, 0, 0, 7],
+                    [9, 3, 0, 0]])
+    output = ndimage.median(a)
+    assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_median03(xp):
+    a = xp.asarray([[1, 2, 0, 1],
+                    [5, 3, 0, 4],
+                    [0, 0, 0, 7],
+                    [9, 3, 0, 0]])
+    labels = xp.asarray([[1, 1, 0, 2],
+                         [1, 1, 0, 2],
+                         [0, 0, 0, 2],
+                         [3, 3, 0, 0]])
+    output = ndimage.median(a, labels=labels)
+    assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+def test_median_gh12836_bool(xp):
+    # test boolean addition fix on example from gh-12836
+    a = np.asarray([1, 1], dtype=bool)
+    a = xp.asarray(a)
+    output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
+    assert_array_almost_equal(output, xp.asarray([1.0]))
+
+
+def test_median_no_int_overflow(xp):
+    # test integer overflow fix on example from gh-12836
+    a = xp.asarray([65, 70], dtype=xp.int8)
+    output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
+    assert_array_almost_equal(output, xp.asarray([67.5]))
+
+
+def test_variance01(xp):
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([], dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                output = ndimage.variance(input)
+            assert xp.isnan(output)
+
+
+def test_variance02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1], dtype=dtype)
+        output = ndimage.variance(input)
+        assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
+
+
+def test_variance03(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 3], dtype=dtype)
+        output = ndimage.variance(input)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_variance04(xp):
+    input = np.asarray([1, 0], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.variance(input)
+    assert_almost_equal(output, xp.asarray(0.25), check_0d=False)
+
+
+def test_variance05(xp):
+    labels = xp.asarray([2, 2, 3])
+    for type in types:
+        dtype = getattr(xp, type)
+
+        input = xp.asarray([1, 3, 8], dtype=dtype)
+        output = ndimage.variance(input, labels, 2)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_variance06(xp):
+    labels = xp.asarray([2, 2, 3, 3, 4])
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
+            output = ndimage.variance(input, labels, xp.asarray([2, 3, 4]))
+            assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
+
+
+def test_standard_deviation01(xp):
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([], dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                output = ndimage.standard_deviation(input)
+            assert xp.isnan(output)
+
+
+def test_standard_deviation02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1], dtype=dtype)
+        output = ndimage.standard_deviation(input)
+        assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
+
+
+def test_standard_deviation03(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 3], dtype=dtype)
+        output = ndimage.standard_deviation(input)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_standard_deviation04(xp):
+    input = np.asarray([1, 0], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.standard_deviation(input)
+    assert_almost_equal(output, xp.asarray(0.5), check_0d=False)
+
+
+def test_standard_deviation05(xp):
+    labels = xp.asarray([2, 2, 3])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 3, 8], dtype=dtype)
+        output = ndimage.standard_deviation(input, labels, 2)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_standard_deviation06(xp):
+    labels = xp.asarray([2, 2, 3, 3, 4])
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
+            output = ndimage.standard_deviation(
+                input, labels, xp.asarray([2, 3, 4])
+            )
+            assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
+
+
+def test_standard_deviation07(xp):
+    labels = xp.asarray([1])
+    with np.errstate(all='ignore'):
+        for type in types:
+            if is_torch(xp) and type == 'uint8':
+                pytest.xfail("value cannot be converted to type uint8 "
+                             "without overflow")
+            dtype = getattr(xp, type)
+            input = xp.asarray([-0.00619519], dtype=dtype)
+            output = ndimage.standard_deviation(input, labels, xp.asarray([1]))
+            assert_array_almost_equal(output, xp.asarray([0]))
+
+
+def test_minimum_position01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.minimum_position(input, labels=labels)
+        assert output == (0, 0)
+
+
+def test_minimum_position02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 0, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.minimum_position(input)
+        assert output == (1, 2)
+
+
+def test_minimum_position03(xp):
+    input = np.asarray([[5, 4, 2, 5],
+                        [3, 7, 0, 2],
+                        [1, 5, 1, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.minimum_position(input)
+    assert output == (1, 2)
+
+
+def test_minimum_position04(xp):
+    input = np.asarray([[5, 4, 2, 5],
+                        [3, 7, 1, 2],
+                        [1, 5, 1, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.minimum_position(input)
+    assert output == (0, 0)
+
+
+def test_minimum_position05(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 0, 2],
+                            [1, 5, 2, 3]], dtype=dtype)
+        output = ndimage.minimum_position(input, labels)
+        assert output == (2, 0)
+
+
+def test_minimum_position06(xp):
+    labels = xp.asarray([1, 2, 3, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 0, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.minimum_position(input, labels, 2)
+        assert output == (0, 1)
+
+
+def test_minimum_position07(xp):
+    labels = xp.asarray([1, 2, 3, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 0, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.minimum_position(input, labels,
+                                          xp.asarray([2, 3]))
+        assert output[0] == (0, 1)
+        assert output[1] == (1, 2)
+
+
+def test_maximum_position01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.maximum_position(input,
+                                          labels=labels)
+        assert output == (1, 0)
+
+
+def test_maximum_position02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input)
+        assert output == (1, 2)
+
+
+def test_maximum_position03(xp):
+    input = np.asarray([[5, 4, 2, 5],
+                        [3, 7, 8, 2],
+                        [1, 5, 1, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.maximum_position(input)
+    assert output == (0, 0)
+
+
+def test_maximum_position04(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input, labels)
+        assert output == (1, 1)
+
+
+def test_maximum_position05(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input, labels, 1)
+        assert output == (0, 0)
+
+
+def test_maximum_position06(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input, labels,
+                                          xp.asarray([1, 2]))
+        assert output[0] == (0, 0)
+        assert output[1] == (1, 1)
+
+
+def test_maximum_position07(xp):
+    # Test float labels
+    if is_torch(xp):
+        pytest.xfail("output[1] is wrong on pytorch")
+
+    labels = xp.asarray([1.0, 2.5, 0.0, 4.5])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input, labels,
+                                          xp.asarray([1.0, 4.5]))
+        assert output[0] == (0, 0)
+        assert output[1] == (0, 3)
+
+
+def test_extrema01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output1 = ndimage.extrema(input, labels=labels)
+        output2 = ndimage.minimum(input, labels=labels)
+        output3 = ndimage.maximum(input, labels=labels)
+        output4 = ndimage.minimum_position(input,
+                                           labels=labels)
+        output5 = ndimage.maximum_position(input,
+                                           labels=labels)
+        assert output1 == (output2, output3, output4, output5)
+
+
+def test_extrema02(xp):
+    labels = xp.asarray([1, 2])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output1 = ndimage.extrema(input, labels=labels,
+                                  index=2)
+        output2 = ndimage.minimum(input, labels=labels,
+                                  index=2)
+        output3 = ndimage.maximum(input, labels=labels,
+                                  index=2)
+        output4 = ndimage.minimum_position(input,
+                                           labels=labels, index=2)
+        output5 = ndimage.maximum_position(input,
+                                           labels=labels, index=2)
+        assert output1 == (output2, output3, output4, output5)
+
+
+def test_extrema03(xp):
+    labels = xp.asarray([[1, 2], [2, 3]])
+    for type in types:
+        if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
+             pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output1 = ndimage.extrema(input,
+                                  labels=labels,
+                                  index=xp.asarray([2, 3, 8]))
+        output2 = ndimage.minimum(input,
+                                  labels=labels,
+                                  index=xp.asarray([2, 3, 8]))
+        output3 = ndimage.maximum(input, labels=labels,
+                                  index=xp.asarray([2, 3, 8]))
+        output4 = ndimage.minimum_position(input,
+                                           labels=labels,
+                                           index=xp.asarray([2, 3, 8]))
+        output5 = ndimage.maximum_position(input,
+                                           labels=labels,
+                                           index=xp.asarray([2, 3, 8]))
+        assert_array_almost_equal(output1[0], output2)
+        assert_array_almost_equal(output1[1], output3)
+        assert output1[2] == output4
+        assert output1[3] == output5
+
+
+def test_extrema04(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
+             pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output1 = ndimage.extrema(input, labels, xp.asarray([1, 2]))
+        output2 = ndimage.minimum(input, labels, xp.asarray([1, 2]))
+        output3 = ndimage.maximum(input, labels, xp.asarray([1, 2]))
+        output4 = ndimage.minimum_position(input, labels,
+                                           xp.asarray([1, 2]))
+        output5 = ndimage.maximum_position(input, labels,
+                                           xp.asarray([1, 2]))
+        assert_array_almost_equal(output1[0], output2)
+        assert_array_almost_equal(output1[1], output3)
+        assert output1[2] == output4
+        assert output1[3] == output5
+
+
+def test_center_of_mass01(xp):
+    expected = (0.0, 0.0)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 0], [0, 0]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass02(xp):
+    expected = (1, 0)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[0, 0], [1, 0]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass03(xp):
+    expected = (0, 1)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[0, 1], [0, 0]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass04(xp):
+    expected = (1, 1)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[0, 0], [0, 1]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass05(xp):
+    expected = (0.5, 0.5)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 1], [1, 1]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass06(xp):
+    expected = (0.5, 0.5)
+    input = np.asarray([[1, 2], [3, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.center_of_mass(input)
+    assert output == expected
+
+
+def test_center_of_mass07(xp):
+    labels = xp.asarray([1, 0])
+    expected = (0.5, 0.0)
+    input = np.asarray([[1, 2], [3, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.center_of_mass(input, labels)
+    assert output == expected
+
+
+def test_center_of_mass08(xp):
+    labels = xp.asarray([1, 2])
+    expected = (0.5, 1.0)
+    input = np.asarray([[5, 2], [3, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.center_of_mass(input, labels, 2)
+    assert output == expected
+
+
+def test_center_of_mass09(xp):
+    labels = xp.asarray((1, 2))
+    expected = xp.asarray([(0.5, 0.0), (0.5, 1.0)], dtype=xp.float64)
+    input = np.asarray([[1, 2], [1, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.center_of_mass(input, labels, xp.asarray([1, 2]))
+    xp_assert_equal(xp.asarray(output), xp.asarray(expected))
+
+
+def test_histogram01(xp):
+    expected = xp.ones(10)
+    input = xp.arange(10)
+    output = ndimage.histogram(input, 0, 10, 10)
+    assert_array_almost_equal(output, expected)
+
+
+def test_histogram02(xp):
+    labels = xp.asarray([1, 1, 1, 1, 2, 2, 2, 2])
+    expected = xp.asarray([0, 2, 0, 1, 1])
+    input = xp.asarray([1, 1, 3, 4, 3, 3, 3, 3])
+    output = ndimage.histogram(input, 0, 4, 5, labels, 1)
+    assert_array_almost_equal(output, expected)
+
+
+@skip_xp_backends(np_only=True, reason='object arrays')
+def test_histogram03(xp):
+    labels = xp.asarray([1, 0, 1, 1, 2, 2, 2, 2])
+    expected1 = xp.asarray([0, 1, 0, 1, 1])
+    expected2 = xp.asarray([0, 0, 0, 3, 0])
+    input = xp.asarray([1, 1, 3, 4, 3, 5, 3, 3])
+
+    output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2))
+
+    assert_array_almost_equal(output[0], expected1)
+    assert_array_almost_equal(output[1], expected2)
+
+
+def test_stat_funcs_2d(xp):
+    a = xp.asarray([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]])
+    lbl = xp.asarray([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]])
+
+    mean = ndimage.mean(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(mean, xp.asarray([7.0, 4.0], dtype=xp.float64))
+
+    var = ndimage.variance(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(var, xp.asarray([2.5, 1.0], dtype=xp.float64))
+
+    std = ndimage.standard_deviation(a, labels=lbl, index=xp.asarray([1, 2]))
+    assert_array_almost_equal(std, xp.sqrt(xp.asarray([2.5, 1.0], dtype=xp.float64)))
+
+    med = ndimage.median(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(med, xp.asarray([7.0, 4.0], dtype=xp.float64))
+
+    min = ndimage.minimum(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(min, xp.asarray([5, 3]), check_dtype=False)
+
+    max = ndimage.maximum(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(max, xp.asarray([9, 5]), check_dtype=False)
+
+
+@skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+class TestWatershedIft:
+
+    def test_watershed_ift01(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.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, 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],
+                              [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+        structure=xp.asarray([[1, 1, 1],
+                              [1, 1, 1],
+                              [1, 1, 1]])
+        out = ndimage.watershed_ift(data, markers, structure=structure)
+        expected = [[-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]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift02(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.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, 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],
+                              [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+        out = ndimage.watershed_ift(data, markers)
+        expected = [[-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]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift03(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 2, 0, 3, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, -1]], dtype=xp.int8)
+        out = ndimage.watershed_ift(data, markers)
+        expected = [[-1, -1, -1, -1, -1, -1, -1],
+                    [-1, -1, 2, -1, 3, -1, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, -1, 2, -1, 3, -1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift04(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 2, 0, 3, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, -1]],
+                             dtype=xp.int8)
+
+        structure=xp.asarray([[1, 1, 1],
+                              [1, 1, 1],
+                              [1, 1, 1]])
+        out = ndimage.watershed_ift(data, markers, structure=structure)
+        expected = [[-1, -1, -1, -1, -1, -1, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift05(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 3, 0, 2, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, -1]],
+                             dtype=xp.int8)
+        structure = xp.asarray([[1, 1, 1],
+                                [1, 1, 1],
+                                [1, 1, 1]])
+        out = ndimage.watershed_ift(data, markers, structure=structure)
+        expected = [[-1, -1, -1, -1, -1, -1, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift06(self, xp):
+        data = xp.asarray([[0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[-1, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+        structure=xp.asarray([[1, 1, 1],
+                              [1, 1, 1],
+                              [1, 1, 1]])
+        out = ndimage.watershed_ift(data, markers, structure=structure)
+        expected = [[-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]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    @skip_xp_backends(np_only=True, reason="inplace ops are numpy-specific")
+    def test_watershed_ift07(self, xp):
+        shape = (7, 6)
+        data = np.zeros(shape, dtype=np.uint8)
+        data = data.transpose()
+        data[...] = np.asarray([[0, 1, 0, 0, 0, 1, 0],
+                                [0, 1, 0, 0, 0, 1, 0],
+                                [0, 1, 0, 0, 0, 1, 0],
+                                [0, 1, 1, 1, 1, 1, 0],
+                                [0, 0, 0, 0, 0, 0, 0],
+                                [0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
+        data = xp.asarray(data)
+        markers = xp.asarray([[-1, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+        out = xp.zeros(shape, dtype=xp.int16)
+        out = out.T
+        structure=xp.asarray([[1, 1, 1],
+                              [1, 1, 1],
+                              [1, 1, 1]])
+        ndimage.watershed_ift(data, markers, structure=structure,
+                              output=out)
+        expected = [[-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]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+    def test_watershed_ift08(self, xp):
+        # Test cost larger than uint8. See gh-10069.
+        data = xp.asarray([[256, 0],
+                           [0, 0]], dtype=xp.uint16)
+        markers = xp.asarray([[1, 0],
+                              [0, 0]], dtype=xp.int8)
+        out = ndimage.watershed_ift(data, markers)
+        expected = [[1, 1],
+                    [1, 1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    @skip_xp_backends("cupy", reason="no watershed_ift on CuPy"	)
+    def test_watershed_ift09(self, xp):
+        # Test large cost. See gh-19575
+        data = xp.asarray([[xp.iinfo(xp.uint16).max, 0],
+                           [0, 0]], dtype=xp.uint16)
+        markers = xp.asarray([[1, 0],
+                              [0, 0]], dtype=xp.int8)
+        out = ndimage.watershed_ift(data, markers)
+        expected = [[1, 1],
+                    [1, 1]]
+        xp_assert_close(out, xp.asarray(expected), check_dtype=False)
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.parametrize("dt", [np.intc, np.uintc])
+def test_gh_19423(dt, xp):
+    rng = np.random.default_rng(123)
+    max_val = 8
+    image = rng.integers(low=0, high=max_val, size=(10, 12)).astype(dtype=dt)
+    val_idx = ndimage.value_indices(image)
+    assert len(val_idx.keys()) == max_val
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..9eff9a2c0f4a05295b7565761292b4ecaac007ac
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py
@@ -0,0 +1,2938 @@
+import numpy as np
+from scipy._lib._array_api import (
+    is_cupy, is_numpy, is_torch, array_namespace,
+    xp_assert_close, xp_assert_equal, assert_array_almost_equal
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy import ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              pytest.mark.usefixtures("xfail_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+class TestNdimageMorphology:
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        # brute force (bf) distance transform
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(data, 'euclidean',
+                                                return_indices=True)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 2, 4, 2, 1, 0, 0],
+                    [0, 0, 1, 4, 8, 4, 1, 0, 0],
+                    [0, 0, 1, 2, 4, 2, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out * out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 1, 2, 2, 2, 2],
+                     [3, 3, 3, 2, 1, 2, 3, 3, 3],
+                     [4, 4, 4, 4, 6, 4, 4, 4, 4],
+                     [5, 5, 6, 6, 7, 6, 6, 5, 5],
+                     [6, 6, 6, 7, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 1, 2, 4, 6, 7, 7, 8],
+                     [0, 1, 1, 1, 6, 7, 7, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(data, 'cityblock',
+                                                return_indices=True)
+
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 2, 2, 2, 1, 0, 0],
+                    [0, 0, 1, 2, 3, 2, 1, 0, 0],
+                    [0, 0, 1, 2, 2, 2, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 1, 2, 2, 2, 2],
+                     [3, 3, 3, 3, 1, 3, 3, 3, 3],
+                     [4, 4, 4, 4, 7, 4, 4, 4, 4],
+                     [5, 5, 6, 7, 7, 7, 6, 5, 5],
+                     [6, 6, 6, 7, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 1, 1, 4, 7, 7, 7, 8],
+                     [0, 1, 1, 1, 4, 7, 7, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(expected, ft)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(data, 'chessboard',
+                                                return_indices=True)
+
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 1, 2, 1, 1, 0, 0],
+                    [0, 0, 1, 2, 2, 2, 1, 0, 0],
+                    [0, 0, 1, 1, 2, 1, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 1, 2, 2, 2, 2],
+                     [3, 3, 4, 2, 2, 2, 4, 3, 3],
+                     [4, 4, 5, 6, 6, 6, 5, 4, 4],
+                     [5, 5, 6, 6, 7, 6, 6, 5, 5],
+                     [6, 6, 6, 7, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 5, 6, 6, 7, 8],
+                     [0, 1, 1, 2, 6, 6, 7, 7, 8],
+                     [0, 1, 1, 2, 6, 7, 7, 7, 8],
+                     [0, 1, 2, 2, 6, 6, 7, 7, 8],
+                     [0, 1, 2, 4, 5, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace distances= arrays are numpy-specific'
+    )
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf04(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        tdt, tft = ndimage.distance_transform_bf(data, return_indices=1)
+        dts = []
+        fts = []
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ndimage.distance_transform_bf(data, distances=dt)
+        dts.append(dt)
+        ft = ndimage.distance_transform_bf(
+            data, return_distances=False, return_indices=1)
+        fts.append(ft)
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ndimage.distance_transform_bf(
+            data, return_distances=False, return_indices=True, indices=ft)
+        fts.append(ft)
+        dt, ft = ndimage.distance_transform_bf(
+            data, return_indices=1)
+        dts.append(dt)
+        fts.append(ft)
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ft = ndimage.distance_transform_bf(
+            data, distances=dt, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+        ft = np.indices(data.shape, dtype=xp.int32)
+        dt = ndimage.distance_transform_bf(
+            data, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ndimage.distance_transform_bf(
+            data, distances=dt, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+        for dt in dts:
+            assert_array_almost_equal(tdt, dt)
+        for ft in fts:
+            assert_array_almost_equal(tft, ft)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(
+            data, 'euclidean', return_indices=True, sampling=[2, 2])
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 4, 4, 4, 0, 0, 0],
+                    [0, 0, 4, 8, 16, 8, 4, 0, 0],
+                    [0, 0, 4, 16, 32, 16, 4, 0, 0],
+                    [0, 0, 4, 8, 16, 8, 4, 0, 0],
+                    [0, 0, 0, 4, 4, 4, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out * out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 1, 2, 2, 2, 2],
+                     [3, 3, 3, 2, 1, 2, 3, 3, 3],
+                     [4, 4, 4, 4, 6, 4, 4, 4, 4],
+                     [5, 5, 6, 6, 7, 6, 6, 5, 5],
+                     [6, 6, 6, 7, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 1, 2, 4, 6, 7, 7, 8],
+                     [0, 1, 1, 1, 6, 7, 7, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf06(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(
+            data, 'euclidean', return_indices=True, sampling=[2, 1])
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 4, 1, 0, 0, 0],
+                    [0, 0, 1, 4, 8, 4, 1, 0, 0],
+                    [0, 0, 1, 4, 9, 4, 1, 0, 0],
+                    [0, 0, 1, 4, 8, 4, 1, 0, 0],
+                    [0, 0, 0, 1, 4, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out * out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 2, 2, 2, 2, 2],
+                     [3, 3, 3, 3, 2, 3, 3, 3, 3],
+                     [4, 4, 4, 4, 4, 4, 4, 4, 4],
+                     [5, 5, 5, 5, 6, 5, 5, 5, 5],
+                     [6, 6, 6, 6, 7, 6, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 6, 6, 6, 7, 8],
+                     [0, 1, 1, 1, 6, 7, 7, 7, 8],
+                     [0, 1, 1, 1, 7, 7, 7, 7, 8],
+                     [0, 1, 1, 1, 6, 7, 7, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    def test_distance_transform_bf07(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf.")
+
+        # test input validation per discussion on PR #13302
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+        with assert_raises(RuntimeError):
+            ndimage.distance_transform_bf(
+                data, return_distances=False, return_indices=False
+            )
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+
+        # chamfer type distance (cdt) transform
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_cdt(
+            data, 'cityblock', return_indices=True)
+        bf = ndimage.distance_transform_bf(data, 'cityblock')
+        assert_array_almost_equal(bf, out)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 1, 1, 1, 2, 2, 2],
+                     [3, 3, 2, 1, 1, 1, 2, 3, 3],
+                     [4, 4, 4, 4, 1, 4, 4, 4, 4],
+                     [5, 5, 5, 5, 7, 7, 6, 5, 5],
+                     [6, 6, 6, 6, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 1, 1, 4, 7, 7, 7, 8],
+                     [0, 1, 1, 1, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_cdt(data, 'chessboard',
+                                                 return_indices=True)
+        bf = ndimage.distance_transform_bf(data, 'chessboard')
+        assert_array_almost_equal(bf, out)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 1, 1, 1, 2, 2, 2],
+                     [3, 3, 2, 2, 1, 2, 2, 3, 3],
+                     [4, 4, 3, 2, 2, 2, 3, 4, 4],
+                     [5, 5, 4, 6, 7, 6, 4, 5, 5],
+                     [6, 6, 6, 6, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 3, 4, 6, 7, 8],
+                     [0, 1, 1, 2, 2, 6, 6, 7, 8],
+                     [0, 1, 1, 1, 2, 6, 7, 7, 8],
+                     [0, 1, 1, 2, 6, 6, 7, 7, 8],
+                     [0, 1, 2, 2, 5, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace indices= arrays are numpy-specific'
+    )
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        tdt, tft = ndimage.distance_transform_cdt(data, return_indices=True)
+        dts = []
+        fts = []
+        dt = xp.zeros(data.shape, dtype=xp.int32)
+        ndimage.distance_transform_cdt(data, distances=dt)
+        dts.append(dt)
+        ft = ndimage.distance_transform_cdt(
+            data, return_distances=False, return_indices=True)
+        fts.append(ft)
+        ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+        ndimage.distance_transform_cdt(
+            data, return_distances=False, return_indices=True, indices=ft)
+        fts.append(ft)
+        dt, ft = ndimage.distance_transform_cdt(
+            data, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+        dt = xp.zeros(data.shape, dtype=xp.int32)
+        ft = ndimage.distance_transform_cdt(
+            data, distances=dt, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+        ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+        dt = ndimage.distance_transform_cdt(
+            data, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+        dt = xp.zeros(data.shape, dtype=xp.int32)
+        ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+        ndimage.distance_transform_cdt(data, distances=dt,
+                                       return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+        for dt in dts:
+            assert_array_almost_equal(tdt, dt)
+        for ft in fts:
+            assert_array_almost_equal(tft, ft)
+
+    @skip_xp_backends(
+        np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+    )
+    def test_distance_transform_cdt04(self, xp):
+        # test input validation per discussion on PR #13302
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+        indices_out = xp.zeros((data.ndim,) + data.shape, dtype=xp.int32)
+        with assert_raises(RuntimeError):
+            ndimage.distance_transform_bf(
+                data,
+                return_distances=True,
+                return_indices=False,
+                indices=indices_out
+            )
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+        elif is_torch(xp):
+            pytest.xfail("int overflow")
+
+        # test custom metric type per discussion on issue #17381
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        metric_arg = xp.ones((3, 3))
+        actual = ndimage.distance_transform_cdt(data, metric=metric_arg)
+        assert xp.sum(actual) == -21
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        # euclidean distance transform (edt)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_edt(data, return_indices=True)
+        bf = ndimage.distance_transform_bf(data, 'euclidean')
+        assert_array_almost_equal(bf, out)
+
+        # np-specific check
+        np_ft = np.asarray(ft)
+        dt = np_ft - np.indices(np_ft.shape[1:], dtype=np_ft.dtype)
+        dt = dt.astype(np.float64)
+        np.multiply(dt, dt, dt)
+        dt = np.add.reduce(dt, axis=0)
+        np.sqrt(dt, dt)
+
+        dt = xp.asarray(dt)
+        assert_array_almost_equal(bf, dt)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace distances= are numpy-specific'
+    )
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        tdt, tft = ndimage.distance_transform_edt(data, return_indices=True)
+        dts = []
+        fts = []
+
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ndimage.distance_transform_edt(data, distances=dt)
+        dts.append(dt)
+
+        ft = ndimage.distance_transform_edt(
+            data, return_distances=0, return_indices=True)
+        fts.append(ft)
+
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ft = xp.asarray(ft)
+        ndimage.distance_transform_edt(
+            data, return_distances=False, return_indices=True, indices=ft)
+        fts.append(ft)
+
+        dt, ft = ndimage.distance_transform_edt(
+            data, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ft = ndimage.distance_transform_edt(
+            data, distances=dt, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ft = xp.asarray(ft)
+        dt = ndimage.distance_transform_edt(
+            data, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ft = xp.asarray(ft)
+        ndimage.distance_transform_edt(
+            data, distances=dt, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+
+        for dt in dts:
+            assert_array_almost_equal(tdt, dt)
+        for ft in fts:
+            assert_array_almost_equal(tft, ft)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2])
+        out = ndimage.distance_transform_edt(data, sampling=[2, 2])
+        assert_array_almost_equal(ref, out)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt4(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1])
+        out = ndimage.distance_transform_edt(data, sampling=[2, 1])
+        assert_array_almost_equal(ref, out)
+
+    def test_distance_transform_edt5(self, xp):
+        # Ticket #954 regression test
+        out = ndimage.distance_transform_edt(False)
+        assert_array_almost_equal(out, [0.])
+
+    @skip_xp_backends(
+        np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+    )
+    def test_distance_transform_edt6(self, xp):
+        # test input validation per discussion on PR #13302
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+        distances_out = xp.zeros(data.shape, dtype=xp.float64)
+        with assert_raises(RuntimeError):
+            ndimage.distance_transform_bf(
+                data,
+                return_indices=True,
+                return_distances=False,
+                distances=distances_out
+            )
+
+    def test_generate_structure01(self, xp):
+        struct = ndimage.generate_binary_structure(0, 1)
+        assert struct == 1
+
+    def test_generate_structure02(self, xp):
+        struct = ndimage.generate_binary_structure(1, 1)
+        assert_array_almost_equal(struct, [1, 1, 1])
+
+    def test_generate_structure03(self, xp):
+        struct = ndimage.generate_binary_structure(2, 1)
+        assert_array_almost_equal(struct, [[0, 1, 0],
+                                           [1, 1, 1],
+                                           [0, 1, 0]])
+
+    def test_generate_structure04(self, xp):
+        struct = ndimage.generate_binary_structure(2, 2)
+        assert_array_almost_equal(struct, [[1, 1, 1],
+                                           [1, 1, 1],
+                                           [1, 1, 1]])
+
+    def test_iterate_structure01(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        out = ndimage.iterate_structure(struct, 2)
+        expected = np.asarray([[0, 0, 1, 0, 0],
+                               [0, 1, 1, 1, 0],
+                               [1, 1, 1, 1, 1],
+                               [0, 1, 1, 1, 0],
+                               [0, 0, 1, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+
+    def test_iterate_structure02(self, xp):
+        struct = [[0, 1],
+                  [1, 1],
+                  [0, 1]]
+        struct = xp.asarray(struct)
+        out = ndimage.iterate_structure(struct, 2)
+        expected = np.asarray([[0, 0, 1],
+                               [0, 1, 1],
+                               [1, 1, 1],
+                               [0, 1, 1],
+                               [0, 0, 1]], dtype=bool)
+        expected = xp.asarray(expected)
+
+        assert_array_almost_equal(out, expected)
+
+    def test_iterate_structure03(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        out = ndimage.iterate_structure(struct, 2, 1)
+        expected = [[0, 0, 1, 0, 0],
+                    [0, 1, 1, 1, 0],
+                    [1, 1, 1, 1, 1],
+                    [0, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out[0], expected)
+        assert out[1] == [2, 2]
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion04(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion06(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion07(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([5], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion08(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([5], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion09(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([0, 0, 0, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion10(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 0, 0, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion11(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion12(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion13(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1, origin=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion14(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion15(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 0, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion16(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 1], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([[1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion17(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 1], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([[0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion18(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 3], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion19(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 3], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion20(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3, 3], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0],
+                                                   [0, 1, 0],
+                                                   [0, 0, 0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion21(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3, 3], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+                                                   [1, 1, 1],
+                                                   [1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion22(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[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, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion23(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = ndimage.generate_binary_structure(2, 2)
+        struct = xp.asarray(struct)
+        expected = [[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, 1, 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, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion24(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = xp.asarray([[0, 1],
+                             [1, 1]])
+        expected = [[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, 1, 1, 1],
+                    [0, 0, 0, 1, 1, 1, 0, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 1, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion25(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1, 0],
+                  [1, 0, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[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, 1, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 0, 1, 1],
+                           [0, 0, 1, 0, 1, 1, 0, 0],
+                           [0, 1, 0, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion26(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1, 0],
+                  [1, 0, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 1],
+                    [0, 0, 0, 0, 1, 0, 0, 1],
+                    [0, 0, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 0, 0, 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, 0, 0, 1]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 0, 1, 1],
+                           [0, 0, 1, 0, 1, 1, 0, 0],
+                           [0, 1, 0, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, struct, border_value=1,
+                                     origin=(-1, -1))
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion27(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct, border_value=1,
+                                     iterations=2)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion28(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=2, output=out)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion29(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct,
+                                     border_value=1, iterations=3)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion30(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=3, output=out)
+        assert_array_almost_equal(out, expected)
+
+        # test with output memory overlap
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=3, output=data)
+        assert_array_almost_equal(data, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion31(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 1, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 0, 0],
+                    [1, 1, 1, 1, 1, 0, 1],
+                    [0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 1]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=1, output=out, origin=(-1, -1))
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion32(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct,
+                                     border_value=1, iterations=2)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion33(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 1, 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, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        mask = [[1, 1, 1, 1, 1, 0, 0],
+                [1, 1, 1, 1, 1, 1, 0],
+                [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]]
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 0, 0, 0, 0, 1, 1],
+                           [0, 0, 0, 1, 0, 0, 1],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct,
+                                     border_value=1, mask=mask, iterations=-1)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion34(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        mask = [[0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0],
+                [0, 0, 1, 0, 1, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0]]
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct,
+                                     border_value=1, mask=mask)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion35(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        mask = [[0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0],
+                [0, 0, 1, 0, 1, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0]]
+        mask = np.asarray(mask, dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        tmp = [[0, 0, 1, 0, 0, 0, 0],
+               [0, 1, 1, 1, 0, 0, 0],
+               [1, 1, 1, 1, 1, 0, 1],
+               [0, 1, 1, 1, 0, 0, 0],
+               [0, 0, 1, 0, 0, 0, 0],
+               [0, 0, 0, 0, 0, 0, 0],
+               [0, 0, 1, 0, 0, 0, 1]]
+        tmp = np.asarray(tmp, dtype=bool)
+        tmp = xp.asarray(tmp)
+        expected = xp.logical_and(tmp, mask)
+        tmp = xp.logical_and(data, xp.logical_not(mask))
+        expected = xp.logical_or(expected, tmp)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=1, output=out,
+                               origin=(-1, -1), mask=mask)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion36(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 0, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        mask = [[0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0, 0],
+                [0, 0, 1, 0, 1, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0]]
+        mask = np.asarray(mask, dtype=bool)
+        mask = xp.asarray(mask)
+        tmp = [[0, 0, 0, 0, 0, 0, 0, 0],
+               [0, 0, 0, 0, 0, 0, 0, 1],
+               [0, 0, 0, 0, 1, 0, 0, 1],
+               [0, 0, 1, 0, 0, 0, 0, 0],
+               [0, 1, 0, 0, 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, 0, 0, 1]]
+        tmp = np.asarray(tmp, dtype=bool)
+        tmp = xp.asarray(tmp)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                            [0, 1, 0, 0, 0, 0, 0, 0],
+                            [0, 0, 0, 0, 0, 1, 1, 1],
+                            [0, 0, 1, 1, 1, 0, 1, 1],
+                            [0, 0, 1, 0, 1, 1, 0, 0],
+                            [0, 1, 0, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 0, 0, 1, 1, 0],
+                            [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        expected = xp.logical_and(tmp, mask)
+        tmp = xp.logical_and(data, xp.logical_not(mask))
+        expected = xp.logical_or(expected, tmp)
+        out = ndimage.binary_erosion(data, struct, mask=mask,
+                                     border_value=1, origin=(-1, -1))
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion37(self, xp):
+        a = np.asarray([[1, 0, 1],
+                        [0, 1, 0],
+                        [1, 0, 1]], dtype=bool)
+        a = xp.asarray(a)
+        b = xp.zeros_like(a)
+        out = ndimage.binary_erosion(a, structure=a, output=b, iterations=0,
+                                     border_value=True, brute_force=True)
+        assert out is b
+        xp_assert_equal(
+            ndimage.binary_erosion(a, structure=a, iterations=0,
+                                   border_value=True),
+            b)
+
+    def test_binary_erosion38(self, xp):
+        data = np.asarray([[1, 0, 1],
+                           [0, 1, 0],
+                           [1, 0, 1]], dtype=bool)
+        data = xp.asarray(data)
+        iterations = 2.0
+        with assert_raises(TypeError):
+            _ = ndimage.binary_erosion(data, iterations=iterations)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion39(self, xp):
+        iterations = np.int32(3)
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=iterations, output=out)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion40(self, xp):
+        iterations = np.int64(3)
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=iterations, output=out)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.zeros([], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert out == xp.asarray(False)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation04(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.zeros([1], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation06(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.zeros([3], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([0, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation07(self, dtype, xp):
+        data = np.zeros([3], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation08(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data[3] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation09(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation10(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, origin=-1)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation11(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, origin=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation12(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_dilation(data, struct)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation13(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_dilation(data, struct, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation14(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_dilation(data, struct, origin=-1)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation15(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_dilation(data, struct,
+                                      origin=-1, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation16(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 1], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation17(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.zeros([1, 1], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation18(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 3], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation19(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3, 3], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+                                                   [1, 1, 1],
+                                                   [1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation20(self, dtype, xp):
+        data = np.zeros([3, 3], dtype=dtype)
+        data[1, 1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[0, 1, 0],
+                                                   [1, 1, 1],
+                                                   [0, 1, 0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation21(self, dtype, xp):
+        struct = ndimage.generate_binary_structure(2, 2)
+        struct = xp.asarray(struct)
+        data = np.zeros([3, 3], dtype=dtype)
+        data[1, 1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, struct)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+                                                   [1, 1, 1],
+                                                   [1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation22(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 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, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation23(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[1, 1, 1, 1, 1, 1, 1, 1],
+                    [1, 1, 1, 0, 0, 0, 0, 1],
+                    [1, 1, 0, 0, 0, 1, 0, 1],
+                    [1, 0, 0, 1, 1, 1, 1, 1],
+                    [1, 0, 1, 1, 1, 1, 0, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1],
+                    [1, 0, 1, 0, 0, 1, 0, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 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, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation24(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[1, 1, 0, 0, 0, 0, 0, 0],
+                    [1, 0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 1, 1, 1, 0, 0, 0],
+                    [1, 1, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 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, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, origin=(1, 1))
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation25(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[1, 1, 0, 0, 0, 0, 1, 1],
+                    [1, 0, 0, 0, 1, 0, 1, 1],
+                    [0, 0, 1, 1, 1, 1, 1, 1],
+                    [0, 1, 1, 1, 1, 0, 1, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1],
+                    [0, 1, 0, 0, 1, 0, 1, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 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, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, origin=(1, 1), border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation26(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = ndimage.generate_binary_structure(2, 2)
+        expected = [[1, 1, 1, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 1, 1, 1, 0],
+                    [0, 0, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 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, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, struct)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation27(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [1, 1, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 1, 0, 1, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 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, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, struct)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation28(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[1, 1, 1, 1],
+                    [1, 0, 0, 1],
+                    [1, 0, 0, 1],
+                    [1, 1, 1, 1]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0],
+                           [0, 0, 0, 0],
+                           [0, 0, 0, 0],
+                           [0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_dilation29(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0],
+                    [0, 0, 1, 1, 0],
+                    [0, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, struct, iterations=2)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    def test_binary_dilation30(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0],
+                    [0, 0, 1, 1, 0],
+                    [0, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_dilation(data, struct, iterations=2, output=out)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_dilation31(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 0, 0, 1, 0],
+                    [0, 0, 1, 1, 0],
+                    [0, 1, 1, 1, 0],
+                    [1, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, struct, iterations=3)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    def test_binary_dilation32(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 0, 0, 1, 0],
+                    [0, 0, 1, 1, 0],
+                    [0, 1, 1, 1, 0],
+                    [1, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_dilation(data, struct, iterations=3, output=out)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_dilation33(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = np.asarray([[0, 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, 0, 0, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 0, 0, 0],
+                               [0, 1, 1, 0, 1, 1, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 1, 1, 0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 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, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 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, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+
+        out = ndimage.binary_dilation(data, struct, iterations=-1,
+                                      mask=mask, border_value=0)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace output= arrays are numpy-specific',
+    )
+    def test_binary_dilation34(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 0, 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, 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]]
+        mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.zeros(mask.shape, dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, struct, iterations=-1,
+                                      mask=mask, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation35(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        tmp = [[1, 1, 0, 0, 0, 0, 1, 1],
+               [1, 0, 0, 0, 1, 0, 1, 1],
+               [0, 0, 1, 1, 1, 1, 1, 1],
+               [0, 1, 1, 1, 1, 0, 1, 1],
+               [1, 1, 1, 1, 1, 1, 1, 1],
+               [0, 1, 0, 0, 1, 0, 1, 1],
+               [1, 1, 1, 1, 1, 1, 1, 1],
+               [1, 1, 1, 1, 1, 1, 1, 1]]
+
+        data = np.asarray([[0, 0, 0, 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, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]])
+        mask = [[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, 1, 1, 1, 1, 0, 0],
+                [0, 0, 1, 1, 1, 1, 0, 0],
+                [0, 0, 1, 1, 1, 1, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0]]
+        mask = np.asarray(mask, dtype=bool)
+
+        expected = np.logical_and(tmp, mask)
+        tmp = np.logical_and(data, np.logical_not(mask))
+        expected = np.logical_or(expected, tmp)
+
+        mask = xp.asarray(mask)
+        expected = xp.asarray(expected)
+
+        data = xp.asarray([[0, 0, 0, 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, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, mask=mask,
+                                      origin=(1, 1), border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_dilation36(self, xp):
+        # gh-21009
+        data = np.zeros([], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, iterations=-1)
+        assert out == xp.asarray(False)
+
+    def test_binary_propagation01(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = np.asarray([[0, 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, 0, 0, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 0, 0, 0],
+                               [0, 1, 1, 0, 1, 1, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 1, 1, 0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 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, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 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, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_propagation(data, struct,
+                                         mask=mask, border_value=0)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_propagation02(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 0, 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, 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]]
+        expected = xp.asarray(expected)
+        struct = xp.asarray(struct)
+        mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.zeros(mask.shape, dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_propagation(data, struct,
+                                         mask=mask, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_propagation03(self, xp):
+        # gh-21009
+        data = xp.asarray(np.zeros([], dtype=bool))
+        expected = xp.asarray(np.zeros([], dtype=bool))
+        out = ndimage.binary_propagation(data)
+        assert out == expected
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_opening01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 0, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_opening(data)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_opening02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = ndimage.generate_binary_structure(2, 2)
+        expected = [[1, 1, 1, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        struct = xp.asarray(struct)
+        data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 0, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_opening(data, struct)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_closing01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 1, 0, 0],
+                    [0, 0, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 0, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_closing(data)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_closing02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = ndimage.generate_binary_structure(2, 2)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        struct = xp.asarray(struct)
+        data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 0, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_closing(data, struct)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_fill_holes01(self, xp):
+        expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+
+        out = ndimage.binary_fill_holes(data)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_fill_holes02(self, xp):
+        expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 1, 1, 0, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 0, 1, 1, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_fill_holes(data)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_fill_holes03(self, xp):
+        expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 1, 0, 0, 0, 0, 0],
+                               [0, 1, 1, 1, 0, 1, 1, 1],
+                               [0, 1, 1, 1, 0, 1, 1, 1],
+                               [0, 1, 1, 1, 0, 1, 1, 1],
+                               [0, 0, 1, 0, 0, 1, 1, 1],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 1, 0, 1, 1, 1],
+                           [0, 1, 0, 1, 0, 1, 0, 1],
+                           [0, 1, 0, 1, 0, 1, 0, 1],
+                           [0, 0, 1, 0, 0, 1, 1, 1],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_fill_holes(data)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(cpu_only=True)
+    @skip_xp_backends(
+        "cupy", reason="these filters do not yet have axes support in CuPy")
+    @skip_xp_backends(
+        "jax.numpy", reason="these filters are not implemented in JAX.numpy")
+    @pytest.mark.parametrize('border_value',[0, 1])
+    @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)])
+    @pytest.mark.parametrize('expand_axis', [0, 1, 2])
+    @pytest.mark.parametrize('func_name', ["binary_erosion",
+                                           "binary_dilation",
+                                           "binary_opening",
+                                           "binary_closing",
+                                           "binary_hit_or_miss",
+                                           "binary_propagation",
+                                           "binary_fill_holes"])
+    def test_binary_axes(self, xp, func_name, expand_axis, origin, border_value):
+        struct = np.asarray([[0, 1, 0],
+                             [1, 1, 1],
+                             [0, 1, 0]], bool)
+        struct = xp.asarray(struct)
+
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 1, 0, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], bool)
+        data = xp.asarray(data)
+        if func_name == "binary_hit_or_miss":
+            kwargs = dict(origin1=origin, origin2=origin)
+        else:
+            kwargs = dict(origin=origin)
+        border_supported = func_name not in ["binary_hit_or_miss",
+                                             "binary_fill_holes"]
+        if border_supported:
+            kwargs['border_value'] = border_value
+        elif border_value != 0:
+            pytest.skip('border_value !=0 unsupported by this function')
+        func = getattr(ndimage, func_name)
+        expected = func(data, struct, **kwargs)
+
+        # replicate data and expected result along a new axis
+        n_reps = 5
+        expected = xp.stack([expected] * n_reps, axis=expand_axis)
+        data = xp.stack([data] * n_reps, axis=expand_axis)
+
+        # filter all axes except expand_axis
+        axes = [0, 1, 2]
+        axes.remove(expand_axis)
+        if is_numpy(xp) or is_cupy(xp):
+            out = xp.asarray(np.zeros(data.shape, bool))
+            func(data, struct, output=out, axes=axes, **kwargs)
+        else:
+            # inplace output= is unsupported by JAX
+            out = func(data, struct, axes=axes, **kwargs)
+        xp_assert_close(out, expected)
+
+    def test_grey_erosion01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.grey_erosion(array, footprint=footprint)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1]]))
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8398")
+    def test_grey_erosion01_overlap(self, xp):
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        ndimage.grey_erosion(array, footprint=footprint, output=array)
+        assert_array_almost_equal(array,
+                                  xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1]])
+        )
+
+    def test_grey_erosion02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        output = ndimage.grey_erosion(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1]])
+        )
+
+    def test_grey_erosion03(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[1, 1, 1], [1, 1, 1]])
+        output = ndimage.grey_erosion(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[1, 1, 0, 0, 0],
+                                              [1, 2, 0, 2, 0],
+                                              [4, 4, 2, 2, 0]])
+        )
+
+    def test_grey_dilation01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+        output = ndimage.grey_dilation(array, footprint=footprint)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[7, 7, 9, 9, 5],
+                                              [7, 9, 8, 9, 7],
+                                              [8, 8, 8, 7, 7]]),
+        )
+
+    def test_grey_dilation02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        output = ndimage.grey_dilation(array, footprint=footprint,
+                                       structure=structure)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[7, 7, 9, 9, 5],
+                                              [7, 9, 8, 9, 7],
+                                              [8, 8, 8, 7, 7]]),
+        )
+
+    def test_grey_dilation03(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+        structure = xp.asarray([[1, 1, 1], [1, 1, 1]])
+        output = ndimage.grey_dilation(array, footprint=footprint,
+                                       structure=structure)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[8, 8, 10, 10, 6],
+                                              [8, 10, 9, 10, 8],
+                                              [9, 9, 9, 8, 8]]),
+        )
+
+    def test_grey_opening01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        tmp = ndimage.grey_erosion(array, footprint=footprint)
+        expected = ndimage.grey_dilation(tmp, footprint=footprint)
+        output = ndimage.grey_opening(array, footprint=footprint)
+        assert_array_almost_equal(output, expected)
+
+    def test_grey_opening02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_erosion(array, footprint=footprint,
+                                   structure=structure)
+        expected = ndimage.grey_dilation(tmp, footprint=footprint,
+                                         structure=structure)
+        output = ndimage.grey_opening(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(output, expected)
+
+    def test_grey_closing01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        tmp = ndimage.grey_dilation(array, footprint=footprint)
+        expected = ndimage.grey_erosion(tmp, footprint=footprint)
+        output = ndimage.grey_closing(array, footprint=footprint)
+        assert_array_almost_equal(expected, output)
+
+    def test_grey_closing02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_dilation(array, footprint=footprint,
+                                    structure=structure)
+        expected = ndimage.grey_erosion(tmp, footprint=footprint,
+                                        structure=structure)
+        output = ndimage.grey_closing(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    def test_morphological_gradient01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+                                     structure=structure)
+        tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+                                    structure=structure)
+        expected = tmp1 - tmp2
+        output = xp.zeros(array.shape, dtype=array.dtype)
+        ndimage.morphological_gradient(array, footprint=footprint,
+                                       structure=structure, output=output)
+        assert_array_almost_equal(expected, output)
+
+    def test_morphological_gradient02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+                                     structure=structure)
+        tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+                                    structure=structure)
+        expected = tmp1 - tmp2
+        output = ndimage.morphological_gradient(array, footprint=footprint,
+                                                structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    def test_morphological_laplace01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+                                     structure=structure)
+        tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+                                    structure=structure)
+        expected = tmp1 + tmp2 - 2 * array
+        output = xp.zeros(array.shape, dtype=array.dtype)
+        ndimage.morphological_laplace(array, footprint=footprint,
+                                      structure=structure, output=output)
+        assert_array_almost_equal(expected, output)
+
+    def test_morphological_laplace02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+                                     structure=structure)
+        tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+                                    structure=structure)
+        expected = tmp1 + tmp2 - 2 * array
+        output = ndimage.morphological_laplace(array, footprint=footprint,
+                                               structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_white_tophat01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_opening(array, footprint=footprint,
+                                   structure=structure)
+        expected = array - tmp
+        output = xp.zeros(array.shape, dtype=array.dtype)
+        ndimage.white_tophat(array, footprint=footprint,
+                             structure=structure, output=output)
+        assert_array_almost_equal(expected, output)
+
+    def test_white_tophat02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_opening(array, footprint=footprint,
+                                   structure=structure)
+        expected = array - tmp
+        output = ndimage.white_tophat(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @xfail_xp_backends('cupy', reason="cupy#8399")
+    def test_white_tophat03(self, xp):
+
+        array = np.asarray([[1, 0, 0, 0, 0, 0, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 0, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 0, 0, 0, 0, 0, 1]], dtype=bool)
+        array = xp.asarray(array)
+        structure = np.ones((3, 3), dtype=bool)
+        structure = xp.asarray(structure)
+        expected = np.asarray([[0, 1, 1, 0, 0, 0, 0],
+                               [1, 0, 0, 1, 1, 1, 0],
+                               [1, 0, 0, 1, 1, 1, 0],
+                               [0, 1, 1, 0, 0, 0, 1],
+                               [0, 1, 1, 0, 1, 0, 1],
+                               [0, 1, 1, 0, 0, 0, 1],
+                               [0, 0, 0, 1, 1, 1, 1]], dtype=bool)
+        expected = xp.asarray(expected)
+
+        output = ndimage.white_tophat(array, structure=structure)
+        xp_assert_equal(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_white_tophat04(self, xp):
+        array = np.eye(5, dtype=bool)
+        structure = np.ones((3, 3), dtype=bool)
+
+        array = xp.asarray(array)
+        structure = xp.asarray(structure)
+
+        # Check that type mismatch is properly handled
+        output = xp.empty_like(array, dtype=xp.float64)
+        ndimage.white_tophat(array, structure=structure, output=output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_black_tophat01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_closing(array, footprint=footprint,
+                                   structure=structure)
+        expected = tmp - array
+        output = xp.zeros(array.shape, dtype=array.dtype)
+        ndimage.black_tophat(array, footprint=footprint,
+                             structure=structure, output=output)
+        assert_array_almost_equal(expected, output)
+
+    def test_black_tophat02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_closing(array, footprint=footprint,
+                                   structure=structure)
+        expected = tmp - array
+        output = ndimage.black_tophat(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8399")
+    def test_black_tophat03(self, xp):
+
+        array = np.asarray([[1, 0, 0, 0, 0, 0, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 0, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 0, 0, 0, 0, 0, 1]], dtype=bool)
+        array = xp.asarray(array)
+        structure = np.ones((3, 3), dtype=bool)
+        structure = xp.asarray(structure)
+        expected = np.asarray([[0, 1, 1, 1, 1, 1, 1],
+                               [1, 0, 0, 0, 0, 0, 1],
+                               [1, 0, 0, 0, 0, 0, 1],
+                               [1, 0, 0, 0, 0, 0, 1],
+                               [1, 0, 0, 0, 1, 0, 1],
+                               [1, 0, 0, 0, 0, 0, 1],
+                               [1, 1, 1, 1, 1, 1, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+
+        output = ndimage.black_tophat(array, structure=structure)
+        xp_assert_equal(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_black_tophat04(self, xp):
+        array = xp.asarray(np.eye(5, dtype=bool))
+        structure = xp.asarray(np.ones((3, 3), dtype=bool))
+
+        # Check that type mismatch is properly handled
+        output = xp.empty_like(array, dtype=xp.float64)
+        ndimage.black_tophat(array, structure=structure, output=output)
+
+    @skip_xp_backends(cpu_only=True)
+    @skip_xp_backends(
+        "cupy", reason="these filters do not yet have axes support in CuPy")
+    @skip_xp_backends(
+        "jax.numpy", reason="these filters are not implemented in JAX.numpy")
+    @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)])
+    @pytest.mark.parametrize('expand_axis', [0, 1, 2])
+    @pytest.mark.parametrize('mode', ['reflect', 'constant', 'nearest',
+                                      'mirror', 'wrap'])
+    @pytest.mark.parametrize('footprint_mode', ['size', 'footprint',
+                                                'structure'])
+    @pytest.mark.parametrize('func_name', ["grey_erosion",
+                                           "grey_dilation",
+                                           "grey_opening",
+                                           "grey_closing",
+                                           "morphological_laplace",
+                                           "morphological_gradient",
+                                           "white_tophat",
+                                           "black_tophat"])
+    def test_grey_axes(self, xp, func_name, expand_axis, origin, footprint_mode,
+                       mode):
+
+        data = xp.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 4, 0, 0, 0],
+                           [0, 0, 2, 1, 0, 2, 0],
+                           [0, 3, 0, 6, 5, 0, 1],
+                           [0, 4, 5, 3, 3, 4, 0],
+                           [0, 0, 9, 3, 0, 0, 0],
+                           [0, 0, 0, 2, 0, 0, 0]])
+        kwargs = dict(origin=origin, mode=mode)
+        if footprint_mode == 'size':
+            kwargs['size'] = (2, 3)
+        else:
+            kwargs['footprint'] = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        if footprint_mode == 'structure':
+            kwargs['structure'] = xp.ones_like(kwargs['footprint'])
+        func = getattr(ndimage, func_name)
+        expected = func(data, **kwargs)
+
+        # replicate data and expected result along a new axis
+        n_reps = 5
+        expected = xp.stack([expected] * n_reps, axis=expand_axis)
+        data = xp.stack([data] * n_reps, axis=expand_axis)
+
+        # filter all axes except expand_axis
+        axes = [0, 1, 2]
+        axes.remove(expand_axis)
+
+        if is_numpy(xp) or is_cupy(xp):
+            out = xp.zeros(expected.shape, dtype=expected.dtype)
+            func(data, output=out, axes=axes, **kwargs)
+        else:
+            # inplace output= is unsupported by JAX
+            out = func(data, axes=axes, **kwargs)
+        xp_assert_close(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_hit_or_miss01(self, dtype, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("inplace output= is numpy-specific")
+
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[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],
+                    [0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 0],
+                           [1, 1, 1, 0, 0],
+                           [0, 1, 0, 1, 1],
+                           [0, 0, 1, 1, 1],
+                           [0, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1],
+                           [0, 0, 0, 0, 0]], dtype=dtype)
+        out = xp.asarray(np.zeros(data.shape, dtype=bool))
+        ndimage.binary_hit_or_miss(data, struct, output=out)
+        assert_array_almost_equal(expected, out)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_hit_or_miss02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        expected = [[0, 0, 0, 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, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0],
+                           [1, 1, 1, 0, 0, 1, 0, 0],
+                           [0, 1, 0, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_hit_or_miss(data, struct)
+        assert_array_almost_equal(expected, out)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_hit_or_miss03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct1 = [[0, 0, 0],
+                   [1, 1, 1],
+                   [0, 0, 0]]
+        struct2 = [[1, 1, 1],
+                   [0, 0, 0],
+                   [1, 1, 1]]
+        expected = [[0, 0, 0, 0, 0, 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, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        struct1 = xp.asarray(struct1)
+        struct2 = xp.asarray(struct2)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_hit_or_miss(data, struct1, struct2)
+        assert_array_almost_equal(expected, out)
+
+
+class TestDilateFix:
+
+    # pytest's setup_method seems to clash with the autouse `xp` fixture
+    # so call _setup manually from all methods
+    def _setup(self, xp):
+        # dilation related setup
+        self.array = xp.asarray([[0, 0, 0, 0, 0],
+                                 [0, 0, 0, 0, 0],
+                                 [0, 0, 0, 1, 0],
+                                 [0, 0, 1, 1, 0],
+                                 [0, 0, 0, 0, 0]], dtype=xp.uint8)
+
+        self.sq3x3 = xp.ones((3, 3))
+        dilated3x3 = ndimage.binary_dilation(self.array, structure=self.sq3x3)
+
+        if is_numpy(xp):
+            self.dilated3x3 = dilated3x3.view(xp.uint8)
+        else:
+            astype = array_namespace(dilated3x3).astype
+            self.dilated3x3 = astype(dilated3x3, xp.uint8)
+
+
+    def test_dilation_square_structure(self, xp):
+        self._setup(xp)
+        result = ndimage.grey_dilation(self.array, structure=self.sq3x3)
+        # +1 accounts for difference between grey and binary dilation
+        assert_array_almost_equal(result, self.dilated3x3 + 1)
+
+    def test_dilation_scalar_size(self, xp):
+        self._setup(xp)
+        result = ndimage.grey_dilation(self.array, size=3)
+        assert_array_almost_equal(result, self.dilated3x3)
+
+
+class TestBinaryOpeningClosing:
+
+    def _setup(self, xp):
+        a = np.zeros((5, 5), dtype=bool)
+        a[1:4, 1:4] = True
+        a[4, 4] = True
+        self.array = xp.asarray(a)
+        self.sq3x3 = xp.ones((3, 3))
+        self.opened_old = ndimage.binary_opening(self.array, self.sq3x3,
+                                                 1, None, 0)
+        self.closed_old = ndimage.binary_closing(self.array, self.sq3x3,
+                                                 1, None, 0)
+
+    def test_opening_new_arguments(self, xp):
+        self._setup(xp)
+        opened_new = ndimage.binary_opening(self.array, self.sq3x3, 1, None,
+                                            0, None, 0, False)
+        xp_assert_equal(opened_new, self.opened_old)
+
+    def test_closing_new_arguments(self, xp):
+        self._setup(xp)
+        closed_new = ndimage.binary_closing(self.array, self.sq3x3, 1, None,
+                                            0, None, 0, False)
+        xp_assert_equal(closed_new, self.closed_old)
+
+
+def test_binary_erosion_noninteger_iterations(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    data = xp.ones([1])
+    assert_raises(TypeError, ndimage.binary_erosion, data, iterations=0.5)
+    assert_raises(TypeError, ndimage.binary_erosion, data, iterations=1.5)
+
+
+def test_binary_dilation_noninteger_iterations(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    data = xp.ones([1])
+    assert_raises(TypeError, ndimage.binary_dilation, data, iterations=0.5)
+    assert_raises(TypeError, ndimage.binary_dilation, data, iterations=1.5)
+
+
+def test_binary_opening_noninteger_iterations(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    data = xp.ones([1])
+    assert_raises(TypeError, ndimage.binary_opening, data, iterations=0.5)
+    assert_raises(TypeError, ndimage.binary_opening, data, iterations=1.5)
+
+
+def test_binary_closing_noninteger_iterations(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    data = xp.ones([1])
+    assert_raises(TypeError, ndimage.binary_closing, data, iterations=0.5)
+    assert_raises(TypeError, ndimage.binary_closing, data, iterations=1.5)
+
+
+def test_binary_closing_noninteger_brute_force_passes_when_true(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    if is_cupy(xp):
+        pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+    data = xp.ones([1])
+
+    xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=1.5),
+                    ndimage.binary_erosion(data, iterations=2, brute_force=bool(1.5))
+    )
+    xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=0.0),
+                    ndimage.binary_erosion(data, iterations=2, brute_force=bool(0.0))
+    )
+
+
+@pytest.mark.parametrize(
+    'function',
+    ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing'],
+)
+@pytest.mark.parametrize('iterations', [1, 5])
+@pytest.mark.parametrize('brute_force', [False, True])
+def test_binary_input_as_output(function, iterations, brute_force, xp):
+    rstate = np.random.RandomState(123)
+    data = rstate.randint(low=0, high=2, size=100).astype(bool)
+    ndi_func = getattr(ndimage, function)
+
+    # input data is not modified
+    data_orig = data.copy()
+    expected = ndi_func(data, brute_force=brute_force, iterations=iterations)
+    xp_assert_equal(data, data_orig)
+
+    # data should now contain the expected result
+    ndi_func(data, brute_force=brute_force, iterations=iterations, output=data)
+    xp_assert_equal(expected, data)
+
+
+def test_binary_hit_or_miss_input_as_output(xp):
+    if not (is_numpy(xp) or is_cupy(xp)):
+        pytest.xfail("inplace output= is numpy-specific")
+
+    rstate = np.random.RandomState(123)
+    data = rstate.randint(low=0, high=2, size=100).astype(bool)
+
+    # input data is not modified
+    data_orig = data.copy()
+    expected = ndimage.binary_hit_or_miss(data)
+    xp_assert_equal(data, data_orig)
+
+    # data should now contain the expected result
+    ndimage.binary_hit_or_miss(data, output=data)
+    xp_assert_equal(expected, data)
+
+
+def test_distance_transform_cdt_invalid_metric(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not have distance_transform_cdt")
+
+    msg = 'invalid metric provided'
+    with pytest.raises(ValueError, match=msg):
+        ndimage.distance_transform_cdt(xp.ones((5, 5)),
+                                       metric="garbage")
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..426d1cf0eccd1ac0f10a90412f008f4b3463c333
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py
@@ -0,0 +1,78 @@
+import pytest
+
+import numpy as np
+from .._ni_support import _get_output
+
+
+@pytest.mark.parametrize(
+    'dtype',
+    [
+        # String specifiers
+        'f4', 'float32', 'complex64', 'complex128',
+        # Type and dtype specifiers
+        np.float32, float, np.dtype('f4'),
+        # Derive from input
+        None,
+    ],
+)
+def test_get_output_basic(dtype):
+    shape = (2, 3)
+
+    input_ = np.zeros(shape, dtype='float32')
+
+    # For None, derive dtype from input
+    expected_dtype = 'float32' if dtype is None else dtype
+
+    # Output is dtype-specifier, retrieve shape from input
+    result = _get_output(dtype, input_)
+    assert result.shape == shape
+    assert result.dtype == np.dtype(expected_dtype)
+
+    # Output is dtype specifier, with explicit shape, overriding input
+    result = _get_output(dtype, input_, shape=(3, 2))
+    assert result.shape == (3, 2)
+    assert result.dtype == np.dtype(expected_dtype)
+
+    # Output is pre-allocated array, return directly
+    output = np.zeros(shape, dtype=dtype)
+    result = _get_output(output, input_)
+    assert result is output
+
+
+@pytest.mark.thread_unsafe
+def test_get_output_complex():
+    shape = (2, 3)
+
+    input_ = np.zeros(shape)
+
+    # None, promote input type to complex
+    result = _get_output(None, input_, complex_output=True)
+    assert result.shape == shape
+    assert result.dtype == np.dtype('complex128')
+
+    # Explicit type, promote type to complex
+    with pytest.warns(UserWarning, match='promoting specified output dtype to complex'):
+        result = _get_output(float, input_, complex_output=True)
+    assert result.shape == shape
+    assert result.dtype == np.dtype('complex128')
+
+    # String specifier, simply verify complex output
+    result = _get_output('complex64', input_, complex_output=True)
+    assert result.shape == shape
+    assert result.dtype == np.dtype('complex64')
+
+
+def test_get_output_error_cases():
+    input_ = np.zeros((2, 3), 'float32')
+
+    # Two separate paths can raise the same error
+    with pytest.raises(RuntimeError, match='output must have complex dtype'):
+        _get_output('float32', input_, complex_output=True)
+    with pytest.raises(RuntimeError, match='output must have complex dtype'):
+        _get_output(np.zeros((2, 3)), input_, complex_output=True)
+
+    with pytest.raises(RuntimeError, match='output must have numeric dtype'):
+        _get_output('void', input_)
+
+    with pytest.raises(RuntimeError, match='shape not correct'):
+        _get_output(np.zeros((3, 2)), input_)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..2561ba5acef20ac340e06164bae96f187486c06a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py
@@ -0,0 +1,72 @@
+"""Tests for spline filtering."""
+import pytest
+
+import numpy as np
+from scipy._lib._array_api import assert_almost_equal
+
+from scipy import ndimage
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+def get_spline_knot_values(order):
+    """Knot values to the right of a B-spline's center."""
+    knot_values = {0: [1],
+                   1: [1],
+                   2: [6, 1],
+                   3: [4, 1],
+                   4: [230, 76, 1],
+                   5: [66, 26, 1]}
+
+    return knot_values[order]
+
+
+def make_spline_knot_matrix(xp, n, order, mode='mirror'):
+    """Matrix to invert to find the spline coefficients."""
+    knot_values = get_spline_knot_values(order)
+
+    # NB: do computations with numpy, convert to xp as the last step only
+
+    matrix = np.zeros((n, n))
+    for diag, knot_value in enumerate(knot_values):
+        indices = np.arange(diag, n)
+        if diag == 0:
+            matrix[indices, indices] = knot_value
+        else:
+            matrix[indices, indices - diag] = knot_value
+            matrix[indices - diag, indices] = knot_value
+
+    knot_values_sum = knot_values[0] + 2 * sum(knot_values[1:])
+
+    if mode == 'mirror':
+        start, step = 1, 1
+    elif mode == 'reflect':
+        start, step = 0, 1
+    elif mode == 'grid-wrap':
+        start, step = -1, -1
+    else:
+        raise ValueError(f'unsupported mode {mode}')
+
+    for row in range(len(knot_values) - 1):
+        for idx, knot_value in enumerate(knot_values[row + 1:]):
+            matrix[row, start + step*idx] += knot_value
+            matrix[-row - 1, -start - 1 - step*idx] += knot_value
+
+    return xp.asarray(matrix / knot_values_sum)
+
+
+@pytest.mark.parametrize('order', [0, 1, 2, 3, 4, 5])
+@pytest.mark.parametrize('mode', ['mirror', 'grid-wrap', 'reflect'])
+def test_spline_filter_vs_matrix_solution(order, mode, xp):
+    n = 100
+    eye = xp.eye(n, dtype=xp.float64)
+    spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order,
+                                                   mode=mode)
+    spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order,
+                                                   mode=mode)
+    matrix = make_spline_knot_matrix(xp, n, order, mode=mode)
+    assert_almost_equal(eye, spline_filter_axis_0 @ matrix)
+    assert_almost_equal(eye, spline_filter_axis_1 @ matrix.T)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py
new file mode 100644
index 0000000000000000000000000000000000000000..42d3d830d0e39797832472b9e039259111cfccc8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py
@@ -0,0 +1,480 @@
+"""Helpers to utilize existing stft / istft tests for testing `ShortTimeFFT`.
+
+This module provides the functions stft_compare() and istft_compare(), which,
+compares the output between the existing (i)stft() and the shortTimeFFT based
+_(i)stft_wrapper() implementations in this module.
+
+For testing add the following imports to the file ``tests/test_spectral.py``::
+
+    from ._scipy_spectral_test_shim import stft_compare as stft
+    from ._scipy_spectral_test_shim import istft_compare as istft
+
+and remove the existing imports of stft and istft.
+
+The idea of these wrappers is not to provide a backward-compatible interface
+but to demonstrate that the ShortTimeFFT implementation is at least as capable
+as the existing one and delivers comparable results. Furthermore, the
+wrappers highlight the different philosophies of the implementations,
+especially in the border handling.
+"""
+import platform
+from typing import cast, Literal
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.signal import ShortTimeFFT
+from scipy.signal import csd, get_window, stft, istft
+from scipy.signal._arraytools import const_ext, even_ext, odd_ext, zero_ext
+from scipy.signal._short_time_fft import FFT_MODE_TYPE
+from scipy.signal._spectral_py import _spectral_helper, _triage_segments, \
+    _median_bias
+
+
+def _stft_wrapper(x, fs=1.0, window='hann', nperseg=256, noverlap=None,
+                  nfft=None, detrend=False, return_onesided=True,
+                  boundary='zeros', padded=True, axis=-1, scaling='spectrum'):
+    """Wrapper for the SciPy `stft()` function based on `ShortTimeFFT` for
+    unit testing.
+
+    Handling the boundary and padding is where `ShortTimeFFT` and `stft()`
+    differ in behavior. Parts of `_spectral_helper()` were copied to mimic
+    the` stft()` behavior.
+
+    This function is meant to be solely used by `stft_compare()`.
+    """
+    if scaling not in ('psd', 'spectrum'):  # same errors as in original stft:
+        raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!")
+
+    # The following lines are taken from the original _spectral_helper():
+    boundary_funcs = {'even': even_ext,
+                      'odd': odd_ext,
+                      'constant': const_ext,
+                      'zeros': zero_ext,
+                      None: None}
+
+    if boundary not in boundary_funcs:
+        raise ValueError(f"Unknown boundary option '{boundary}', must be one" +
+                         f" of: {list(boundary_funcs.keys())}")
+    if x.size == 0:
+        return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape)
+
+    if nperseg is not None:  # if specified by user
+        nperseg = int(nperseg)
+        if nperseg < 1:
+            raise ValueError('nperseg must be a positive integer')
+
+    # parse window; if array like, then set nperseg = win.shape
+    win, nperseg = _triage_segments(window, nperseg,
+                                    input_length=x.shape[axis])
+
+    if nfft is None:
+        nfft = nperseg
+    elif nfft < nperseg:
+        raise ValueError('nfft must be greater than or equal to nperseg.')
+    else:
+        nfft = int(nfft)
+
+    if noverlap is None:
+        noverlap = nperseg//2
+    else:
+        noverlap = int(noverlap)
+    if noverlap >= nperseg:
+        raise ValueError('noverlap must be less than nperseg.')
+    nstep = nperseg - noverlap
+    n = x.shape[axis]
+
+    # Padding occurs after boundary extension, so that the extended signal ends
+    # in zeros, instead of introducing an impulse at the end.
+    # I.e. if x = [..., 3, 2]
+    # extend then pad -> [..., 3, 2, 2, 3, 0, 0, 0]
+    # pad then extend -> [..., 3, 2, 0, 0, 0, 2, 3]
+
+    if boundary is not None:
+        ext_func = boundary_funcs[boundary]
+        # Extend by nperseg//2 in front and back:
+        x = ext_func(x, nperseg//2, axis=axis)
+
+    if padded:
+        # Pad to integer number of windowed segments
+        # I.e make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg
+        x = np.moveaxis(x, axis, -1)
+
+        # This is an edge case where shortTimeFFT returns one more time slice
+        # than the Scipy stft() shorten to remove last time slice:
+        if n % 2 == 1 and nperseg % 2 == 1 and noverlap % 2 == 1:
+            x = x[..., : -1]
+
+        nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg
+        zeros_shape = list(x.shape[:-1]) + [nadd]
+        x = np.concatenate((x, np.zeros(zeros_shape)), axis=-1)
+        x = np.moveaxis(x, -1, axis)
+
+    #  ... end original _spectral_helper() code.
+    scale_to = {'spectrum': 'magnitude', 'psd': 'psd'}[scaling]
+
+    if np.iscomplexobj(x) and return_onesided:
+        return_onesided = False
+    # using cast() to make mypy happy:
+    fft_mode = cast(FFT_MODE_TYPE, 'onesided' if return_onesided else 'twosided')
+
+    ST = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft,
+                      scale_to=scale_to, phase_shift=None)
+
+    k_off = nperseg // 2
+    p0 = 0  # ST.lower_border_end[1] + 1
+    nn = x.shape[axis] if padded else n+k_off+1
+    # number of frames akin to legacy stft computation
+    p1 = (x.shape[axis] - nperseg) // nstep + 1 
+
+    detr = None if detrend is False else detrend
+    Sxx = ST.stft_detrend(x, detr, p0, p1, k_offset=k_off, axis=axis)
+    t = ST.t(nn, 0, p1 - p0, k_offset=0 if boundary is not None else k_off)
+    if x.dtype in (np.float32, np.complex64):
+        Sxx = Sxx.astype(np.complex64)
+
+    return ST.f, t, Sxx
+
+
+def _istft_wrapper(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None,
+                   nfft=None, input_onesided=True, boundary=True, time_axis=-1,
+                   freq_axis=-2, scaling='spectrum') -> \
+        tuple[np.ndarray, np.ndarray, tuple[int, int]]:
+    """Wrapper for the SciPy `istft()` function based on `ShortTimeFFT` for
+        unit testing.
+
+    Note that only option handling is implemented as far as to handle the unit
+    tests. E.g., the case ``nperseg=None`` is not handled.
+
+    This function is meant to be solely used by `istft_compare()`.
+    """
+    # *** Lines are taken from _spectral_py.istft() ***:
+    if Zxx.ndim < 2:
+        raise ValueError('Input stft must be at least 2d!')
+
+    if freq_axis == time_axis:
+        raise ValueError('Must specify differing time and frequency axes!')
+
+    nseg = Zxx.shape[time_axis]
+
+    if input_onesided:
+        # Assume even segment length
+        n_default = 2*(Zxx.shape[freq_axis] - 1)
+    else:
+        n_default = Zxx.shape[freq_axis]
+
+    # Check windowing parameters
+    if nperseg is None:
+        nperseg = n_default
+    else:
+        nperseg = int(nperseg)
+        if nperseg < 1:
+            raise ValueError('nperseg must be a positive integer')
+
+    if nfft is None:
+        if input_onesided and (nperseg == n_default + 1):
+            # Odd nperseg, no FFT padding
+            nfft = nperseg
+        else:
+            nfft = n_default
+    elif nfft < nperseg:
+        raise ValueError('nfft must be greater than or equal to nperseg.')
+    else:
+        nfft = int(nfft)
+
+    if noverlap is None:
+        noverlap = nperseg//2
+    else:
+        noverlap = int(noverlap)
+    if noverlap >= nperseg:
+        raise ValueError('noverlap must be less than nperseg.')
+    nstep = nperseg - noverlap
+
+    # Get window as array
+    if isinstance(window, str) or type(window) is tuple:
+        win = get_window(window, nperseg)
+    else:
+        win = np.asarray(window)
+        if len(win.shape) != 1:
+            raise ValueError('window must be 1-D')
+        if win.shape[0] != nperseg:
+            raise ValueError(f'window must have length of {nperseg}')
+
+    outputlength = nperseg + (nseg-1)*nstep
+    # *** End block of: Taken from _spectral_py.istft() ***
+
+    # Using cast() to make mypy happy:
+    fft_mode = cast(FFT_MODE_TYPE, 'onesided' if input_onesided else 'twosided')
+    scale_to = cast(Literal['magnitude', 'psd'],
+                    {'spectrum': 'magnitude', 'psd': 'psd'}[scaling])
+
+    ST = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft,
+                      scale_to=scale_to, phase_shift=None)
+
+    if boundary:
+        j = nperseg if nperseg % 2 == 0 else nperseg - 1
+        k0 = ST.k_min + nperseg // 2
+        k1 = outputlength - j + k0
+    else:
+        raise NotImplementedError("boundary=False does not make sense with" +
+                                  "ShortTimeFFT.istft()!")
+
+    x = ST.istft(Zxx, k0=k0, k1=k1, f_axis=freq_axis, t_axis=time_axis)
+    t = np.arange(k1 - k0) * ST.T
+    k_hi = ST.upper_border_begin(k1 - k0)[0]
+    # using cast() to make mypy happy:
+    return t, x, (ST.lower_border_end[0], k_hi)
+
+
+def _csd_wrapper(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None,
+                 nfft=None, detrend='constant', return_onesided=True,
+                 scaling='density', axis=-1, average='mean'):
+    """Wrapper for the `csd()` function based on `ShortTimeFFT` for
+        unit testing.
+    """
+    freqs, _, Pxy = _csd_test_shim(x, y, fs, window, nperseg, noverlap, nfft,
+                                   detrend, return_onesided, scaling, axis)
+
+    # The following code is taken from csd():
+    if len(Pxy.shape) >= 2 and Pxy.size > 0:
+        if Pxy.shape[-1] > 1:
+            if average == 'median':
+                # np.median must be passed real arrays for the desired result
+                bias = _median_bias(Pxy.shape[-1])
+                if np.iscomplexobj(Pxy):
+                    Pxy = (np.median(np.real(Pxy), axis=-1)
+                           + 1j * np.median(np.imag(Pxy), axis=-1))
+                else:
+                    Pxy = np.median(Pxy, axis=-1)
+                Pxy /= bias
+            elif average == 'mean':
+                Pxy = Pxy.mean(axis=-1)
+            else:
+                raise ValueError(f'average must be "median" or "mean", got {average}')
+        else:
+            Pxy = np.reshape(Pxy, Pxy.shape[:-1])
+
+    return freqs, Pxy
+
+
+def _csd_test_shim(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None,
+                   nfft=None, detrend='constant', return_onesided=True,
+                   scaling='density', axis=-1):
+    """Compare output of  _spectral_helper() and ShortTimeFFT, more
+    precisely _spect_helper_csd() for used in csd_wrapper().
+
+   The motivation of this function is to test if the ShortTimeFFT-based
+   wrapper `_spect_helper_csd()` returns the same values as `_spectral_helper`.
+   This function should only be usd by csd() in (unit) testing.
+   """
+    freqs, t, Pxy = _spectral_helper(x, y, fs, window, nperseg, noverlap, nfft,
+                                     detrend, return_onesided, scaling, axis,
+                                     mode='psd')
+    freqs1, Pxy1 = _spect_helper_csd(x, y, fs, window, nperseg, noverlap, nfft,
+                                     detrend, return_onesided, scaling, axis)
+
+    np.testing.assert_allclose(freqs1, freqs)
+    amax_Pxy = max(np.abs(Pxy).max(), 1) if Pxy.size else 1
+    atol = np.finfo(Pxy.dtype).resolution * amax_Pxy  # needed for large Pxy
+    # for c_ in range(Pxy.shape[-1]):
+    #    np.testing.assert_allclose(Pxy1[:, c_], Pxy[:, c_], atol=atol)
+    np.testing.assert_allclose(Pxy1, Pxy, atol=atol)
+    return freqs, t, Pxy
+
+
+def _spect_helper_csd(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None,
+                      nfft=None, detrend='constant', return_onesided=True,
+                      scaling='density', axis=-1):
+    """Wrapper for replacing _spectral_helper() by using the ShortTimeFFT
+      for use by csd().
+
+    This function should be only used by _csd_test_shim() and is only useful
+    for testing the ShortTimeFFT implementation.
+    """
+
+    # The following lines are taken from the original _spectral_helper():
+    same_data = y is x
+    axis = int(axis)
+
+    # Ensure we have np.arrays, get outdtype
+    x = np.asarray(x)
+    if not same_data:
+        y = np.asarray(y)
+    #     outdtype = np.result_type(x, y, np.complex64)
+    # else:
+    #     outdtype = np.result_type(x, np.complex64)
+
+    if not same_data:
+        # Check if we can broadcast the outer axes together
+        xouter = list(x.shape)
+        youter = list(y.shape)
+        xouter.pop(axis)
+        youter.pop(axis)
+        try:
+            outershape = np.broadcast(np.empty(xouter), np.empty(youter)).shape
+        except ValueError as e:
+            raise ValueError('x and y cannot be broadcast together.') from e
+
+    if same_data:
+        if x.size == 0:
+            return np.empty(x.shape), np.empty(x.shape)
+    else:
+        if x.size == 0 or y.size == 0:
+            outshape = outershape + (min([x.shape[axis], y.shape[axis]]),)
+            emptyout = np.moveaxis(np.empty(outshape), -1, axis)
+            return emptyout, emptyout
+
+    if nperseg is not None:  # if specified by user
+        nperseg = int(nperseg)
+        if nperseg < 1:
+            raise ValueError('nperseg must be a positive integer')
+
+    # parse window; if array like, then set nperseg = win.shape
+    n = x.shape[axis] if same_data else max(x.shape[axis], y.shape[axis])
+    win, nperseg = _triage_segments(window, nperseg, input_length=n)
+
+    if nfft is None:
+        nfft = nperseg
+    elif nfft < nperseg:
+        raise ValueError('nfft must be greater than or equal to nperseg.')
+    else:
+        nfft = int(nfft)
+
+    if noverlap is None:
+        noverlap = nperseg // 2
+    else:
+        noverlap = int(noverlap)
+    if noverlap >= nperseg:
+        raise ValueError('noverlap must be less than nperseg.')
+    nstep = nperseg - noverlap
+
+    if np.iscomplexobj(x) and return_onesided:
+        return_onesided = False
+
+    # using cast() to make mypy happy:
+    fft_mode = cast(FFT_MODE_TYPE, 'onesided' if return_onesided
+                    else 'twosided')
+    scale = {'spectrum': 'magnitude', 'density': 'psd'}[scaling]
+    SFT = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft,
+                       scale_to=scale, phase_shift=None)
+
+    # _spectral_helper() calculates X.conj()*Y instead of X*Y.conj():
+    Pxy = SFT.spectrogram(y, x, detr=None if detrend is False else detrend,
+                          p0=0, p1=(n-noverlap)//SFT.hop, k_offset=nperseg//2,
+                          axis=axis).conj()
+    # Note:
+    # 'onesided2X' scaling of ShortTimeFFT conflicts with the
+    # scaling='spectrum' parameter, since it doubles the squared magnitude,
+    # which in the view of the ShortTimeFFT implementation does not make sense.
+    # Hence, the doubling of the square is implemented here:
+    if return_onesided:
+        f_axis = Pxy.ndim - 1 + axis if axis < 0 else axis
+        Pxy = np.moveaxis(Pxy, f_axis, -1)
+        Pxy[..., 1:-1 if SFT.mfft % 2 == 0 else None] *= 2
+        Pxy = np.moveaxis(Pxy, -1, f_axis)
+
+    return SFT.f, Pxy
+
+
+def stft_compare(x, fs=1.0, window='hann', nperseg=256, noverlap=None,
+                 nfft=None, detrend=False, return_onesided=True,
+                 boundary='zeros', padded=True, axis=-1, scaling='spectrum'):
+    """Assert that the results from the existing `stft()` and `_stft_wrapper()`
+    are close to each other.
+
+    For comparing the STFT values an absolute tolerance of the floating point
+    resolution was added to circumvent problems with the following tests:
+    * For float32 the tolerances are much higher in
+      TestSTFT.test_roundtrip_float32()).
+    * The TestSTFT.test_roundtrip_scaling() has a high relative deviation.
+      Interestingly this did not appear in Scipy 1.9.1 but only in the current
+      development version.
+    """
+    kw = dict(x=x, fs=fs, window=window, nperseg=nperseg, noverlap=noverlap,
+              nfft=nfft, detrend=detrend, return_onesided=return_onesided,
+              boundary=boundary, padded=padded, axis=axis, scaling=scaling)
+    f, t, Zxx = stft(**kw)
+    f_wrapper, t_wrapper, Zxx_wrapper = _stft_wrapper(**kw)
+
+    e_msg_part = " of `stft_wrapper()` differ from `stft()`."
+    assert_allclose(f_wrapper, f, err_msg=f"Frequencies {e_msg_part}")
+    assert_allclose(t_wrapper, t, err_msg=f"Time slices {e_msg_part}")
+
+    # Adapted tolerances to account for:
+    atol = np.finfo(Zxx.dtype).resolution * 2
+    assert_allclose(Zxx_wrapper, Zxx, atol=atol,
+                    err_msg=f"STFT values {e_msg_part}")
+    return f, t, Zxx
+
+
+def istft_compare(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None,
+                  nfft=None, input_onesided=True, boundary=True, time_axis=-1,
+                  freq_axis=-2, scaling='spectrum'):
+    """Assert that the results from the existing `istft()` and
+    `_istft_wrapper()` are close to each other.
+
+    Quirks:
+    * If ``boundary=False`` the comparison is skipped, since it does not
+      make sense with ShortTimeFFT.istft(). Only used in test
+      TestSTFT.test_roundtrip_boundary_extension().
+    * If ShortTimeFFT.istft() decides the STFT is not invertible, the
+      comparison is skipped, since istft() only emits a warning and does not
+      return a correct result. Only used in
+      ShortTimeFFT.test_roundtrip_not_nola().
+    * For comparing the signals an absolute tolerance of the floating point
+      resolution was added to account for the low accuracy of float32 (Occurs
+      only in TestSTFT.test_roundtrip_float32()).
+    """
+    kw = dict(Zxx=Zxx, fs=fs, window=window, nperseg=nperseg,
+              noverlap=noverlap, nfft=nfft, input_onesided=input_onesided,
+              boundary=boundary, time_axis=time_axis, freq_axis=freq_axis,
+              scaling=scaling)
+
+    t, x = istft(**kw)
+    if not boundary:  # skip test_roundtrip_boundary_extension():
+        return t, x  # _istft_wrapper does() not implement this case
+    try:  # if inversion fails, istft() only emits a warning:
+        t_wrapper, x_wrapper, (k_lo, k_hi) = _istft_wrapper(**kw)
+    except ValueError as v:  # Do nothing if inversion fails:
+        if v.args[0] == "Short-time Fourier Transform not invertible!":
+            return t, x
+        raise v
+
+    e_msg_part = " of `istft_wrapper()` differ from `istft()`"
+    assert_allclose(t, t_wrapper, err_msg=f"Sample times {e_msg_part}")
+
+    # Adapted tolerances to account for resolution loss:
+    atol = np.finfo(x.dtype).resolution*2  # instead of default atol = 0
+    rtol = 1e-7  # default for np.allclose()
+
+    # Relax atol on 32-Bit platforms a bit to pass CI tests.
+    #  - Not clear why there are discrepancies (in the FFT maybe?)
+    #  - Not sure what changed on 'i686' since earlier on those test passed
+    if x.dtype == np.float32 and platform.machine() == 'i686':
+        # float32 gets only used by TestSTFT.test_roundtrip_float32() so
+        # we are using the tolerances from there to circumvent CI problems
+        atol, rtol = 1e-4, 1e-5
+    elif platform.machine() in ('aarch64', 'i386', 'i686'):
+        atol = max(atol, 1e-12)  # 2e-15 seems too tight for 32-Bit platforms
+
+    assert_allclose(x_wrapper[k_lo:k_hi], x[k_lo:k_hi], atol=atol, rtol=rtol,
+                    err_msg=f"Signal values {e_msg_part}")
+    return t, x
+
+
+def csd_compare(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None,
+                nfft=None, detrend='constant', return_onesided=True,
+                scaling='density', axis=-1, average='mean'):
+    """Assert that the results from the existing `csd()` and `_csd_wrapper()`
+    are close to each other. """
+    kw = dict(x=x, y=y, fs=fs, window=window, nperseg=nperseg,
+              noverlap=noverlap, nfft=nfft, detrend=detrend,
+              return_onesided=return_onesided, scaling=scaling, axis=axis,
+              average=average)
+    freqs0, Pxy0 = csd(**kw)
+    freqs1, Pxy1 = _csd_wrapper(**kw)
+
+    assert_allclose(freqs1, freqs0)
+    assert_allclose(Pxy1, Pxy0)
+    assert_allclose(freqs1, freqs0)
+    return freqs0, Pxy0
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bda9716e0bc4b6ad3ed0c3954147043b74c421a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_array_tools.py
@@ -0,0 +1,111 @@
+import numpy as np
+
+from scipy._lib._array_api import xp_assert_equal
+from pytest import raises as assert_raises
+
+from scipy.signal._arraytools import (axis_slice, axis_reverse,
+     odd_ext, even_ext, const_ext, zero_ext)
+
+
+class TestArrayTools:
+
+    def test_axis_slice(self):
+        a = np.arange(12).reshape(3, 4)
+
+        s = axis_slice(a, start=0, stop=1, axis=0)
+        xp_assert_equal(s, a[0:1, :])
+
+        s = axis_slice(a, start=-1, axis=0)
+        xp_assert_equal(s, a[-1:, :])
+
+        s = axis_slice(a, start=0, stop=1, axis=1)
+        xp_assert_equal(s, a[:, 0:1])
+
+        s = axis_slice(a, start=-1, axis=1)
+        xp_assert_equal(s, a[:, -1:])
+
+        s = axis_slice(a, start=0, step=2, axis=0)
+        xp_assert_equal(s, a[::2, :])
+
+        s = axis_slice(a, start=0, step=2, axis=1)
+        xp_assert_equal(s, a[:, ::2])
+
+    def test_axis_reverse(self):
+        a = np.arange(12).reshape(3, 4)
+
+        r = axis_reverse(a, axis=0)
+        xp_assert_equal(r, a[::-1, :])
+
+        r = axis_reverse(a, axis=1)
+        xp_assert_equal(r, a[:, ::-1])
+
+    def test_odd_ext(self):
+        a = np.array([[1, 2, 3, 4, 5],
+                      [9, 8, 7, 6, 5]])
+
+        odd = odd_ext(a, 2, axis=1)
+        expected = np.array([[-1, 0, 1, 2, 3, 4, 5, 6, 7],
+                             [11, 10, 9, 8, 7, 6, 5, 4, 3]])
+        xp_assert_equal(odd, expected)
+
+        odd = odd_ext(a, 1, axis=0)
+        expected = np.array([[-7, -4, -1, 2, 5],
+                             [1, 2, 3, 4, 5],
+                             [9, 8, 7, 6, 5],
+                             [17, 14, 11, 8, 5]])
+        xp_assert_equal(odd, expected)
+
+        assert_raises(ValueError, odd_ext, a, 2, axis=0)
+        assert_raises(ValueError, odd_ext, a, 5, axis=1)
+
+    def test_even_ext(self):
+        a = np.array([[1, 2, 3, 4, 5],
+                      [9, 8, 7, 6, 5]])
+
+        even = even_ext(a, 2, axis=1)
+        expected = np.array([[3, 2, 1, 2, 3, 4, 5, 4, 3],
+                             [7, 8, 9, 8, 7, 6, 5, 6, 7]])
+        xp_assert_equal(even, expected)
+
+        even = even_ext(a, 1, axis=0)
+        expected = np.array([[9, 8, 7, 6, 5],
+                             [1, 2, 3, 4, 5],
+                             [9, 8, 7, 6, 5],
+                             [1, 2, 3, 4, 5]])
+        xp_assert_equal(even, expected)
+
+        assert_raises(ValueError, even_ext, a, 2, axis=0)
+        assert_raises(ValueError, even_ext, a, 5, axis=1)
+
+    def test_const_ext(self):
+        a = np.array([[1, 2, 3, 4, 5],
+                      [9, 8, 7, 6, 5]])
+
+        const = const_ext(a, 2, axis=1)
+        expected = np.array([[1, 1, 1, 2, 3, 4, 5, 5, 5],
+                             [9, 9, 9, 8, 7, 6, 5, 5, 5]])
+        xp_assert_equal(const, expected)
+
+        const = const_ext(a, 1, axis=0)
+        expected = np.array([[1, 2, 3, 4, 5],
+                             [1, 2, 3, 4, 5],
+                             [9, 8, 7, 6, 5],
+                             [9, 8, 7, 6, 5]])
+        xp_assert_equal(const, expected)
+
+    def test_zero_ext(self):
+        a = np.array([[1, 2, 3, 4, 5],
+                      [9, 8, 7, 6, 5]])
+
+        zero = zero_ext(a, 2, axis=1)
+        expected = np.array([[0, 0, 1, 2, 3, 4, 5, 0, 0],
+                             [0, 0, 9, 8, 7, 6, 5, 0, 0]])
+        xp_assert_equal(zero, expected)
+
+        zero = zero_ext(a, 1, axis=0)
+        expected = np.array([[0, 0, 0, 0, 0],
+                             [1, 2, 3, 4, 5],
+                             [9, 8, 7, 6, 5],
+                             [0, 0, 0, 0, 0]])
+        xp_assert_equal(zero, expected)
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c7baf2d8d9f2f9a84452965c35b5262ca20105d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_bsplines.py
@@ -0,0 +1,330 @@
+# pylint: disable=missing-docstring
+import numpy as np
+
+from scipy._lib._array_api import (
+    assert_almost_equal, xp_assert_close, xp_assert_equal
+)
+import pytest
+from pytest import raises
+
+import scipy.signal._spline_filters as bsp
+from scipy import signal
+
+
+class TestBSplines:
+    """Test behaviors of B-splines. Some of the values tested against were
+    returned as of SciPy 1.1.0 and are included for regression testing
+    purposes. Others (at integer points) are compared to theoretical
+    expressions (cf. Unser, Aldroubi, Eden, IEEE TSP 1993, Table 1)."""
+
+    def test_spline_filter(self):
+        rng = np.random.RandomState(12457)
+        # Test the type-error branch
+        raises(TypeError, bsp.spline_filter, np.asarray([0]), 0)
+        # Test the real branch
+        data_array_real = rng.rand(12, 12)
+        # make the magnitude exceed 1, and make some negative
+        data_array_real = 10*(1-2*data_array_real)
+        result_array_real = np.asarray(
+            [[-.463312621, 8.33391222, .697290949, 5.28390836,
+              5.92066474, 6.59452137, 9.84406950, -8.78324188,
+              7.20675750, -8.17222994, -4.38633345, 9.89917069],
+             [2.67755154, 6.24192170, -3.15730578, 9.87658581,
+              -9.96930425, 3.17194115, -4.50919947, 5.75423446,
+              9.65979824, -8.29066885, .971416087, -2.38331897],
+             [-7.08868346, 4.89887705, -1.37062289, 7.70705838,
+              2.51526461, 3.65885497, 5.16786604, -8.77715342e-03,
+              4.10533325, 9.04761993, -.577960351, 9.86382519],
+             [-4.71444301, -1.68038985, 2.84695116, 1.14315938,
+              -3.17127091, 1.91830461, 7.13779687, -5.35737482,
+              -9.66586425, -9.87717456, 9.93160672, 4.71948144],
+             [9.49551194, -1.92958436, 6.25427993, -9.05582911,
+              3.97562282, 7.68232426, -1.04514824, -5.86021443,
+              -8.43007451, 5.47528997, 2.06330736, -8.65968112],
+             [-8.91720100, 8.87065356, 3.76879937, 2.56222894,
+              -.828387146, 8.72288903, 6.42474741, -6.84576083,
+              9.94724115, 6.90665380, -6.61084494, -9.44907391],
+             [9.25196790, -.774032030, 7.05371046, -2.73505725,
+              2.53953305, -1.82889155, 2.95454824, -1.66362046,
+              5.72478916, -3.10287679, 1.54017123, -7.87759020],
+             [-3.98464539, -2.44316992, -1.12708657, 1.01725672,
+              -8.89294671, -5.42145629, -6.16370321, 2.91775492,
+              9.64132208, .702499998, -2.02622392, 1.56308431],
+             [-2.22050773, 7.89951554, 5.98970713, -7.35861835,
+              5.45459283, -7.76427957, 3.67280490, -4.05521315,
+              4.51967507, -3.22738749, -3.65080177, 3.05630155],
+             [-6.21240584, -.296796126, -8.34800163, 9.21564563,
+              -3.61958784, -4.77120006, -3.99454057, 1.05021988e-03,
+              -6.95982829, 6.04380797, 8.43181250, -2.71653339],
+             [1.19638037, 6.99718842e-02, 6.72020394, -2.13963198,
+              3.75309875, -5.70076744, 5.92143551, -7.22150575,
+              -3.77114594, -1.11903194, -5.39151466, 3.06620093],
+             [9.86326886, 1.05134482, -7.75950607, -3.64429655,
+              7.81848957, -9.02270373, 3.73399754, -4.71962549,
+              -7.71144306, 3.78263161, 6.46034818, -4.43444731]])
+        xp_assert_close(bsp.spline_filter(data_array_real, 0),
+                        result_array_real)
+
+    def test_spline_filter_complex(self):
+        rng = np.random.RandomState(12457)
+        data_array_complex = rng.rand(7, 7) + rng.rand(7, 7)*1j
+        # make the magnitude exceed 1, and make some negative
+        data_array_complex = 10*(1+1j-2*data_array_complex)
+        result_array_complex = np.asarray(
+            [[-4.61489230e-01-1.92994022j, 8.33332443+6.25519943j,
+              6.96300745e-01-9.05576038j, 5.28294849+3.97541356j,
+              5.92165565+7.68240595j, 6.59493160-1.04542804j,
+              9.84503460-5.85946894j],
+             [-8.78262329-8.4295969j, 7.20675516+5.47528982j,
+              -8.17223072+2.06330729j, -4.38633347-8.65968037j,
+              9.89916801-8.91720295j, 2.67755103+8.8706522j,
+              6.24192142+3.76879835j],
+             [-3.15627527+2.56303072j, 9.87658501-0.82838702j,
+              -9.96930313+8.72288895j, 3.17193985+6.42474651j,
+              -4.50919819-6.84576082j, 5.75423431+9.94723988j,
+              9.65979767+6.90665293j],
+             [-8.28993416-6.61064005j, 9.71416473e-01-9.44907284j,
+              -2.38331890+9.25196648j, -7.08868170-0.77403212j,
+              4.89887714+7.05371094j, -1.37062311-2.73505688j,
+              7.70705748+2.5395329j],
+             [2.51528406-1.82964492j, 3.65885472+2.95454836j,
+              5.16786575-1.66362023j, -8.77737999e-03+5.72478867j,
+              4.10533333-3.10287571j, 9.04761887+1.54017115j,
+              -5.77960968e-01-7.87758923j],
+             [9.86398506-3.98528528j, -4.71444130-2.44316983j,
+              -1.68038976-1.12708664j, 2.84695053+1.01725709j,
+              1.14315915-8.89294529j, -3.17127085-5.42145538j,
+              1.91830420-6.16370344j],
+             [7.13875294+2.91851187j, -5.35737514+9.64132309j,
+              -9.66586399+0.70250005j, -9.87717438-2.0262239j,
+              9.93160629+1.5630846j, 4.71948051-2.22050714j,
+              9.49550819+7.8995142j]])
+        # FIXME: for complex types, the computations are done in
+        # single precision (reason unclear). When this is changed,
+        # this test needs updating.
+        xp_assert_close(bsp.spline_filter(data_array_complex, 0),
+                        result_array_complex, rtol=1e-6)
+
+    def test_gauss_spline(self):
+        np.random.seed(12459)
+        assert_almost_equal(bsp.gauss_spline(0, 0), 1.381976597885342)
+        xp_assert_close(bsp.gauss_spline(np.asarray([1.]), 1),
+                        np.asarray([0.04865217]), atol=1e-9
+        )
+
+    def test_gauss_spline_list(self):
+        # regression test for gh-12152 (accept array_like)
+        knots = [-1.0, 0.0, -1.0]
+        assert_almost_equal(bsp.gauss_spline(knots, 3),
+                            np.asarray([0.15418033, 0.6909883, 0.15418033])
+        )
+
+    def test_cspline1d(self):
+        np.random.seed(12462)
+        xp_assert_equal(bsp.cspline1d(np.asarray([0])), [0.])
+        c1d = np.asarray([1.21037185, 1.86293902, 2.98834059, 4.11660378,
+                          4.78893826])
+        # test lamda != 0
+        xp_assert_close(bsp.cspline1d(np.asarray([1., 2, 3, 4, 5]), 1), c1d)
+        c1d0 = np.asarray([0.78683946, 2.05333735, 2.99981113, 3.94741812,
+                           5.21051638])
+        xp_assert_close(bsp.cspline1d(np.asarray([1., 2, 3, 4, 5])), c1d0)
+
+    def test_qspline1d(self):
+        np.random.seed(12463)
+        xp_assert_equal(bsp.qspline1d(np.asarray([0])), [0.])
+        # test lamda != 0
+        raises(ValueError, bsp.qspline1d, np.asarray([1., 2, 3, 4, 5]), 1.)
+        raises(ValueError, bsp.qspline1d, np.asarray([1., 2, 3, 4, 5]), -1.)
+        q1d0 = np.asarray([0.85350007, 2.02441743, 2.99999534, 3.97561055,
+                           5.14634135])
+        xp_assert_close(bsp.qspline1d(np.asarray([1., 2, 3, 4, 5])), q1d0)
+
+    def test_cspline1d_eval(self):
+        np.random.seed(12464)
+        xp_assert_close(bsp.cspline1d_eval(np.asarray([0., 0]), [0.]),
+                        np.asarray([0.])
+        )
+        xp_assert_equal(bsp.cspline1d_eval(np.asarray([1., 0, 1]), []),
+                        np.asarray([])
+        )
+        x = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
+        dx = x[1] - x[0]
+        newx = [-6., -5.5, -5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1.,
+                -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6.,
+                6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10., 10.5, 11., 11.5, 12.,
+                12.5]
+        y = np.asarray([4.216, 6.864, 3.514, 6.203, 6.759, 7.433, 7.874, 5.879,
+                        1.396, 4.094])
+        cj = bsp.cspline1d(y)
+        newy = np.asarray([6.203, 4.41570658, 3.514, 5.16924703, 6.864, 6.04643068,
+                           4.21600281, 6.04643068, 6.864, 5.16924703, 3.514,
+                           4.41570658, 6.203, 6.80717667, 6.759, 6.98971173, 7.433,
+                           7.79560142, 7.874, 7.41525761, 5.879, 3.18686814, 1.396,
+                           2.24889482, 4.094, 2.24889482, 1.396, 3.18686814, 5.879,
+                           7.41525761, 7.874, 7.79560142, 7.433, 6.98971173, 6.759,
+                           6.80717667, 6.203, 4.41570658])
+        xp_assert_close(bsp.cspline1d_eval(cj, newx, dx=dx, x0=x[0]), newy)
+
+    def test_qspline1d_eval(self):
+        np.random.seed(12465)
+        xp_assert_close(bsp.qspline1d_eval(np.asarray([0., 0]), [0.]),
+                        np.asarray([0.])
+        )
+        xp_assert_equal(bsp.qspline1d_eval(np.asarray([1., 0, 1]), []),
+                        np.asarray([])
+        )
+        x = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
+        dx = x[1]-x[0]
+        newx = [-6., -5.5, -5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1.,
+                -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6.,
+                6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10., 10.5, 11., 11.5, 12.,
+                12.5]
+        y = np.asarray([4.216, 6.864, 3.514, 6.203, 6.759, 7.433, 7.874, 5.879,
+                        1.396, 4.094])
+        cj = bsp.qspline1d(y)
+        newy = np.asarray([6.203, 4.49418159, 3.514, 5.18390821, 6.864, 5.91436915,
+                           4.21600002, 5.91436915, 6.864, 5.18390821, 3.514,
+                           4.49418159, 6.203, 6.71900226, 6.759, 7.03980488, 7.433,
+                           7.81016848, 7.874, 7.32718426, 5.879, 3.23872593, 1.396,
+                           2.34046013, 4.094, 2.34046013, 1.396, 3.23872593, 5.879,
+                           7.32718426, 7.874, 7.81016848, 7.433, 7.03980488, 6.759,
+                           6.71900226, 6.203, 4.49418159])
+        xp_assert_close(bsp.qspline1d_eval(cj, newx, dx=dx, x0=x[0]), newy)
+
+
+# i/o dtypes with scipy 1.9.1, likely fixed by backwards compat
+sepfir_dtype_map = {np.uint8: np.float32, int: np.float64,
+                    np.float32: np.float32, float: float,
+                    np.complex64: np.complex64, complex: complex}
+
+class TestSepfir2d:
+    def test_sepfir2d_invalid_filter(self):
+        filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0])
+        image = np.random.rand(7, 9)
+        # No error for odd lengths
+        signal.sepfir2d(image, filt, filt[2:])
+
+        # Row or column filter must be odd
+        with pytest.raises(ValueError, match="odd length"):
+            signal.sepfir2d(image, filt, filt[1:])
+        with pytest.raises(ValueError, match="odd length"):
+            signal.sepfir2d(image, filt[1:], filt)
+
+        # Filters must be 1-dimensional
+        with pytest.raises(ValueError, match="object too deep"):
+            signal.sepfir2d(image, filt.reshape(1, -1), filt)
+        with pytest.raises(ValueError, match="object too deep"):
+            signal.sepfir2d(image, filt, filt.reshape(1, -1))
+
+    def test_sepfir2d_invalid_image(self):
+        filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0])
+        image = np.random.rand(8, 8)
+
+        # Image must be 2 dimensional
+        with pytest.raises(ValueError, match="object too deep"):
+            signal.sepfir2d(image.reshape(4, 4, 4), filt, filt)
+
+        with pytest.raises(ValueError, match="object of too small depth"):
+            signal.sepfir2d(image[0], filt, filt)
+
+    @pytest.mark.parametrize('dtyp',
+        [np.uint8, int, np.float32, float, np.complex64, complex]
+    )
+    def test_simple(self, dtyp):
+        # test values on a paper-and-pencil example
+        a = np.array([[1, 2, 3, 3, 2, 1],
+                      [1, 2, 3, 3, 2, 1],
+                      [1, 2, 3, 3, 2, 1],
+                      [1, 2, 3, 3, 2, 1]], dtype=dtyp)
+        h1 = [0.5, 1, 0.5]
+        h2 = [1]
+        result = signal.sepfir2d(a, h1, h2)
+        dt = sepfir_dtype_map[dtyp]
+        expected = np.asarray([[2.5, 4. , 5.5, 5.5, 4. , 2.5],
+                               [2.5, 4. , 5.5, 5.5, 4. , 2.5],
+                               [2.5, 4. , 5.5, 5.5, 4. , 2.5],
+                               [2.5, 4. , 5.5, 5.5, 4. , 2.5]], dtype=dt)
+        xp_assert_close(result, expected, atol=1e-16)
+
+        result = signal.sepfir2d(a, h2, h1)
+        expected = np.asarray([[2., 4., 6., 6., 4., 2.],
+                               [2., 4., 6., 6., 4., 2.],
+                               [2., 4., 6., 6., 4., 2.],
+                               [2., 4., 6., 6., 4., 2.]], dtype=dt)
+        xp_assert_close(result, expected, atol=1e-16)
+
+    @pytest.mark.parametrize('dtyp',
+        [np.uint8, int, np.float32, float, np.complex64, complex]
+    )
+    def test_strided(self, dtyp):
+        a = np.array([[1, 2, 3, 3, 2, 1, 1, 2, 3],
+                     [1, 2, 3, 3, 2, 1, 1, 2, 3],
+                     [1, 2, 3, 3, 2, 1, 1, 2, 3],
+                     [1, 2, 3, 3, 2, 1, 1, 2, 3]])
+        h1, h2 = [0.5, 1, 0.5], [1]
+        result_strided = signal.sepfir2d(a[:, ::2], h1, h2)
+        result_contig = signal.sepfir2d(a[:, ::2].copy(), h1, h2)
+        xp_assert_close(result_strided, result_contig, atol=1e-15)
+        assert result_strided.dtype == result_contig.dtype
+
+    @pytest.mark.xfail(reason="XXX: filt.size > image.shape: flaky")
+    def test_sepfir2d_strided_2(self):
+        # XXX: this test is flaky: fails on some reruns, with
+        # result[0, 1] and result[1, 1] being ~1e+224.
+        np.random.seed(1234)
+        filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0, 3.0, 2.0])
+        image = np.random.rand(4, 4)
+
+        expected = np.asarray([[36.018162, 30.239061, 38.71187 , 43.878183],
+                                [38.180999, 35.824583, 43.525247, 43.874945],
+                                [43.269533, 40.834018, 46.757772, 44.276423],
+                                [49.120928, 39.681844, 43.596067, 45.085854]])
+        xp_assert_close(signal.sepfir2d(image, filt, filt[::3]), expected)
+
+    @pytest.mark.xfail(reason="XXX: flaky. pointers OOB on some platforms")
+    @pytest.mark.parametrize('dtyp',
+        [np.uint8, int, np.float32, float, np.complex64, complex]
+    )
+    def test_sepfir2d_strided_3(self, dtyp):
+        # NB: 'image' and 'filt' dtypes match here. Otherwise we can run into
+        # unsafe casting errors for many combinations. Historically, dtype handling
+        # in `sepfir2d` is a tad baroque; fixing it is an enhancement.
+        filt = np.array([1, 2, 4, 2, 1, 3, 2], dtype=dtyp)
+        image = np.asarray([[0, 3, 0, 1, 2],
+                            [2, 2, 3, 3, 3],
+                            [0, 1, 3, 0, 3],
+                            [2, 3, 0, 1, 3],
+                            [3, 3, 2, 1, 2]], dtype=dtyp)
+
+        expected = [[123., 101.,  91., 136., 127.],
+                    [133., 125., 126., 152., 160.],
+                    [136., 137., 150., 162., 177.],
+                    [133., 124., 132., 148., 147.],
+                    [173., 158., 152., 164., 141.]]
+        expected = np.asarray(expected)
+        result = signal.sepfir2d(image, filt, filt[::3])
+        xp_assert_close(result, expected, atol=1e-15)
+        assert result.dtype == sepfir_dtype_map[dtyp]
+
+        expected = [[22., 35., 41., 31., 47.],
+                    [27., 39., 48., 47., 55.],
+                    [33., 42., 49., 53., 59.],
+                    [39., 44., 41., 36., 48.],
+                    [67., 62., 47., 34., 46.]]
+        expected = np.asarray(expected)
+        result = signal.sepfir2d(image, filt[::3], filt[::3])
+        xp_assert_close(result, expected, atol=1e-15)
+        assert result.dtype == sepfir_dtype_map[dtyp]
+
+
+def test_cspline2d():
+    np.random.seed(181819142)
+    image = np.random.rand(71, 73)
+    signal.cspline2d(image, 8.0)
+
+
+def test_qspline2d():
+    np.random.seed(181819143)
+    image = np.random.rand(71, 73)
+    signal.qspline2d(image)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..872541543ba485f3e8a17735bee471875f92fd05
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_dltisys.py
@@ -0,0 +1,599 @@
+# Author: Jeffrey Armstrong 
+# April 4, 2011
+
+import numpy as np
+from numpy.testing import suppress_warnings
+from pytest import raises as assert_raises
+from scipy._lib._array_api import (
+    assert_array_almost_equal, assert_almost_equal, xp_assert_close, xp_assert_equal,
+)
+
+from scipy.signal import (dlsim, dstep, dimpulse, tf2zpk, lti, dlti,
+                          StateSpace, TransferFunction, ZerosPolesGain,
+                          dfreqresp, dbode, BadCoefficients)
+
+
+class TestDLTI:
+
+    def test_dlsim(self):
+
+        a = np.asarray([[0.9, 0.1], [-0.2, 0.9]])
+        b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]])
+        c = np.asarray([[0.1, 0.3]])
+        d = np.asarray([[0.0, -0.1, 0.0]])
+        dt = 0.5
+
+        # Create an input matrix with inputs down the columns (3 cols) and its
+        # respective time input vector
+        u = np.hstack((np.linspace(0, 4.0, num=5)[:, np.newaxis],
+                       np.full((5, 1), 0.01),
+                       np.full((5, 1), -0.002)))
+        t_in = np.linspace(0, 2.0, num=5)
+
+        # Define the known result
+        yout_truth = np.array([[-0.001,
+                                -0.00073,
+                                0.039446,
+                                0.0915387,
+                                0.13195948]]).T
+        xout_truth = np.asarray([[0, 0],
+                                 [0.0012, 0.0005],
+                                 [0.40233, 0.00071],
+                                 [1.163368, -0.079327],
+                                 [2.2402985, -0.3035679]])
+
+        tout, yout, xout = dlsim((a, b, c, d, dt), u, t_in)
+
+        assert_array_almost_equal(yout_truth, yout)
+        assert_array_almost_equal(xout_truth, xout)
+        assert_array_almost_equal(t_in, tout)
+
+        # Make sure input with single-dimension doesn't raise error
+        dlsim((1, 2, 3), 4)
+
+        # Interpolated control - inputs should have different time steps
+        # than the discrete model uses internally
+        u_sparse = u[[0, 4], :]
+        t_sparse = np.asarray([0.0, 2.0])
+
+        tout, yout, xout = dlsim((a, b, c, d, dt), u_sparse, t_sparse)
+
+        assert_array_almost_equal(yout_truth, yout)
+        assert_array_almost_equal(xout_truth, xout)
+        assert len(tout) == len(yout)
+
+        # Transfer functions (assume dt = 0.5)
+        num = np.asarray([1.0, -0.1])
+        den = np.asarray([0.3, 1.0, 0.2])
+        yout_truth = np.array([[0.0,
+                                0.0,
+                                3.33333333333333,
+                                -4.77777777777778,
+                                23.0370370370370]]).T
+
+        # Assume use of the first column of the control input built earlier
+        tout, yout = dlsim((num, den, 0.5), u[:, 0], t_in)
+
+        assert_array_almost_equal(yout, yout_truth)
+        assert_array_almost_equal(t_in, tout)
+
+        # Retest the same with a 1-D input vector
+        uflat = np.asarray(u[:, 0])
+        uflat = uflat.reshape((5,))
+        tout, yout = dlsim((num, den, 0.5), uflat, t_in)
+
+        assert_array_almost_equal(yout, yout_truth)
+        assert_array_almost_equal(t_in, tout)
+
+        # zeros-poles-gain representation
+        zd = np.array([0.5, -0.5])
+        pd = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)])
+        k = 1.0
+        yout_truth = np.array([[0.0, 1.0, 2.0, 2.25, 2.5]]).T
+
+        tout, yout = dlsim((zd, pd, k, 0.5), u[:, 0], t_in)
+
+        assert_array_almost_equal(yout, yout_truth)
+        assert_array_almost_equal(t_in, tout)
+
+        # Raise an error for continuous-time systems
+        system = lti([1], [1, 1])
+        assert_raises(AttributeError, dlsim, system, u)
+
+    def test_dstep(self):
+
+        a = np.asarray([[0.9, 0.1], [-0.2, 0.9]])
+        b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]])
+        c = np.asarray([[0.1, 0.3]])
+        d = np.asarray([[0.0, -0.1, 0.0]])
+        dt = 0.5
+
+        # Because b.shape[1] == 3, dstep should result in a tuple of three
+        # result vectors
+        yout_step_truth = (np.asarray([0.0, 0.04, 0.052, 0.0404, 0.00956,
+                                       -0.036324, -0.093318, -0.15782348,
+                                       -0.226628324, -0.2969374948]),
+                           np.asarray([-0.1, -0.075, -0.058, -0.04815,
+                                       -0.04453, -0.0461895, -0.0521812,
+                                       -0.061588875, -0.073549579,
+                                       -0.08727047595]),
+                           np.asarray([0.0, -0.01, -0.013, -0.0101, -0.00239,
+                                       0.009081, 0.0233295, 0.03945587,
+                                       0.056657081, 0.0742343737]))
+
+        tout, yout = dstep((a, b, c, d, dt), n=10)
+
+        assert len(yout) == 3
+
+        for i in range(0, len(yout)):
+            assert yout[i].shape[0] == 10
+            assert_array_almost_equal(yout[i].flatten(), yout_step_truth[i])
+
+        # Check that the other two inputs (tf, zpk) will work as well
+        tfin = ([1.0], [1.0, 1.0], 0.5)
+        yout_tfstep = np.asarray([0.0, 1.0, 0.0])
+        tout, yout = dstep(tfin, n=3)
+        assert len(yout) == 1
+        assert_array_almost_equal(yout[0].flatten(), yout_tfstep)
+
+        zpkin = tf2zpk(tfin[0], tfin[1]) + (0.5,)
+        tout, yout = dstep(zpkin, n=3)
+        assert len(yout) == 1
+        assert_array_almost_equal(yout[0].flatten(), yout_tfstep)
+
+        # Raise an error for continuous-time systems
+        system = lti([1], [1, 1])
+        assert_raises(AttributeError, dstep, system)
+
+    def test_dimpulse(self):
+
+        a = np.asarray([[0.9, 0.1], [-0.2, 0.9]])
+        b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]])
+        c = np.asarray([[0.1, 0.3]])
+        d = np.asarray([[0.0, -0.1, 0.0]])
+        dt = 0.5
+
+        # Because b.shape[1] == 3, dimpulse should result in a tuple of three
+        # result vectors
+        yout_imp_truth = (np.asarray([0.0, 0.04, 0.012, -0.0116, -0.03084,
+                                      -0.045884, -0.056994, -0.06450548,
+                                      -0.068804844, -0.0703091708]),
+                          np.asarray([-0.1, 0.025, 0.017, 0.00985, 0.00362,
+                                      -0.0016595, -0.0059917, -0.009407675,
+                                      -0.011960704, -0.01372089695]),
+                          np.asarray([0.0, -0.01, -0.003, 0.0029, 0.00771,
+                                      0.011471, 0.0142485, 0.01612637,
+                                      0.017201211, 0.0175772927]))
+
+        tout, yout = dimpulse((a, b, c, d, dt), n=10)
+
+        assert len(yout) == 3
+
+        for i in range(0, len(yout)):
+            assert yout[i].shape[0] == 10
+            assert_array_almost_equal(yout[i].flatten(), yout_imp_truth[i])
+
+        # Check that the other two inputs (tf, zpk) will work as well
+        tfin = ([1.0], [1.0, 1.0], 0.5)
+        yout_tfimpulse = np.asarray([0.0, 1.0, -1.0])
+        tout, yout = dimpulse(tfin, n=3)
+        assert len(yout) == 1
+        assert_array_almost_equal(yout[0].flatten(), yout_tfimpulse)
+
+        zpkin = tf2zpk(tfin[0], tfin[1]) + (0.5,)
+        tout, yout = dimpulse(zpkin, n=3)
+        assert len(yout) == 1
+        assert_array_almost_equal(yout[0].flatten(), yout_tfimpulse)
+
+        # Raise an error for continuous-time systems
+        system = lti([1], [1, 1])
+        assert_raises(AttributeError, dimpulse, system)
+
+    def test_dlsim_trivial(self):
+        a = np.array([[0.0]])
+        b = np.array([[0.0]])
+        c = np.array([[0.0]])
+        d = np.array([[0.0]])
+        n = 5
+        u = np.zeros(n).reshape(-1, 1)
+        tout, yout, xout = dlsim((a, b, c, d, 1), u)
+        xp_assert_equal(tout, np.arange(float(n)))
+        xp_assert_equal(yout, np.zeros((n, 1)))
+        xp_assert_equal(xout, np.zeros((n, 1)))
+
+    def test_dlsim_simple1d(self):
+        a = np.array([[0.5]])
+        b = np.array([[0.0]])
+        c = np.array([[1.0]])
+        d = np.array([[0.0]])
+        n = 5
+        u = np.zeros(n).reshape(-1, 1)
+        tout, yout, xout = dlsim((a, b, c, d, 1), u, x0=1)
+        xp_assert_equal(tout, np.arange(float(n)))
+        expected = (0.5 ** np.arange(float(n))).reshape(-1, 1)
+        xp_assert_equal(yout, expected)
+        xp_assert_equal(xout, expected)
+
+    def test_dlsim_simple2d(self):
+        lambda1 = 0.5
+        lambda2 = 0.25
+        a = np.array([[lambda1, 0.0],
+                      [0.0, lambda2]])
+        b = np.array([[0.0],
+                      [0.0]])
+        c = np.array([[1.0, 0.0],
+                      [0.0, 1.0]])
+        d = np.array([[0.0],
+                      [0.0]])
+        n = 5
+        u = np.zeros(n).reshape(-1, 1)
+        tout, yout, xout = dlsim((a, b, c, d, 1), u, x0=1)
+        xp_assert_equal(tout, np.arange(float(n)))
+        # The analytical solution:
+        expected = (np.array([lambda1, lambda2]) **
+                                np.arange(float(n)).reshape(-1, 1))
+        xp_assert_equal(yout, expected)
+        xp_assert_equal(xout, expected)
+
+    def test_more_step_and_impulse(self):
+        lambda1 = 0.5
+        lambda2 = 0.75
+        a = np.array([[lambda1, 0.0],
+                      [0.0, lambda2]])
+        b = np.array([[1.0, 0.0],
+                      [0.0, 1.0]])
+        c = np.array([[1.0, 1.0]])
+        d = np.array([[0.0, 0.0]])
+
+        n = 10
+
+        # Check a step response.
+        ts, ys = dstep((a, b, c, d, 1), n=n)
+
+        # Create the exact step response.
+        stp0 = (1.0 / (1 - lambda1)) * (1.0 - lambda1 ** np.arange(n))
+        stp1 = (1.0 / (1 - lambda2)) * (1.0 - lambda2 ** np.arange(n))
+
+        xp_assert_close(ys[0][:, 0], stp0)
+        xp_assert_close(ys[1][:, 0], stp1)
+
+        # Check an impulse response with an initial condition.
+        x0 = np.array([1.0, 1.0])
+        ti, yi = dimpulse((a, b, c, d, 1), n=n, x0=x0)
+
+        # Create the exact impulse response.
+        imp = (np.array([lambda1, lambda2]) **
+                            np.arange(-1, n + 1).reshape(-1, 1))
+        imp[0, :] = 0.0
+        # Analytical solution to impulse response
+        y0 = imp[:n, 0] + np.dot(imp[1:n + 1, :], x0)
+        y1 = imp[:n, 1] + np.dot(imp[1:n + 1, :], x0)
+
+        xp_assert_close(yi[0][:, 0], y0)
+        xp_assert_close(yi[1][:, 0], y1)
+
+        # Check that dt=0.1, n=3 gives 3 time values.
+        system = ([1.0], [1.0, -0.5], 0.1)
+        t, (y,) = dstep(system, n=3)
+        xp_assert_close(t, [0, 0.1, 0.2])
+        xp_assert_equal(y.T, [[0, 1.0, 1.5]])
+        t, (y,) = dimpulse(system, n=3)
+        xp_assert_close(t, [0, 0.1, 0.2])
+        xp_assert_equal(y.T, [[0, 1, 0.5]])
+
+
+class TestDlti:
+    def test_dlti_instantiation(self):
+        # Test that lti can be instantiated.
+
+        dt = 0.05
+        # TransferFunction
+        s = dlti([1], [-1], dt=dt)
+        assert isinstance(s, TransferFunction)
+        assert isinstance(s, dlti)
+        assert not isinstance(s, lti)
+        assert s.dt == dt
+
+        # ZerosPolesGain
+        s = dlti(np.array([]), np.array([-1]), 1, dt=dt)
+        assert isinstance(s, ZerosPolesGain)
+        assert isinstance(s, dlti)
+        assert not isinstance(s, lti)
+        assert s.dt == dt
+
+        # StateSpace
+        s = dlti([1], [-1], 1, 3, dt=dt)
+        assert isinstance(s, StateSpace)
+        assert isinstance(s, dlti)
+        assert not isinstance(s, lti)
+        assert s.dt == dt
+
+        # Number of inputs
+        assert_raises(ValueError, dlti, 1)
+        assert_raises(ValueError, dlti, 1, 1, 1, 1, 1)
+
+
+class TestStateSpaceDisc:
+    def test_initialization(self):
+        # Check that all initializations work
+        dt = 0.05
+        StateSpace(1, 1, 1, 1, dt=dt)
+        StateSpace([1], [2], [3], [4], dt=dt)
+        StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]),
+                   np.array([[1, 0]]), np.array([[0]]), dt=dt)
+        StateSpace(1, 1, 1, 1, dt=True)
+
+    def test_conversion(self):
+        # Check the conversion functions
+        s = StateSpace(1, 2, 3, 4, dt=0.05)
+        assert isinstance(s.to_ss(), StateSpace)
+        assert isinstance(s.to_tf(), TransferFunction)
+        assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+        # Make sure copies work
+        assert StateSpace(s) is not s
+        assert s.to_ss() is not s
+
+    def test_properties(self):
+        # Test setters/getters for cross class properties.
+        # This implicitly tests to_tf() and to_zpk()
+
+        # Getters
+        s = StateSpace(1, 1, 1, 1, dt=0.05)
+        xp_assert_equal(s.poles, [1.])
+        xp_assert_equal(s.zeros, [0.])
+
+
+class TestTransferFunction:
+    def test_initialization(self):
+        # Check that all initializations work
+        dt = 0.05
+        TransferFunction(1, 1, dt=dt)
+        TransferFunction([1], [2], dt=dt)
+        TransferFunction(np.array([1]), np.array([2]), dt=dt)
+        TransferFunction(1, 1, dt=True)
+
+    def test_conversion(self):
+        # Check the conversion functions
+        s = TransferFunction([1, 0], [1, -1], dt=0.05)
+        assert isinstance(s.to_ss(), StateSpace)
+        assert isinstance(s.to_tf(), TransferFunction)
+        assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+        # Make sure copies work
+        assert TransferFunction(s) is not s
+        assert s.to_tf() is not s
+
+    def test_properties(self):
+        # Test setters/getters for cross class properties.
+        # This implicitly tests to_ss() and to_zpk()
+
+        # Getters
+        s = TransferFunction([1, 0], [1, -1], dt=0.05)
+        xp_assert_equal(s.poles, [1.])
+        xp_assert_equal(s.zeros, [0.])
+
+
+class TestZerosPolesGain:
+    def test_initialization(self):
+        # Check that all initializations work
+        dt = 0.05
+        ZerosPolesGain(1, 1, 1, dt=dt)
+        ZerosPolesGain([1], [2], 1, dt=dt)
+        ZerosPolesGain(np.array([1]), np.array([2]), 1, dt=dt)
+        ZerosPolesGain(1, 1, 1, dt=True)
+
+    def test_conversion(self):
+        # Check the conversion functions
+        s = ZerosPolesGain(1, 2, 3, dt=0.05)
+        assert isinstance(s.to_ss(), StateSpace)
+        assert isinstance(s.to_tf(), TransferFunction)
+        assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+        # Make sure copies work
+        assert ZerosPolesGain(s) is not s
+        assert s.to_zpk() is not s
+
+
+class Test_dfreqresp:
+
+    def test_manual(self):
+        # Test dfreqresp() real part calculation (manual sanity check).
+        # 1st order low-pass filter: H(z) = 1 / (z - 0.2),
+        system = TransferFunction(1, [1, -0.2], dt=0.1)
+        w = [0.1, 1, 10]
+        w, H = dfreqresp(system, w=w)
+
+        # test real
+        expected_re = [1.2383, 0.4130, -0.7553]
+        assert_almost_equal(H.real, expected_re, decimal=4)
+
+        # test imag
+        expected_im = [-0.1555, -1.0214, 0.3955]
+        assert_almost_equal(H.imag, expected_im, decimal=4)
+
+    def test_auto(self):
+        # Test dfreqresp() real part calculation.
+        # 1st order low-pass filter: H(z) = 1 / (z - 0.2),
+        system = TransferFunction(1, [1, -0.2], dt=0.1)
+        w = [0.1, 1, 10, 100]
+        w, H = dfreqresp(system, w=w)
+        jw = np.exp(w * 1j)
+        y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
+
+        # test real
+        expected_re = y.real
+        assert_almost_equal(H.real, expected_re)
+
+        # test imag
+        expected_im = y.imag
+        assert_almost_equal(H.imag, expected_im)
+
+    def test_freq_range(self):
+        # Test that freqresp() finds a reasonable frequency range.
+        # 1st order low-pass filter: H(z) = 1 / (z - 0.2),
+        # Expected range is from 0.01 to 10.
+        system = TransferFunction(1, [1, -0.2], dt=0.1)
+        n = 10
+        expected_w = np.linspace(0, np.pi, 10, endpoint=False)
+        w, H = dfreqresp(system, n=n)
+        assert_almost_equal(w, expected_w)
+
+    def test_pole_one(self):
+        # Test that freqresp() doesn't fail on a system with a pole at 0.
+        # integrator, pole at zero: H(s) = 1 / s
+        system = TransferFunction([1], [1, -1], dt=0.1)
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, message="divide by zero")
+            sup.filter(RuntimeWarning, message="invalid value encountered")
+            w, H = dfreqresp(system, n=2)
+        assert w[0] == 0.   # a fail would give not-a-number
+
+    def test_error(self):
+        # Raise an error for continuous-time systems
+        system = lti([1], [1, 1])
+        assert_raises(AttributeError, dfreqresp, system)
+
+    def test_from_state_space(self):
+        # H(z) = 2 / z^3 - 0.5 * z^2
+
+        system_TF = dlti([2], [1, -0.5, 0, 0])
+
+        A = np.array([[0.5, 0, 0],
+                      [1, 0, 0],
+                      [0, 1, 0]])
+        B = np.array([[1, 0, 0]]).T
+        C = np.array([[0, 0, 2]])
+        D = 0
+
+        system_SS = dlti(A, B, C, D)
+        w = 10.0**np.arange(-3,0,.5)
+        with suppress_warnings() as sup:
+            sup.filter(BadCoefficients)
+            w1, H1 = dfreqresp(system_TF, w=w)
+            w2, H2 = dfreqresp(system_SS, w=w)
+
+        assert_almost_equal(H1, H2)
+
+    def test_from_zpk(self):
+        # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
+        system_ZPK = dlti([],[0.2],0.3)
+        system_TF = dlti(0.3, [1, -0.2])
+        w = [0.1, 1, 10, 100]
+        w1, H1 = dfreqresp(system_ZPK, w=w)
+        w2, H2 = dfreqresp(system_TF, w=w)
+        assert_almost_equal(H1, H2)
+
+
+class Test_bode:
+
+    def test_manual(self):
+        # Test bode() magnitude calculation (manual sanity check).
+        # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
+        dt = 0.1
+        system = TransferFunction(0.3, [1, -0.2], dt=dt)
+        w = [0.1, 0.5, 1, np.pi]
+        w2, mag, phase = dbode(system, w=w)
+
+        # Test mag
+        expected_mag = [-8.5329, -8.8396, -9.6162, -12.0412]
+        assert_almost_equal(mag, expected_mag, decimal=4)
+
+        # Test phase
+        expected_phase = [-7.1575, -35.2814, -67.9809, -180.0000]
+        assert_almost_equal(phase, expected_phase, decimal=4)
+
+        # Test frequency
+        xp_assert_equal(np.array(w) / dt, w2)
+
+    def test_auto(self):
+        # Test bode() magnitude calculation.
+        # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
+        system = TransferFunction(0.3, [1, -0.2], dt=0.1)
+        w = np.array([0.1, 0.5, 1, np.pi])
+        w2, mag, phase = dbode(system, w=w)
+        jw = np.exp(w * 1j)
+        y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
+
+        # Test mag
+        expected_mag = 20.0 * np.log10(abs(y))
+        assert_almost_equal(mag, expected_mag)
+
+        # Test phase
+        expected_phase = np.rad2deg(np.angle(y))
+        assert_almost_equal(phase, expected_phase)
+
+    def test_range(self):
+        # Test that bode() finds a reasonable frequency range.
+        # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
+        dt = 0.1
+        system = TransferFunction(0.3, [1, -0.2], dt=0.1)
+        n = 10
+        # Expected range is from 0.01 to 10.
+        expected_w = np.linspace(0, np.pi, n, endpoint=False) / dt
+        w, mag, phase = dbode(system, n=n)
+        assert_almost_equal(w, expected_w)
+
+    def test_pole_one(self):
+        # Test that freqresp() doesn't fail on a system with a pole at 0.
+        # integrator, pole at zero: H(s) = 1 / s
+        system = TransferFunction([1], [1, -1], dt=0.1)
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, message="divide by zero")
+            sup.filter(RuntimeWarning, message="invalid value encountered")
+            w, mag, phase = dbode(system, n=2)
+        assert w[0] == 0.  # a fail would give not-a-number
+
+    def test_imaginary(self):
+        # bode() should not fail on a system with pure imaginary poles.
+        # The test passes if bode doesn't raise an exception.
+        system = TransferFunction([1], [1, 0, 100], dt=0.1)
+        dbode(system, n=2)
+
+    def test_error(self):
+        # Raise an error for continuous-time systems
+        system = lti([1], [1, 1])
+        assert_raises(AttributeError, dbode, system)
+
+
+class TestTransferFunctionZConversion:
+    """Test private conversions between 'z' and 'z**-1' polynomials."""
+
+    def test_full(self):
+        # Numerator and denominator same order
+        num = np.asarray([2.0, 3, 4])
+        den = np.asarray([5.0, 6, 7])
+        num2, den2 = TransferFunction._z_to_zinv(num, den)
+        xp_assert_equal(num, num2)
+        xp_assert_equal(den, den2)
+
+        num2, den2 = TransferFunction._zinv_to_z(num, den)
+        xp_assert_equal(num, num2)
+        xp_assert_equal(den, den2)
+
+    def test_numerator(self):
+        # Numerator lower order than denominator
+        num = np.asarray([2.0, 3])
+        den = np.asarray([50, 6, 7])
+        num2, den2 = TransferFunction._z_to_zinv(num, den)
+        xp_assert_equal([0.0, 2, 3], num2)
+        xp_assert_equal(den, den2)
+
+        num2, den2 = TransferFunction._zinv_to_z(num, den)
+        xp_assert_equal([2.0, 3, 0], num2)
+        xp_assert_equal(den, den2)
+
+    def test_denominator(self):
+        # Numerator higher order than denominator
+        num = np.asarray([2., 3, 4])
+        den = np.asarray([5.0, 6])
+        num2, den2 = TransferFunction._z_to_zinv(num, den)
+        xp_assert_equal(num, num2)
+        xp_assert_equal([0.0, 5, 6], den2)
+
+        num2, den2 = TransferFunction._zinv_to_z(num, den)
+        xp_assert_equal(num, num2)
+        xp_assert_equal([5.0, 6, 0], den2)
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..df1ccc639f2041cfc8a6aec50190b34f72d25c84
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_short_time_fft.py
@@ -0,0 +1,880 @@
+"""Unit tests for module `_short_time_fft`.
+
+This file's structure loosely groups the tests into the following sequential
+categories:
+
+1. Test function `_calc_dual_canonical_window`.
+2. Test for invalid parameters and exceptions in `ShortTimeFFT` (until the
+    `test_from_window` function).
+3. Test algorithmic properties of STFT/ISTFT. Some tests were ported from
+   ``test_spectral.py``.
+
+Notes
+-----
+* Mypy 0.990 does interpret the line::
+
+        from scipy.stats import norm as normal_distribution
+
+  incorrectly (but the code works), hence a ``type: ignore`` was appended.
+"""
+import math
+from itertools import product
+from typing import cast, get_args, Literal
+
+import numpy as np
+import pytest
+from scipy._lib._array_api import xp_assert_close, xp_assert_equal
+from scipy.fft import fftshift
+from scipy.stats import norm as normal_distribution  # type: ignore
+from scipy.signal import get_window, welch, stft, istft, spectrogram
+
+from scipy.signal._short_time_fft import FFT_MODE_TYPE, \
+    _calc_dual_canonical_window, ShortTimeFFT, PAD_TYPE
+from scipy.signal.windows import gaussian
+
+
+def test__calc_dual_canonical_window_roundtrip():
+    """Test dual window calculation with a round trip to verify duality.
+
+    Note that this works only for canonical window pairs (having minimal
+    energy) like a Gaussian.
+
+    The window is the same as in the example of `from ShortTimeFFT.from_dual`.
+    """
+    win = gaussian(51, std=10, sym=True)
+    d_win = _calc_dual_canonical_window(win, 10)
+    win2 = _calc_dual_canonical_window(d_win, 10)
+    xp_assert_close(win2, win)
+
+
+def test__calc_dual_canonical_window_exceptions():
+    """Raise all exceptions in `_calc_dual_canonical_window`."""
+    # Verify that calculation can fail:
+    with pytest.raises(ValueError, match="hop=5 is larger than window len.*"):
+        _calc_dual_canonical_window(np.ones(4), 5)
+    with pytest.raises(ValueError, match=".* Transform not invertible!"):
+        _calc_dual_canonical_window(np.array([.1, .2, .3, 0]), 4)
+
+    # Verify that parameter `win` may not be integers:
+    with pytest.raises(ValueError, match="Parameter 'win' cannot be of int.*"):
+        _calc_dual_canonical_window(np.ones(4, dtype=int), 1)
+
+
+def test_invalid_initializer_parameters():
+    """Verify that exceptions get raised on invalid parameters when
+    instantiating ShortTimeFFT. """
+    with pytest.raises(ValueError, match=r"Parameter win must be 1d, " +
+                                         r"but win.shape=\(2, 2\)!"):
+        ShortTimeFFT(np.ones((2, 2)), hop=4, fs=1)
+    with pytest.raises(ValueError, match="Parameter win must have " +
+                                         "finite entries"):
+        ShortTimeFFT(np.array([1, np.inf, 2, 3]), hop=4, fs=1)
+    with pytest.raises(ValueError, match="Parameter hop=0 is not " +
+                                         "an integer >= 1!"):
+        ShortTimeFFT(np.ones(4), hop=0, fs=1)
+    with pytest.raises(ValueError, match="Parameter hop=2.0 is not " +
+                                         "an integer >= 1!"):
+        # noinspection PyTypeChecker
+        ShortTimeFFT(np.ones(4), hop=2.0, fs=1)
+    with pytest.raises(ValueError, match=r"dual_win.shape=\(5,\) must equal " +
+                                         r"win.shape=\(4,\)!"):
+        ShortTimeFFT(np.ones(4), hop=2, fs=1, dual_win=np.ones(5))
+    with pytest.raises(ValueError, match="Parameter dual_win must be " +
+                                         "a finite array!"):
+        ShortTimeFFT(np.ones(3), hop=2, fs=1,
+                     dual_win=np.array([np.nan, 2, 3]))
+
+
+def test_exceptions_properties_methods():
+    """Verify that exceptions get raised when setting properties or calling
+    method of ShortTimeFFT to/with invalid values."""
+    SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+    with pytest.raises(ValueError, match="Sampling interval T=-1 must be " +
+                                         "positive!"):
+        SFT.T = -1
+    with pytest.raises(ValueError, match="Sampling frequency fs=-1 must be " +
+                                         "positive!"):
+        SFT.fs = -1
+    with pytest.raises(ValueError, match="fft_mode='invalid_typ' not in " +
+                                         r"\('twosided', 'centered', " +
+                                         r"'onesided', 'onesided2X'\)!"):
+        SFT.fft_mode = 'invalid_typ'
+    with pytest.raises(ValueError, match="For scaling is None, " +
+                                         "fft_mode='onesided2X' is invalid.*"):
+        SFT.fft_mode = 'onesided2X'
+    with pytest.raises(ValueError, match="Attribute mfft=7 needs to be " +
+                                         "at least the window length.*"):
+        SFT.mfft = 7
+    with pytest.raises(ValueError, match="scaling='invalid' not in.*"):
+        # noinspection PyTypeChecker
+        SFT.scale_to('invalid')
+    with pytest.raises(ValueError, match="phase_shift=3.0 has the unit .*"):
+        SFT.phase_shift = 3.0
+    with pytest.raises(ValueError, match="-mfft < phase_shift < mfft " +
+                                         "does not hold.*"):
+        SFT.phase_shift = 2*SFT.mfft
+    with pytest.raises(ValueError, match="Parameter padding='invalid' not.*"):
+        # noinspection PyTypeChecker
+        g = SFT._x_slices(np.zeros(16), k_off=0, p0=0, p1=1, padding='invalid')
+        next(g)  # execute generator
+    with pytest.raises(ValueError, match="Trend type must be 'linear' " +
+                                         "or 'constant'"):
+        # noinspection PyTypeChecker
+        SFT.stft_detrend(np.zeros(16), detr='invalid')
+    with pytest.raises(ValueError, match="Parameter detr=nan is not a str, " +
+                                         "function or None!"):
+        # noinspection PyTypeChecker
+        SFT.stft_detrend(np.zeros(16), detr=np.nan)
+    with pytest.raises(ValueError, match="Invalid Parameter p0=0, p1=200.*"):
+        SFT.p_range(100, 0, 200)
+
+    with pytest.raises(ValueError, match="f_axis=0 may not be equal to " +
+                                         "t_axis=0!"):
+        SFT.istft(np.zeros((SFT.f_pts, 2)), t_axis=0, f_axis=0)
+    with pytest.raises(ValueError, match=r"S.shape\[f_axis\]=2 must be equal" +
+                                         " to self.f_pts=5.*"):
+        SFT.istft(np.zeros((2, 2)))
+    with pytest.raises(ValueError, match=r"S.shape\[t_axis\]=1 needs to have" +
+                                         " at least 2 slices.*"):
+        SFT.istft(np.zeros((SFT.f_pts, 1)))
+    with pytest.raises(ValueError, match=r".*\(k1=100\) <= \(k_max=12\) " +
+                                         "is false!$"):
+        SFT.istft(np.zeros((SFT.f_pts, 3)), k1=100)
+    with pytest.raises(ValueError, match=r"\(k1=1\) - \(k0=0\) = 1 has to " +
+                                         "be at least.* length 4!"):
+        SFT.istft(np.zeros((SFT.f_pts, 3)), k0=0, k1=1)
+
+    with pytest.raises(ValueError, match=r"Parameter axes_seq='invalid' " +
+                                         r"not in \['tf', 'ft'\]!"):
+        # noinspection PyTypeChecker
+        SFT.extent(n=100, axes_seq='invalid')
+    with pytest.raises(ValueError, match="Attribute fft_mode=twosided must.*"):
+        SFT.fft_mode = 'twosided'
+        SFT.extent(n=100)
+
+
+@pytest.mark.parametrize('m', ('onesided', 'onesided2X'))
+def test_exceptions_fft_mode_complex_win(m: FFT_MODE_TYPE):
+    """Verify that one-sided spectra are not allowed with complex-valued
+    windows or with complex-valued signals.
+
+    The reason being, the `rfft` function only accepts real-valued input.
+    """
+    with pytest.raises(ValueError,
+                       match=f"One-sided spectra, i.e., fft_mode='{m}'.*"):
+        ShortTimeFFT(np.ones(8)*1j, hop=4, fs=1, fft_mode=m)
+
+    SFT = ShortTimeFFT(np.ones(8)*1j, hop=4, fs=1, fft_mode='twosided')
+    with pytest.raises(ValueError,
+                       match=f"One-sided spectra, i.e., fft_mode='{m}'.*"):
+        SFT.fft_mode = m
+
+    SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1, scale_to='psd', fft_mode='onesided')
+    with pytest.raises(ValueError, match="Complex-valued `x` not allowed for self.*"):
+        SFT.stft(np.ones(8)*1j)
+    SFT.fft_mode = 'onesided2X'
+    with pytest.raises(ValueError, match="Complex-valued `x` not allowed for self.*"):
+        SFT.stft(np.ones(8)*1j)
+
+
+def test_invalid_fft_mode_RuntimeError():
+    """Ensure exception gets raised when property `fft_mode` is invalid. """
+    SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+    SFT._fft_mode = 'invalid_typ'
+
+    with pytest.raises(RuntimeError):
+        _ = SFT.f
+    with pytest.raises(RuntimeError):
+        SFT._fft_func(np.ones(8))
+    with pytest.raises(RuntimeError):
+        SFT._ifft_func(np.ones(8))
+
+
+@pytest.mark.parametrize('win_params, Nx', [(('gaussian', 2.), 9),  # in docstr
+                                            ('triang', 7),
+                                            (('kaiser', 4.0), 9),
+                                            (('exponential', None, 1.), 9),
+                                            (4.0, 9)])
+def test_from_window(win_params, Nx: int):
+    """Verify that `from_window()` handles parameters correctly.
+
+    The window parameterizations are documented in the `get_window` docstring.
+    """
+    w_sym, fs = get_window(win_params, Nx, fftbins=False), 16.
+    w_per = get_window(win_params, Nx, fftbins=True)
+    SFT0 = ShortTimeFFT(w_sym, hop=3, fs=fs, fft_mode='twosided',
+                        scale_to='psd', phase_shift=1)
+    nperseg = len(w_sym)
+    noverlap = nperseg - SFT0.hop
+    SFT1 = ShortTimeFFT.from_window(win_params, fs, nperseg, noverlap,
+                                    symmetric_win=True, fft_mode='twosided',
+                                    scale_to='psd', phase_shift=1)
+    # periodic window:
+    SFT2 = ShortTimeFFT.from_window(win_params, fs, nperseg, noverlap,
+                                    symmetric_win=False, fft_mode='twosided',
+                                    scale_to='psd', phase_shift=1)
+    # Be informative when comparing instances:
+    xp_assert_equal(SFT1.win, SFT0.win)
+    xp_assert_close(SFT2.win, w_per / np.sqrt(sum(w_per**2) * fs))
+    for n_ in ('hop', 'T', 'fft_mode', 'mfft', 'scaling', 'phase_shift'):
+        v0, v1, v2 = (getattr(SFT_, n_) for SFT_ in (SFT0, SFT1, SFT2))
+        assert v1 == v0, f"SFT1.{n_}={v1} does not equal SFT0.{n_}={v0}"
+        assert v2 == v0, f"SFT2.{n_}={v2} does not equal SFT0.{n_}={v0}"
+
+
+def test_dual_win_roundtrip():
+    """Verify the duality of `win` and `dual_win`.
+
+    Note that this test does not work for arbitrary windows, since dual windows
+    are not unique. It always works for invertible STFTs if the windows do not
+    overlap.
+    """
+    # Non-standard values for keyword arguments (except for `scale_to`):
+    kw = dict(hop=4, fs=1, fft_mode='twosided', mfft=8, scale_to=None,
+              phase_shift=2)
+    SFT0 = ShortTimeFFT(np.ones(4), **kw)
+    SFT1 = ShortTimeFFT.from_dual(SFT0.dual_win, **kw)
+    xp_assert_close(SFT1.dual_win, SFT0.win)
+
+
+@pytest.mark.parametrize('scale_to, fac_psd, fac_mag',
+                         [(None, 0.25, 0.125),
+                          ('magnitude', 2.0, 1),
+                          ('psd', 1, 0.5)])
+def test_scaling(scale_to: Literal['magnitude', 'psd'], fac_psd, fac_mag):
+    """Verify scaling calculations.
+
+    * Verify passing `scale_to`parameter  to ``__init__().
+    * Roundtrip while changing scaling factor.
+    """
+    SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=scale_to)
+    assert SFT.fac_psd == fac_psd
+    assert SFT.fac_magnitude == fac_mag
+    # increase coverage by accessing properties twice:
+    assert SFT.fac_psd == fac_psd
+    assert SFT.fac_magnitude == fac_mag
+
+    x = np.fft.irfft([0, 0, 7, 0, 0, 0, 0])  # periodic signal
+    Sx = SFT.stft(x)
+    Sx_mag, Sx_psd = Sx * SFT.fac_magnitude, Sx * SFT.fac_psd
+
+    SFT.scale_to('magnitude')
+    x_mag = SFT.istft(Sx_mag, k1=len(x))
+    xp_assert_close(x_mag, x)
+
+    SFT.scale_to('psd')
+    x_psd = SFT.istft(Sx_psd, k1=len(x))
+    xp_assert_close(x_psd, x)
+
+
+def test_scale_to():
+    """Verify `scale_to()` method."""
+    SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=None)
+
+    SFT.scale_to('magnitude')
+    assert SFT.scaling == 'magnitude'
+    assert SFT.fac_psd == 2.0
+    assert SFT.fac_magnitude == 1
+
+    SFT.scale_to('psd')
+    assert SFT.scaling == 'psd'
+    assert SFT.fac_psd == 1
+    assert SFT.fac_magnitude == 0.5
+
+    SFT.scale_to('psd')  # needed for coverage
+
+    for scale, s_fac in zip(('magnitude', 'psd'), (8, 4)):
+        SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=None)
+        dual_win = SFT.dual_win.copy()
+
+        SFT.scale_to(cast(Literal['magnitude', 'psd'], scale))
+        xp_assert_close(SFT.dual_win, dual_win * s_fac)
+
+
+def test_x_slices_padding():
+    """Verify padding.
+
+    The reference arrays were taken from  the docstrings of `zero_ext`,
+    `const_ext`, `odd_ext()`, and `even_ext()` from the _array_tools module.
+    """
+    SFT = ShortTimeFFT(np.ones(5), hop=4, fs=1)
+    x = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]], dtype=float)
+    d = {'zeros': [[[0, 0, 1, 2, 3], [0, 0, 0, 1, 4]],
+                   [[3, 4, 5, 0, 0], [4, 9, 16, 0, 0]]],
+         'edge': [[[1, 1, 1, 2, 3], [0, 0, 0, 1, 4]],
+                  [[3, 4, 5, 5, 5], [4, 9, 16, 16, 16]]],
+         'even': [[[3, 2, 1, 2, 3], [4, 1, 0, 1, 4]],
+                  [[3, 4, 5, 4, 3], [4, 9, 16, 9, 4]]],
+         'odd': [[[-1, 0, 1, 2, 3], [-4, -1, 0, 1, 4]],
+                 [[3, 4, 5, 6, 7], [4, 9, 16, 23, 28]]]}
+    for p_, xx in d.items():
+        gen = SFT._x_slices(np.array(x), 0, 0, 2, padding=cast(PAD_TYPE, p_))
+        yy = np.array([y_.copy() for y_ in gen])  # due to inplace copying
+        xx = np.asarray(xx, dtype=np.float64)
+        xp_assert_equal(yy, xx, err_msg=f"Failed '{p_}' padding.")
+
+
+def test_invertible():
+    """Verify `invertible` property. """
+    SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+    assert SFT.invertible
+    SFT = ShortTimeFFT(np.ones(8), hop=9, fs=1)
+    assert not SFT.invertible
+
+
+def test_border_values():
+    """Ensure that minimum and maximum values of slices are correct."""
+    SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+    assert SFT.p_min == 0
+    assert SFT.k_min == -4
+    assert SFT.lower_border_end == (4, 1)
+    assert SFT.lower_border_end == (4, 1)  # needed to test caching
+    assert SFT.p_max(10) == 4
+    assert SFT.k_max(10) == 16
+    assert SFT.upper_border_begin(10) == (4, 2)
+    # Raise exceptions:
+    with pytest.raises(ValueError, match="^Parameter n must be"):
+        SFT.upper_border_begin(3)
+    with pytest.raises(ValueError, match="^Parameter n must be"):
+        SFT._post_padding(3)
+
+def test_border_values_exotic():
+    """Ensure that the border calculations are correct for windows with
+    zeros. """
+    w = np.array([0, 0, 0, 0, 0, 0, 0, 1.])
+    SFT = ShortTimeFFT(w, hop=1, fs=1)
+    assert SFT.lower_border_end == (0, 0)
+
+    SFT = ShortTimeFFT(np.flip(w), hop=20, fs=1)
+    assert SFT.upper_border_begin(4) == (16, 1)
+    assert SFT.upper_border_begin(5) == (16, 1)
+    assert SFT.upper_border_begin(23) == (36, 2)
+    assert SFT.upper_border_begin(24) == (36, 2)
+    assert SFT.upper_border_begin(25) == (36, 2)
+
+    SFT._hop = -1  # provoke unreachable line
+    with pytest.raises(RuntimeError):
+        _ = SFT.k_max(4)
+    with pytest.raises(RuntimeError):
+        _ = SFT.k_min
+
+
+def test_t():
+    """Verify that the times of the slices are correct. """
+    SFT = ShortTimeFFT(np.ones(8), hop=4, fs=2)
+    assert SFT.T == 1/2
+    assert SFT.fs == 2.
+    assert SFT.delta_t == 4 * 1/2
+    t_stft = np.arange(0, SFT.p_max(10)) * SFT.delta_t
+    xp_assert_equal(SFT.t(10), t_stft)
+    xp_assert_equal(SFT.t(10, 1, 3), t_stft[1:3])
+    SFT.T = 1/4
+    assert SFT.T == 1/4
+    assert SFT.fs == 4
+    SFT.fs = 1/8
+    assert SFT.fs == 1/8
+    assert SFT.T == 8
+
+
+@pytest.mark.parametrize('fft_mode, f',
+                         [('onesided', [0., 1., 2.]),
+                          ('onesided2X', [0., 1., 2.]),
+                          ('twosided', [0., 1., 2., -2., -1.]),
+                          ('centered', [-2., -1., 0., 1., 2.])])
+def test_f(fft_mode: FFT_MODE_TYPE, f):
+    """Verify the frequency values property `f`."""
+    SFT = ShortTimeFFT(np.ones(5), hop=4, fs=5, fft_mode=fft_mode,
+                       scale_to='psd')
+    xp_assert_equal(SFT.f, f)
+
+
+@pytest.mark.parametrize('n', [20, 21])
+@pytest.mark.parametrize('m', [5, 6])
+@pytest.mark.parametrize('fft_mode', ['onesided', 'centered'])
+def test_extent(n, m, fft_mode: FFT_MODE_TYPE):
+    """Ensure that the `extent()` method is correct. """
+    SFT = ShortTimeFFT(np.ones(m), hop=m, fs=m, fft_mode=fft_mode)
+
+    t0 = SFT.t(n)[0]  # first timestamp
+    t1 = SFT.t(n)[-1] + SFT.delta_t  # last timestamp + 1
+    t0c, t1c = t0 - SFT.delta_t / 2, t1 - SFT.delta_t / 2  # centered timestamps
+
+    f0 = SFT.f[0]  # first frequency
+    f1 = SFT.f[-1] + SFT.delta_f  # last frequency + 1
+    f0c, f1c = f0 - SFT.delta_f / 2, f1 - SFT.delta_f / 2  # centered frequencies
+
+    assert SFT.extent(n, 'tf', False) == (t0, t1, f0, f1)
+    assert SFT.extent(n, 'ft', False) == (f0, f1, t0, t1)
+    assert SFT.extent(n, 'tf', True) == (t0c, t1c, f0c, f1c)
+    assert SFT.extent(n, 'ft', True) == (f0c, f1c, t0c, t1c)
+
+
+def test_spectrogram():
+    """Verify spectrogram and cross-spectrogram methods. """
+    SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+    x, y = np.ones(10), np.arange(10)
+    X, Y = SFT.stft(x), SFT.stft(y)
+    xp_assert_close(SFT.spectrogram(x), X.real**2+X.imag**2)
+    xp_assert_close(SFT.spectrogram(x, y), X * Y.conj())
+
+
+@pytest.mark.parametrize('n', [8, 9])
+def test_fft_func_roundtrip(n: int):
+    """Test roundtrip `ifft_func(fft_func(x)) == x` for all permutations of
+    relevant parameters. """
+    np.random.seed(2394795)
+    x0 = np.random.rand(n)
+    w, h_n = np.ones(n), 4
+
+    pp = dict(
+        fft_mode=get_args(FFT_MODE_TYPE),
+        mfft=[None, n, n+1, n+2],
+        scaling=[None, 'magnitude', 'psd'],
+        phase_shift=[None, -n+1, 0, n // 2, n-1])
+    for f_typ, mfft, scaling, phase_shift in product(*pp.values()):
+        if f_typ == 'onesided2X' and scaling is None:
+            continue  # this combination is forbidden
+        SFT = ShortTimeFFT(w, h_n, fs=n, fft_mode=f_typ, mfft=mfft,
+                           scale_to=scaling, phase_shift=phase_shift)
+        X0 = SFT._fft_func(x0)
+        x1 = SFT._ifft_func(X0)
+        xp_assert_close(x0.astype(x1.dtype), x1,
+                        err_msg="_fft_func() roundtrip failed for " +
+                        f"{f_typ=}, {mfft=}, {scaling=}, {phase_shift=}")
+
+    SFT = ShortTimeFFT(w, h_n, fs=1)
+    SFT._fft_mode = 'invalid_fft'  # type: ignore
+    with pytest.raises(RuntimeError):
+        SFT._fft_func(x0)
+    with pytest.raises(RuntimeError):
+        SFT._ifft_func(x0)
+
+
+@pytest.mark.parametrize('i', range(19))
+def test_impulse_roundtrip(i):
+    """Roundtrip for an impulse being at different positions `i`."""
+    n = 19
+    w, h_n = np.ones(8), 3
+    x = np.zeros(n)
+    x[i] = 1
+
+    SFT = ShortTimeFFT(w, hop=h_n, fs=1, scale_to=None, phase_shift=None)
+    Sx = SFT.stft(x)
+    # test slicing the input signal into two parts:
+    n_q = SFT.nearest_k_p(n // 2)
+    Sx0 = SFT.stft(x[:n_q], padding='zeros')
+    Sx1 = SFT.stft(x[n_q:], padding='zeros')
+    q0_ub = SFT.upper_border_begin(n_q)[1] - SFT.p_min
+    q1_le = SFT.lower_border_end[1] - SFT.p_min
+    xp_assert_close(Sx0[:, :q0_ub], Sx[:, :q0_ub], err_msg=f"{i=}")
+    xp_assert_close(Sx1[:, q1_le:], Sx[:, q1_le-Sx1.shape[1]:],
+                    err_msg=f"{i=}")
+
+    Sx01 = np.hstack((Sx0[:, :q0_ub],
+                      Sx0[:, q0_ub:] + Sx1[:, :q1_le],
+                      Sx1[:, q1_le:]))
+    xp_assert_close(Sx, Sx01, atol=1e-8, err_msg=f"{i=}")
+
+    y = SFT.istft(Sx, 0, n)
+    xp_assert_close(y, x, atol=1e-8, err_msg=f"{i=}")
+    y0 = SFT.istft(Sx, 0, n//2)
+    xp_assert_close(x[:n//2], y0, atol=1e-8, err_msg=f"{i=}")
+    y1 = SFT.istft(Sx, n // 2, n)
+    xp_assert_close(x[n // 2:], y1, atol=1e-8, err_msg=f"{i=}")
+
+
+@pytest.mark.parametrize('hop', [1, 7, 8])
+def test_asymmetric_window_roundtrip(hop: int):
+    """An asymmetric window could uncover indexing problems. """
+    np.random.seed(23371)
+
+    w = np.arange(16) / 8  # must be of type float
+    w[len(w)//2:] = 1
+    SFT = ShortTimeFFT(w, hop, fs=1)
+
+    x = 10 * np.random.randn(64)
+    Sx = SFT.stft(x)
+    x1 = SFT.istft(Sx, k1=len(x))
+    xp_assert_close(x1, x1, err_msg="Roundtrip for asymmetric window with " +
+                                    f" {hop=} failed!")
+
+
+@pytest.mark.parametrize('m_num', [6, 7])
+def test_minimal_length_signal(m_num):
+    """Verify that the shortest allowed signal works. """
+    SFT = ShortTimeFFT(np.ones(m_num), m_num//2, fs=1)
+    n = math.ceil(m_num/2)
+    x = np.ones(n)
+    Sx = SFT.stft(x)
+    x1 = SFT.istft(Sx, k1=n)
+    xp_assert_close(x1, x, err_msg=f"Roundtrip minimal length signal ({n=})" +
+                                   f" for {m_num} sample window failed!")
+    with pytest.raises(ValueError, match=rf"len\(x\)={n-1} must be >= ceil.*"):
+        SFT.stft(x[:-1])
+    with pytest.raises(ValueError, match=rf"S.shape\[t_axis\]={Sx.shape[1]-1}"
+                       f" needs to have at least {Sx.shape[1]} slices"):
+        SFT.istft(Sx[:, :-1], k1=n)
+
+
+def test_tutorial_stft_sliding_win():
+    """Verify example in "Sliding Windows" subsection from the "User Guide".
+
+    In :ref:`tutorial_stft_sliding_win` (file ``signal.rst``) of the
+    :ref:`user_guide` the behavior the border behavior of
+    ``ShortTimeFFT(np.ones(6), 2, fs=1)`` with a 50 sample signal is discussed.
+    This test verifies the presented indexes.
+    """
+    SFT = ShortTimeFFT(np.ones(6), 2, fs=1)
+
+    # Lower border:
+    assert SFT.m_num_mid == 3, f"Slice middle is not 3 but {SFT.m_num_mid=}"
+    assert SFT.p_min == -1, f"Lowest slice {SFT.p_min=} is not -1"
+    assert SFT.k_min == -5, f"Lowest slice sample {SFT.p_min=} is not -5"
+    k_lb, p_lb = SFT.lower_border_end
+    assert p_lb == 2, f"First unaffected slice {p_lb=} is not 2"
+    assert k_lb == 5, f"First unaffected sample {k_lb=} is not 5"
+
+    n = 50  # upper signal border
+    assert (p_max := SFT.p_max(n)) == 27, f"Last slice {p_max=} must be 27"
+    assert (k_max := SFT.k_max(n)) == 55, f"Last sample {k_max=} must be 55"
+    k_ub, p_ub = SFT.upper_border_begin(n)
+    assert p_ub == 24, f"First upper border slice {p_ub=} must be 24"
+    assert k_ub == 45, f"First upper border slice {k_ub=} must be 45"
+
+
+def test_tutorial_stft_legacy_stft():
+    """Verify STFT example in "Comparison with Legacy Implementation" from the
+    "User Guide".
+
+    In :ref:`tutorial_stft_legacy_stft` (file ``signal.rst``) of the
+    :ref:`user_guide` the legacy and the new implementation are compared.
+    """
+    fs, N = 200, 1001  # # 200 Hz sampling rate for 5 s signal
+    t_z = np.arange(N) / fs  # time indexes for signal
+    z = np.exp(2j*np.pi * 70 * (t_z - 0.2 * t_z ** 2))  # complex-valued chirp
+
+    nperseg, noverlap = 50, 40
+    win = ('gaussian', 1e-2 * fs)  # Gaussian with 0.01 s standard deviation
+
+    # Legacy STFT:
+    f0_u, t0, Sz0_u = stft(z, fs, win, nperseg, noverlap,
+                           return_onesided=False, scaling='spectrum')
+    Sz0 = fftshift(Sz0_u, axes=0)
+
+    # New STFT:
+    SFT = ShortTimeFFT.from_window(win, fs, nperseg, noverlap,
+                                   fft_mode='centered',
+                                   scale_to='magnitude', phase_shift=None)
+    Sz1 = SFT.stft(z)
+
+    xp_assert_close(Sz0, Sz1[:, 2:-1])
+
+    xp_assert_close((abs(Sz1[:, 1]).min(), abs(Sz1[:, 1]).max()),
+                    (6.925060911593139e-07, 8.00271269218721e-07))
+
+    t0_r, z0_r = istft(Sz0_u, fs, win, nperseg, noverlap, input_onesided=False,
+                       scaling='spectrum')
+    z1_r = SFT.istft(Sz1, k1=N)
+    assert len(z0_r) == N + 9
+    xp_assert_close(z0_r[:N], z)
+    xp_assert_close(z1_r, z)
+
+    #  Spectrogram is just the absolute square of th STFT:
+    xp_assert_close(SFT.spectrogram(z), abs(Sz1) ** 2)
+
+
+def test_tutorial_stft_legacy_spectrogram():
+    """Verify spectrogram example in "Comparison with Legacy Implementation"
+    from the "User Guide".
+
+    In :ref:`tutorial_stft_legacy_stft` (file ``signal.rst``) of the
+    :ref:`user_guide` the legacy and the new implementation are compared.
+    """
+    fs, N = 200, 1001  # 200 Hz sampling rate for almost 5 s signal
+    t_z = np.arange(N) / fs  # time indexes for signal
+    z = np.exp(2j*np.pi*70 * (t_z - 0.2*t_z**2))  # complex-valued sweep
+
+    nperseg, noverlap = 50, 40
+    win = ('gaussian', 1e-2 * fs)  # Gaussian with 0.01 s standard dev.
+
+    # Legacy spectrogram:
+    f2_u, t2, Sz2_u = spectrogram(z, fs, win, nperseg, noverlap, detrend=None,
+                                  return_onesided=False, scaling='spectrum',
+                                  mode='complex')
+
+    f2, Sz2 = fftshift(f2_u), fftshift(Sz2_u, axes=0)
+
+    # New STFT:
+    SFT = ShortTimeFFT.from_window(win, fs, nperseg, noverlap,
+                                   fft_mode='centered', scale_to='magnitude',
+                                   phase_shift=None)
+    Sz3 = SFT.stft(z, p0=0, p1=(N-noverlap) // SFT.hop, k_offset=nperseg // 2)
+    t3 = SFT.t(N, p0=0, p1=(N-noverlap) // SFT.hop, k_offset=nperseg // 2)
+
+    xp_assert_close(t2, t3)
+    xp_assert_close(f2, SFT.f)
+    xp_assert_close(Sz2, Sz3)
+
+
+def test_permute_axes():
+    """Verify correctness of four-dimensional signal by permuting its
+    shape. """
+    n = 25
+    SFT = ShortTimeFFT(np.ones(8)/8, hop=3, fs=n)
+    x0 = np.arange(n, dtype=np.float64)
+    Sx0 = SFT.stft(x0)
+    Sx0 = Sx0.reshape((Sx0.shape[0], 1, 1, 1, Sx0.shape[-1]))
+    SxT = np.moveaxis(Sx0, (0, -1), (-1, 0))
+
+    atol = 2 * np.finfo(SFT.win.dtype).resolution
+    for i in range(4):
+        y = np.reshape(x0, np.roll((n, 1, 1, 1), i))
+        Sy = SFT.stft(y, axis=i)
+        xp_assert_close(Sy, np.moveaxis(Sx0, 0, i))
+
+        yb0 = SFT.istft(Sy, k1=n, f_axis=i)
+        xp_assert_close(yb0, y, atol=atol)
+        # explicit t-axis parameter (for coverage):
+        yb1 = SFT.istft(Sy, k1=n, f_axis=i, t_axis=Sy.ndim-1)
+        xp_assert_close(yb1, y, atol=atol)
+
+        SyT = np.moveaxis(Sy, (i, -1), (-1, i))
+        xp_assert_close(SyT, np.moveaxis(SxT, 0, i))
+
+        ybT = SFT.istft(SyT, k1=n, t_axis=i, f_axis=-1)
+        xp_assert_close(ybT, y, atol=atol)
+
+
+@pytest.mark.parametrize("fft_mode",
+                         ('twosided', 'centered', 'onesided', 'onesided2X'))
+def test_roundtrip_multidimensional(fft_mode: FFT_MODE_TYPE):
+    """Test roundtrip of a multidimensional input signal versus its components.
+
+    This test can uncover potential problems with `fftshift()`.
+    """
+    n = 9
+    x = np.arange(4*n*2, dtype=np.float64).reshape(4, n, 2)
+    SFT = ShortTimeFFT(get_window('hann', 4), hop=2, fs=1,
+                       scale_to='magnitude', fft_mode=fft_mode)
+    Sx = SFT.stft(x, axis=1)
+    y = SFT.istft(Sx, k1=n, f_axis=1, t_axis=-1)
+    xp_assert_close(y, x.astype(y.dtype), err_msg='Multidim. roundtrip failed!')
+
+    for i, j in product(range(x.shape[0]), range(x.shape[2])):
+        y_ = SFT.istft(Sx[i, :, j, :], k1=n)
+        xp_assert_close(y_, x[i, :, j].astype(y_.dtype),
+                        err_msg="Multidim. roundtrip for component " +
+                        f"x[{i}, :, {j}] and {fft_mode=} failed!")
+
+@pytest.mark.parametrize("phase_shift", (0, 4,  None))
+def test_roundtrip_two_dimensional(phase_shift: int|None):
+    """Test roundtrip of a 2 channel input signal with `mfft` set with different
+    values for `phase_shift`
+
+    Tests for Issue https://github.com/scipy/scipy/issues/21671
+    """
+    n = 21
+    SFT = ShortTimeFFT.from_window('hann', fs=1, nperseg=13, noverlap=7,
+                                   mfft=16, phase_shift=phase_shift)
+    x = np.arange(2*n, dtype=float).reshape(2, n)
+    Sx = SFT.stft(x)
+    y = SFT.istft(Sx, k1=n)
+    xp_assert_close(y, x, atol=2 * np.finfo(SFT.win.dtype).resolution,
+                    err_msg='2-dim. roundtrip failed!')
+
+
+@pytest.mark.parametrize('window, n, nperseg, noverlap',
+                         [('boxcar', 100, 10, 0),     # Test no overlap
+                          ('boxcar', 100, 10, 9),     # Test high overlap
+                          ('bartlett', 101, 51, 26),  # Test odd nperseg
+                          ('hann', 1024, 256, 128),   # Test defaults
+                          (('tukey', 0.5), 1152, 256, 64),  # Test Tukey
+                          ('hann', 1024, 256, 255),   # Test overlapped hann
+                          ('boxcar', 100, 10, 3),     # NOLA True, COLA False
+                          ('bartlett', 101, 51, 37),  # NOLA True, COLA False
+                          ('hann', 1024, 256, 127),   # NOLA True, COLA False
+                          # NOLA True, COLA False:
+                          (('tukey', 0.5), 1152, 256, 14),
+                          ('hann', 1024, 256, 5)])    # NOLA True, COLA False
+def test_roundtrip_windows(window, n: int, nperseg: int, noverlap: int):
+    """Roundtrip test adapted from `test_spectral.TestSTFT`.
+
+    The parameters are taken from the methods test_roundtrip_real(),
+    test_roundtrip_nola_not_cola(), test_roundtrip_float32(),
+    test_roundtrip_complex().
+    """
+    np.random.seed(2394655)
+
+    w = get_window(window, nperseg)
+    SFT = ShortTimeFFT(w, nperseg - noverlap, fs=1, fft_mode='twosided',
+                       phase_shift=None)
+
+    z = 10 * np.random.randn(n) + 10j * np.random.randn(n)
+    Sz = SFT.stft(z)
+    z1 = SFT.istft(Sz, k1=len(z))
+    xp_assert_close(z, z1, err_msg="Roundtrip for complex values failed")
+
+    x = 10 * np.random.randn(n)
+    Sx = SFT.stft(x)
+    x1 = SFT.istft(Sx, k1=len(z))
+    xp_assert_close(x.astype(np.complex128), x1,
+                    err_msg="Roundtrip for float values failed")
+
+    x32 = x.astype(np.float32)
+    Sx32 = SFT.stft(x32)
+    x32_1 = SFT.istft(Sx32, k1=len(x32))
+    x32_1_r = x32_1.real
+    xp_assert_close(x32, x32_1_r.astype(np.float32),
+                    err_msg="Roundtrip for 32 Bit float values failed")
+    xp_assert_close(x32.imag, np.zeros_like(x32.imag),
+                    err_msg="Roundtrip for 32 Bit float values failed")
+
+
+@pytest.mark.parametrize('signal_type', ('real', 'complex'))
+def test_roundtrip_complex_window(signal_type):
+    """Test roundtrip for complex-valued window function
+
+    The purpose of this test is to check if the dual window is calculated
+    correctly for complex-valued windows.
+    """
+    np.random.seed(1354654)
+    win = np.exp(2j*np.linspace(0, np.pi, 8))
+    SFT = ShortTimeFFT(win, 3, fs=1, fft_mode='twosided')
+
+    z = 10 * np.random.randn(11)
+    if signal_type == 'complex':
+        z = z + 2j * z
+    Sz = SFT.stft(z)
+    z1 = SFT.istft(Sz, k1=len(z))
+    xp_assert_close(z.astype(np.complex128), z1,
+                    err_msg="Roundtrip for complex-valued window failed")
+
+
+def test_average_all_segments():
+    """Compare `welch` function with stft mean.
+
+    Ported from `TestSpectrogram.test_average_all_segments` from file
+    ``test__spectral.py``.
+    """
+    x = np.random.randn(1024)
+
+    fs = 1.0
+    window = ('tukey', 0.25)
+    nperseg, noverlap = 16, 2
+    fw, Pw = welch(x, fs, window, nperseg, noverlap)
+    SFT = ShortTimeFFT.from_window(window, fs, nperseg, noverlap,
+                                   fft_mode='onesided2X', scale_to='psd',
+                                   phase_shift=None)
+    # `welch` positions the window differently than the STFT:
+    P = SFT.spectrogram(x, detr='constant', p0=0,
+                        p1=(len(x)-noverlap)//SFT.hop, k_offset=nperseg//2)
+
+    xp_assert_close(SFT.f, fw)
+    xp_assert_close(np.mean(P, axis=-1), Pw)
+
+
+@pytest.mark.parametrize('window, N, nperseg, noverlap, mfft',
+                         # from test_roundtrip_padded_FFT:
+                         [('hann', 1024, 256, 128, 512),
+                          ('hann', 1024, 256, 128, 501),
+                          ('boxcar', 100, 10, 0, 33),
+                          (('tukey', 0.5), 1152, 256, 64, 1024),
+                          # from test_roundtrip_padded_signal:
+                          ('boxcar', 101, 10, 0, None),
+                          ('hann', 1000, 256, 128, None),
+                          # from test_roundtrip_boundary_extension:
+                          ('boxcar', 100, 10, 0, None),
+                          ('boxcar', 100, 10, 9, None)])
+@pytest.mark.parametrize('padding', get_args(PAD_TYPE))
+def test_stft_padding_roundtrip(window, N: int, nperseg: int, noverlap: int,
+                                mfft: int, padding):
+    """Test the parameter 'padding' of `stft` with roundtrips.
+
+    The STFT parametrizations were taken from the methods
+    `test_roundtrip_padded_FFT`, `test_roundtrip_padded_signal` and
+    `test_roundtrip_boundary_extension` from class `TestSTFT` in  file
+    ``test_spectral.py``. Note that the ShortTimeFFT does not need the
+    concept of "boundary extension".
+    """
+    x = normal_distribution.rvs(size=N, random_state=2909)  # real signal
+    z = x * np.exp(1j * np.pi / 4)  # complex signal
+
+    SFT = ShortTimeFFT.from_window(window, 1, nperseg, noverlap,
+                                   fft_mode='twosided', mfft=mfft)
+    Sx = SFT.stft(x, padding=padding)
+    x1 = SFT.istft(Sx, k1=N)
+    xp_assert_close(x1, x.astype(np.complex128),
+                    err_msg=f"Failed real roundtrip with '{padding}' padding")
+
+    Sz = SFT.stft(z, padding=padding)
+    z1 = SFT.istft(Sz, k1=N)
+    xp_assert_close(z1, z, err_msg="Failed complex roundtrip with " +
+                    f" '{padding}' padding")
+
+
+@pytest.mark.parametrize('N_x', (128, 129, 255, 256, 1337))  # signal length
+@pytest.mark.parametrize('w_size', (128, 256))  # window length
+@pytest.mark.parametrize('t_step', (4, 64))  # SFT time hop
+@pytest.mark.parametrize('f_c', (7., 23.))  # frequency of input sine
+def test_energy_conservation(N_x: int, w_size: int, t_step: int, f_c: float):
+    """Test if a `psd`-scaled STFT conserves the L2 norm.
+
+    This test is adapted from MNE-Python [1]_. Besides being battle-tested,
+    this test has the benefit of using non-standard window including
+    non-positive values and a 2d input signal.
+
+    Since `ShortTimeFFT` requires the signal length `N_x` to be at least the
+    window length `w_size`, the parameter `N_x` was changed from
+    ``(127, 128, 255, 256, 1337)`` to ``(128, 129, 255, 256, 1337)`` to be
+    more useful.
+
+    .. [1] File ``test_stft.py`` of MNE-Python
+        https://github.com/mne-tools/mne-python/blob/main/mne/time_frequency/tests/test_stft.py
+    """
+    window = np.sin(np.arange(.5, w_size + .5) / w_size * np.pi)
+    SFT = ShortTimeFFT(window, t_step, fs=1000, fft_mode='onesided2X',
+                       scale_to='psd')
+    atol = 2*np.finfo(window.dtype).resolution
+    N_x = max(N_x, w_size)  # minimal sing
+    # Test with low frequency signal
+    t = np.arange(N_x).astype(np.float64)
+    x = np.sin(2 * np.pi * f_c * t * SFT.T)
+    x = np.array([x, x + 1.])
+    X = SFT.stft(x)
+    xp = SFT.istft(X, k1=N_x)
+
+    max_freq = SFT.f[np.argmax(np.sum(np.abs(X[0]) ** 2, axis=1))]
+
+    assert X.shape[1] == SFT.f_pts
+    assert np.all(SFT.f >= 0.)
+    assert np.abs(max_freq - f_c) < 1.
+    xp_assert_close(x, xp, atol=atol)
+
+    # check L2-norm squared (i.e., energy) conservation:
+    E_x = np.sum(x**2, axis=-1) * SFT.T  # numerical integration
+    aX2 = X.real**2 + X.imag.real**2
+    E_X = np.sum(np.sum(aX2, axis=-1) * SFT.delta_t, axis=-1) * SFT.delta_f
+    xp_assert_close(E_X, E_x, atol=atol)
+
+    # Test with random signal
+    np.random.seed(2392795)
+    x = np.random.randn(2, N_x)
+    X = SFT.stft(x)
+    xp = SFT.istft(X, k1=N_x)
+
+    assert X.shape[1] == SFT.f_pts
+    assert np.all(SFT.f >= 0.)
+    assert np.abs(max_freq - f_c) < 1.
+    xp_assert_close(x, xp, atol=atol)
+
+    # check L2-norm squared (i.e., energy) conservation:
+    E_x = np.sum(x**2, axis=-1) * SFT.T  # numeric integration
+    aX2 = X.real ** 2 + X.imag.real ** 2
+    E_X = np.sum(np.sum(aX2, axis=-1) * SFT.delta_t, axis=-1) * SFT.delta_f
+    xp_assert_close(E_X, E_x, atol=atol)
+
+    # Try with empty array
+    x = np.zeros((0, N_x))
+    X = SFT.stft(x)
+    xp = SFT.istft(X, k1=N_x)
+    assert xp.shape == x.shape
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..12dac6300b9ef4b2eac0475f0b53517ab4867416
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_spectral.py
@@ -0,0 +1,2059 @@
+import sys
+
+import numpy as np
+from numpy.testing import (assert_,
+                           assert_allclose, assert_array_equal, assert_equal,
+                           assert_array_almost_equal_nulp, suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy import signal
+from scipy.fft import fftfreq, rfftfreq, fft, irfft
+from scipy.integrate import trapezoid
+from scipy.signal import (periodogram, welch, lombscargle, coherence,
+                          spectrogram, check_COLA, check_NOLA)
+from scipy.signal.windows import hann
+from scipy.signal._spectral_py import _spectral_helper
+
+# Compare ShortTimeFFT.stft() / ShortTimeFFT.istft() with stft() / istft():
+from scipy.signal.tests._scipy_spectral_test_shim import stft_compare as stft
+from scipy.signal.tests._scipy_spectral_test_shim import istft_compare as istft
+from scipy.signal.tests._scipy_spectral_test_shim import csd_compare as csd
+
+
+class TestPeriodogram:
+    def test_real_onesided_even(self):
+        x = np.zeros(16)
+        x[0] = 1
+        f, p = periodogram(x)
+        assert_allclose(f, np.linspace(0, 0.5, 9))
+        q = np.ones(9)
+        q[0] = 0
+        q[-1] /= 2.0
+        q /= 8
+        assert_allclose(p, q)
+
+    def test_real_onesided_odd(self):
+        x = np.zeros(15)
+        x[0] = 1
+        f, p = periodogram(x)
+        assert_allclose(f, np.arange(8.0)/15.0)
+        q = np.ones(8)
+        q[0] = 0
+        q *= 2.0/15.0
+        assert_allclose(p, q, atol=1e-15)
+
+    def test_real_twosided(self):
+        x = np.zeros(16)
+        x[0] = 1
+        f, p = periodogram(x, return_onesided=False)
+        assert_allclose(f, fftfreq(16, 1.0))
+        q = np.full(16, 1/16.0)
+        q[0] = 0
+        assert_allclose(p, q)
+
+    def test_real_spectrum(self):
+        x = np.zeros(16)
+        x[0] = 1
+        f, p = periodogram(x, scaling='spectrum')
+        g, q = periodogram(x, scaling='density')
+        assert_allclose(f, np.linspace(0, 0.5, 9))
+        assert_allclose(p, q/16.0)
+
+    def test_integer_even(self):
+        x = np.zeros(16, dtype=int)
+        x[0] = 1
+        f, p = periodogram(x)
+        assert_allclose(f, np.linspace(0, 0.5, 9))
+        q = np.ones(9)
+        q[0] = 0
+        q[-1] /= 2.0
+        q /= 8
+        assert_allclose(p, q)
+
+    def test_integer_odd(self):
+        x = np.zeros(15, dtype=int)
+        x[0] = 1
+        f, p = periodogram(x)
+        assert_allclose(f, np.arange(8.0)/15.0)
+        q = np.ones(8)
+        q[0] = 0
+        q *= 2.0/15.0
+        assert_allclose(p, q, atol=1e-15)
+
+    def test_integer_twosided(self):
+        x = np.zeros(16, dtype=int)
+        x[0] = 1
+        f, p = periodogram(x, return_onesided=False)
+        assert_allclose(f, fftfreq(16, 1.0))
+        q = np.full(16, 1/16.0)
+        q[0] = 0
+        assert_allclose(p, q)
+
+    def test_complex(self):
+        x = np.zeros(16, np.complex128)
+        x[0] = 1.0 + 2.0j
+        f, p = periodogram(x, return_onesided=False)
+        assert_allclose(f, fftfreq(16, 1.0))
+        q = np.full(16, 5.0/16.0)
+        q[0] = 0
+        assert_allclose(p, q)
+
+    def test_unk_scaling(self):
+        assert_raises(ValueError, periodogram, np.zeros(4, np.complex128),
+                scaling='foo')
+
+    @pytest.mark.skipif(
+        sys.maxsize <= 2**32,
+        reason="On some 32-bit tolerance issue"
+    )
+    def test_nd_axis_m1(self):
+        x = np.zeros(20, dtype=np.float64)
+        x = x.reshape((2,1,10))
+        x[:,:,0] = 1.0
+        f, p = periodogram(x)
+        assert_array_equal(p.shape, (2, 1, 6))
+        assert_array_almost_equal_nulp(p[0,0,:], p[1,0,:], 60)
+        f0, p0 = periodogram(x[0,0,:])
+        assert_array_almost_equal_nulp(p0[np.newaxis,:], p[1,:], 60)
+
+    @pytest.mark.skipif(
+        sys.maxsize <= 2**32,
+        reason="On some 32-bit tolerance issue"
+    )
+    def test_nd_axis_0(self):
+        x = np.zeros(20, dtype=np.float64)
+        x = x.reshape((10,2,1))
+        x[0,:,:] = 1.0
+        f, p = periodogram(x, axis=0)
+        assert_array_equal(p.shape, (6,2,1))
+        assert_array_almost_equal_nulp(p[:,0,0], p[:,1,0], 60)
+        f0, p0 = periodogram(x[:,0,0])
+        assert_array_almost_equal_nulp(p0, p[:,1,0])
+
+    def test_window_external(self):
+        x = np.zeros(16)
+        x[0] = 1
+        f, p = periodogram(x, 10, 'hann')
+        win = signal.get_window('hann', 16)
+        fe, pe = periodogram(x, 10, win)
+        assert_array_almost_equal_nulp(p, pe)
+        assert_array_almost_equal_nulp(f, fe)
+        win_err = signal.get_window('hann', 32)
+        assert_raises(ValueError, periodogram, x,
+                      10, win_err)  # win longer than signal
+
+    def test_padded_fft(self):
+        x = np.zeros(16)
+        x[0] = 1
+        f, p = periodogram(x)
+        fp, pp = periodogram(x, nfft=32)
+        assert_allclose(f, fp[::2])
+        assert_allclose(p, pp[::2])
+        assert_array_equal(pp.shape, (17,))
+
+    def test_empty_input(self):
+        f, p = periodogram([])
+        assert_array_equal(f.shape, (0,))
+        assert_array_equal(p.shape, (0,))
+        for shape in [(0,), (3,0), (0,5,2)]:
+            f, p = periodogram(np.empty(shape))
+            assert_array_equal(f.shape, shape)
+            assert_array_equal(p.shape, shape)
+
+    def test_empty_input_other_axis(self):
+        for shape in [(3,0), (0,5,2)]:
+            f, p = periodogram(np.empty(shape), axis=1)
+            assert_array_equal(f.shape, shape)
+            assert_array_equal(p.shape, shape)
+
+    def test_short_nfft(self):
+        x = np.zeros(18)
+        x[0] = 1
+        f, p = periodogram(x, nfft=16)
+        assert_allclose(f, np.linspace(0, 0.5, 9))
+        q = np.ones(9)
+        q[0] = 0
+        q[-1] /= 2.0
+        q /= 8
+        assert_allclose(p, q)
+
+    def test_nfft_is_xshape(self):
+        x = np.zeros(16)
+        x[0] = 1
+        f, p = periodogram(x, nfft=16)
+        assert_allclose(f, np.linspace(0, 0.5, 9))
+        q = np.ones(9)
+        q[0] = 0
+        q[-1] /= 2.0
+        q /= 8
+        assert_allclose(p, q)
+
+    def test_real_onesided_even_32(self):
+        x = np.zeros(16, 'f')
+        x[0] = 1
+        f, p = periodogram(x)
+        assert_allclose(f, np.linspace(0, 0.5, 9))
+        q = np.ones(9, 'f')
+        q[0] = 0
+        q[-1] /= 2.0
+        q /= 8
+        assert_allclose(p, q)
+        assert_(p.dtype == q.dtype)
+
+    def test_real_onesided_odd_32(self):
+        x = np.zeros(15, 'f')
+        x[0] = 1
+        f, p = periodogram(x)
+        assert_allclose(f, np.arange(8.0)/15.0)
+        q = np.ones(8, 'f')
+        q[0] = 0
+        q *= 2.0/15.0
+        assert_allclose(p, q, atol=1e-7)
+        assert_(p.dtype == q.dtype)
+
+    def test_real_twosided_32(self):
+        x = np.zeros(16, 'f')
+        x[0] = 1
+        f, p = periodogram(x, return_onesided=False)
+        assert_allclose(f, fftfreq(16, 1.0))
+        q = np.full(16, 1/16.0, 'f')
+        q[0] = 0
+        assert_allclose(p, q)
+        assert_(p.dtype == q.dtype)
+
+    def test_complex_32(self):
+        x = np.zeros(16, 'F')
+        x[0] = 1.0 + 2.0j
+        f, p = periodogram(x, return_onesided=False)
+        assert_allclose(f, fftfreq(16, 1.0))
+        q = np.full(16, 5.0/16.0, 'f')
+        q[0] = 0
+        assert_allclose(p, q)
+        assert_(p.dtype == q.dtype)
+
+    def test_shorter_window_error(self):
+        x = np.zeros(16)
+        x[0] = 1
+        win = signal.get_window('hann', 10)
+        expected_msg = ('the size of the window must be the same size '
+                        'of the input on the specified axis')
+        with assert_raises(ValueError, match=expected_msg):
+            periodogram(x, window=win)
+
+
+class TestWelch:
+    def test_real_onesided_even(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=8)
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+                      0.11111111])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_real_onesided_odd(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=9)
+        assert_allclose(f, np.arange(5.0)/9.0)
+        q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113,
+                      0.17072113])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_real_twosided(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111,
+                      0.11111111, 0.11111111, 0.11111111, 0.07638889])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_real_spectrum(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=8, scaling='spectrum')
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([0.015625, 0.02864583, 0.04166667, 0.04166667,
+                      0.02083333])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_integer_onesided_even(self):
+        x = np.zeros(16, dtype=int)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=8)
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+                      0.11111111])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_integer_onesided_odd(self):
+        x = np.zeros(16, dtype=int)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=9)
+        assert_allclose(f, np.arange(5.0)/9.0)
+        q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113,
+                      0.17072113])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_integer_twosided(self):
+        x = np.zeros(16, dtype=int)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111,
+                      0.11111111, 0.11111111, 0.11111111, 0.07638889])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_complex(self):
+        x = np.zeros(16, np.complex128)
+        x[0] = 1.0 + 2.0j
+        x[8] = 1.0 + 2.0j
+        f, p = welch(x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.41666667, 0.38194444, 0.55555556, 0.55555556,
+                      0.55555556, 0.55555556, 0.55555556, 0.38194444])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_unk_scaling(self):
+        assert_raises(ValueError, welch, np.zeros(4, np.complex128),
+                      scaling='foo', nperseg=4)
+
+    def test_detrend_linear(self):
+        x = np.arange(10, dtype=np.float64) + 0.04
+        f, p = welch(x, nperseg=10, detrend='linear')
+        assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+    def test_no_detrending(self):
+        x = np.arange(10, dtype=np.float64) + 0.04
+        f1, p1 = welch(x, nperseg=10, detrend=False)
+        f2, p2 = welch(x, nperseg=10, detrend=lambda x: x)
+        assert_allclose(f1, f2, atol=1e-15)
+        assert_allclose(p1, p2, atol=1e-15)
+
+    def test_detrend_external(self):
+        x = np.arange(10, dtype=np.float64) + 0.04
+        f, p = welch(x, nperseg=10,
+                     detrend=lambda seg: signal.detrend(seg, type='l'))
+        assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+    def test_detrend_external_nd_m1(self):
+        x = np.arange(40, dtype=np.float64) + 0.04
+        x = x.reshape((2,2,10))
+        f, p = welch(x, nperseg=10,
+                     detrend=lambda seg: signal.detrend(seg, type='l'))
+        assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+    def test_detrend_external_nd_0(self):
+        x = np.arange(20, dtype=np.float64) + 0.04
+        x = x.reshape((2,1,10))
+        x = np.moveaxis(x, 2, 0)
+        f, p = welch(x, nperseg=10, axis=0,
+                     detrend=lambda seg: signal.detrend(seg, axis=0, type='l'))
+        assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+    def test_nd_axis_m1(self):
+        x = np.arange(20, dtype=np.float64) + 0.04
+        x = x.reshape((2,1,10))
+        f, p = welch(x, nperseg=10)
+        assert_array_equal(p.shape, (2, 1, 6))
+        assert_allclose(p[0,0,:], p[1,0,:], atol=1e-13, rtol=1e-13)
+        f0, p0 = welch(x[0,0,:], nperseg=10)
+        assert_allclose(p0[np.newaxis,:], p[1,:], atol=1e-13, rtol=1e-13)
+
+    def test_nd_axis_0(self):
+        x = np.arange(20, dtype=np.float64) + 0.04
+        x = x.reshape((10,2,1))
+        f, p = welch(x, nperseg=10, axis=0)
+        assert_array_equal(p.shape, (6,2,1))
+        assert_allclose(p[:,0,0], p[:,1,0], atol=1e-13, rtol=1e-13)
+        f0, p0 = welch(x[:,0,0], nperseg=10)
+        assert_allclose(p0, p[:,1,0], atol=1e-13, rtol=1e-13)
+
+    def test_window_external(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, 10, 'hann', nperseg=8)
+        win = signal.get_window('hann', 8)
+        fe, pe = welch(x, 10, win, nperseg=None)
+        assert_array_almost_equal_nulp(p, pe)
+        assert_array_almost_equal_nulp(f, fe)
+        assert_array_equal(fe.shape, (5,))  # because win length used as nperseg
+        assert_array_equal(pe.shape, (5,))
+        assert_raises(ValueError, welch, x,
+                      10, win, nperseg=4)  # because nperseg != win.shape[-1]
+        win_err = signal.get_window('hann', 32)
+        assert_raises(ValueError, welch, x,
+                      10, win_err, nperseg=None)  # win longer than signal
+
+    def test_empty_input(self):
+        f, p = welch([])
+        assert_array_equal(f.shape, (0,))
+        assert_array_equal(p.shape, (0,))
+        for shape in [(0,), (3,0), (0,5,2)]:
+            f, p = welch(np.empty(shape))
+            assert_array_equal(f.shape, shape)
+            assert_array_equal(p.shape, shape)
+
+    def test_empty_input_other_axis(self):
+        for shape in [(3,0), (0,5,2)]:
+            f, p = welch(np.empty(shape), axis=1)
+            assert_array_equal(f.shape, shape)
+            assert_array_equal(p.shape, shape)
+
+    def test_short_data(self):
+        x = np.zeros(8)
+        x[0] = 1
+        #for string-like window, input signal length < nperseg value gives
+        #UserWarning, sets nperseg to x.shape[-1]
+        with suppress_warnings() as sup:
+            msg = "nperseg = 256 is greater than input length  = 8, using nperseg = 8"
+            sup.filter(UserWarning, msg)
+            f, p = welch(x,window='hann')  # default nperseg
+            f1, p1 = welch(x,window='hann', nperseg=256)  # user-specified nperseg
+        f2, p2 = welch(x, nperseg=8)  # valid nperseg, doesn't give warning
+        assert_allclose(f, f2)
+        assert_allclose(p, p2)
+        assert_allclose(f1, f2)
+        assert_allclose(p1, p2)
+
+    def test_window_long_or_nd(self):
+        assert_raises(ValueError, welch, np.zeros(4), 1, np.array([1,1,1,1,1]))
+        assert_raises(ValueError, welch, np.zeros(4), 1,
+                      np.arange(6).reshape((2,3)))
+
+    def test_nondefault_noverlap(self):
+        x = np.zeros(64)
+        x[::8] = 1
+        f, p = welch(x, nperseg=16, noverlap=4)
+        q = np.array([0, 1./12., 1./3., 1./5., 1./3., 1./5., 1./3., 1./5.,
+                      1./6.])
+        assert_allclose(p, q, atol=1e-12)
+
+    def test_bad_noverlap(self):
+        assert_raises(ValueError, welch, np.zeros(4), 1, 'hann', 2, 7)
+
+    def test_nfft_too_short(self):
+        assert_raises(ValueError, welch, np.ones(12), nfft=3, nperseg=4)
+
+    def test_real_onesided_even_32(self):
+        x = np.zeros(16, 'f')
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=8)
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+                      0.11111111], 'f')
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+        assert_(p.dtype == q.dtype)
+
+    def test_real_onesided_odd_32(self):
+        x = np.zeros(16, 'f')
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=9)
+        assert_allclose(f, np.arange(5.0)/9.0)
+        q = np.array([0.12477458, 0.23430935, 0.17072113, 0.17072116,
+                      0.17072113], 'f')
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+        assert_(p.dtype == q.dtype)
+
+    def test_real_twosided_32(self):
+        x = np.zeros(16, 'f')
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.08333333, 0.07638889, 0.11111111,
+                      0.11111111, 0.11111111, 0.11111111, 0.11111111,
+                      0.07638889], 'f')
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+        assert_(p.dtype == q.dtype)
+
+    def test_complex_32(self):
+        x = np.zeros(16, 'F')
+        x[0] = 1.0 + 2.0j
+        x[8] = 1.0 + 2.0j
+        f, p = welch(x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.41666666, 0.38194442, 0.55555552, 0.55555552,
+                      0.55555558, 0.55555552, 0.55555552, 0.38194442], 'f')
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+        assert_(p.dtype == q.dtype,
+                f'dtype mismatch, {p.dtype}, {q.dtype}')
+
+    def test_padded_freqs(self):
+        x = np.zeros(12)
+
+        nfft = 24
+        f = fftfreq(nfft, 1.0)[:nfft//2+1]
+        f[-1] *= -1
+        fodd, _ = welch(x, nperseg=5, nfft=nfft)
+        feven, _ = welch(x, nperseg=6, nfft=nfft)
+        assert_allclose(f, fodd)
+        assert_allclose(f, feven)
+
+        nfft = 25
+        f = fftfreq(nfft, 1.0)[:(nfft + 1)//2]
+        fodd, _ = welch(x, nperseg=5, nfft=nfft)
+        feven, _ = welch(x, nperseg=6, nfft=nfft)
+        assert_allclose(f, fodd)
+        assert_allclose(f, feven)
+
+    def test_window_correction(self):
+        A = 20
+        fs = 1e4
+        nperseg = int(fs//10)
+        fsig = 300
+        ii = int(fsig*nperseg//fs)  # Freq index of fsig
+
+        tt = np.arange(fs)/fs
+        x = A*np.sin(2*np.pi*fsig*tt)
+
+        for window in ['hann', 'bartlett', ('tukey', 0.1), 'flattop']:
+            _, p_spec = welch(x, fs=fs, nperseg=nperseg, window=window,
+                              scaling='spectrum')
+            freq, p_dens = welch(x, fs=fs, nperseg=nperseg, window=window,
+                                 scaling='density')
+
+            # Check peak height at signal frequency for 'spectrum'
+            assert_allclose(p_spec[ii], A**2/2.0)
+            # Check integrated spectrum RMS for 'density'
+            assert_allclose(np.sqrt(trapezoid(p_dens, freq)), A*np.sqrt(2)/2,
+                            rtol=1e-3)
+
+    def test_axis_rolling(self):
+        np.random.seed(1234)
+
+        x_flat = np.random.randn(1024)
+        _, p_flat = welch(x_flat)
+
+        for a in range(3):
+            newshape = [1,]*3
+            newshape[a] = -1
+            x = x_flat.reshape(newshape)
+
+            _, p_plus = welch(x, axis=a)  # Positive axis index
+            _, p_minus = welch(x, axis=a-x.ndim)  # Negative axis index
+
+            assert_equal(p_flat, p_plus.squeeze(), err_msg=a)
+            assert_equal(p_flat, p_minus.squeeze(), err_msg=a-x.ndim)
+
+    def test_average(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = welch(x, nperseg=8, average='median')
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([.1, .05, 0., 1.54074396e-33, 0.])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+        assert_raises(ValueError, welch, x, nperseg=8,
+                      average='unrecognised-average')
+
+
+class TestCSD:
+    def test_pad_shorter_x(self):
+        x = np.zeros(8)
+        y = np.zeros(12)
+
+        f = np.linspace(0, 0.5, 7)
+        c = np.zeros(7,dtype=np.complex128)
+        f1, c1 = csd(x, y, nperseg=12)
+
+        assert_allclose(f, f1)
+        assert_allclose(c, c1)
+
+    def test_pad_shorter_y(self):
+        x = np.zeros(12)
+        y = np.zeros(8)
+
+        f = np.linspace(0, 0.5, 7)
+        c = np.zeros(7,dtype=np.complex128)
+        f1, c1 = csd(x, y, nperseg=12)
+
+        assert_allclose(f, f1)
+        assert_allclose(c, c1)
+
+    def test_real_onesided_even(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=8)
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+                      0.11111111])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_real_onesided_odd(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=9)
+        assert_allclose(f, np.arange(5.0)/9.0)
+        q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113,
+                      0.17072113])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_real_twosided(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111,
+                      0.11111111, 0.11111111, 0.11111111, 0.07638889])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_real_spectrum(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=8, scaling='spectrum')
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([0.015625, 0.02864583, 0.04166667, 0.04166667,
+                      0.02083333])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_integer_onesided_even(self):
+        x = np.zeros(16, dtype=int)
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=8)
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+                      0.11111111])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_integer_onesided_odd(self):
+        x = np.zeros(16, dtype=int)
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=9)
+        assert_allclose(f, np.arange(5.0)/9.0)
+        q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113,
+                      0.17072113])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_integer_twosided(self):
+        x = np.zeros(16, dtype=int)
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111,
+                      0.11111111, 0.11111111, 0.11111111, 0.07638889])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_complex(self):
+        x = np.zeros(16, np.complex128)
+        x[0] = 1.0 + 2.0j
+        x[8] = 1.0 + 2.0j
+        f, p = csd(x, x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.41666667, 0.38194444, 0.55555556, 0.55555556,
+                      0.55555556, 0.55555556, 0.55555556, 0.38194444])
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+    def test_unk_scaling(self):
+        assert_raises(ValueError, csd, np.zeros(4, np.complex128),
+                      np.ones(4, np.complex128), scaling='foo', nperseg=4)
+
+    def test_detrend_linear(self):
+        x = np.arange(10, dtype=np.float64) + 0.04
+        f, p = csd(x, x, nperseg=10, detrend='linear')
+        assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+    def test_no_detrending(self):
+        x = np.arange(10, dtype=np.float64) + 0.04
+        f1, p1 = csd(x, x, nperseg=10, detrend=False)
+        f2, p2 = csd(x, x, nperseg=10, detrend=lambda x: x)
+        assert_allclose(f1, f2, atol=1e-15)
+        assert_allclose(p1, p2, atol=1e-15)
+
+    def test_detrend_external(self):
+        x = np.arange(10, dtype=np.float64) + 0.04
+        f, p = csd(x, x, nperseg=10,
+                   detrend=lambda seg: signal.detrend(seg, type='l'))
+        assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+    def test_detrend_external_nd_m1(self):
+        x = np.arange(40, dtype=np.float64) + 0.04
+        x = x.reshape((2,2,10))
+        f, p = csd(x, x, nperseg=10,
+                   detrend=lambda seg: signal.detrend(seg, type='l'))
+        assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+    def test_detrend_external_nd_0(self):
+        x = np.arange(20, dtype=np.float64) + 0.04
+        x = x.reshape((2,1,10))
+        x = np.moveaxis(x, 2, 0)
+        f, p = csd(x, x, nperseg=10, axis=0,
+                   detrend=lambda seg: signal.detrend(seg, axis=0, type='l'))
+        assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+    def test_nd_axis_m1(self):
+        x = np.arange(20, dtype=np.float64) + 0.04
+        x = x.reshape((2,1,10))
+        f, p = csd(x, x, nperseg=10)
+        assert_array_equal(p.shape, (2, 1, 6))
+        assert_allclose(p[0,0,:], p[1,0,:], atol=1e-13, rtol=1e-13)
+        f0, p0 = csd(x[0,0,:], x[0,0,:], nperseg=10)
+        assert_allclose(p0[np.newaxis,:], p[1,:], atol=1e-13, rtol=1e-13)
+
+    def test_nd_axis_0(self):
+        x = np.arange(20, dtype=np.float64) + 0.04
+        x = x.reshape((10,2,1))
+        f, p = csd(x, x, nperseg=10, axis=0)
+        assert_array_equal(p.shape, (6,2,1))
+        assert_allclose(p[:,0,0], p[:,1,0], atol=1e-13, rtol=1e-13)
+        f0, p0 = csd(x[:,0,0], x[:,0,0], nperseg=10)
+        assert_allclose(p0, p[:,1,0], atol=1e-13, rtol=1e-13)
+
+    def test_window_external(self):
+        x = np.zeros(16)
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, 10, 'hann', 8)
+        win = signal.get_window('hann', 8)
+        fe, pe = csd(x, x, 10, win, nperseg=None)
+        assert_array_almost_equal_nulp(p, pe)
+        assert_array_almost_equal_nulp(f, fe)
+        assert_array_equal(fe.shape, (5,))  # because win length used as nperseg
+        assert_array_equal(pe.shape, (5,))
+        assert_raises(ValueError, csd, x, x,
+                      10, win, nperseg=256)  # because nperseg != win.shape[-1]
+        win_err = signal.get_window('hann', 32)
+        assert_raises(ValueError, csd, x, x,
+              10, win_err, nperseg=None)  # because win longer than signal
+
+    def test_empty_input(self):
+        f, p = csd([],np.zeros(10))
+        assert_array_equal(f.shape, (0,))
+        assert_array_equal(p.shape, (0,))
+
+        f, p = csd(np.zeros(10),[])
+        assert_array_equal(f.shape, (0,))
+        assert_array_equal(p.shape, (0,))
+
+        for shape in [(0,), (3,0), (0,5,2)]:
+            f, p = csd(np.empty(shape), np.empty(shape))
+            assert_array_equal(f.shape, shape)
+            assert_array_equal(p.shape, shape)
+
+        f, p = csd(np.ones(10), np.empty((5,0)))
+        assert_array_equal(f.shape, (5,0))
+        assert_array_equal(p.shape, (5,0))
+
+        f, p = csd(np.empty((5,0)), np.ones(10))
+        assert_array_equal(f.shape, (5,0))
+        assert_array_equal(p.shape, (5,0))
+
+    def test_empty_input_other_axis(self):
+        for shape in [(3,0), (0,5,2)]:
+            f, p = csd(np.empty(shape), np.empty(shape), axis=1)
+            assert_array_equal(f.shape, shape)
+            assert_array_equal(p.shape, shape)
+
+        f, p = csd(np.empty((10,10,3)), np.zeros((10,0,1)), axis=1)
+        assert_array_equal(f.shape, (10,0,3))
+        assert_array_equal(p.shape, (10,0,3))
+
+        f, p = csd(np.empty((10,0,1)), np.zeros((10,10,3)), axis=1)
+        assert_array_equal(f.shape, (10,0,3))
+        assert_array_equal(p.shape, (10,0,3))
+
+    def test_short_data(self):
+        x = np.zeros(8)
+        x[0] = 1
+
+        #for string-like window, input signal length < nperseg value gives
+        #UserWarning, sets nperseg to x.shape[-1]
+        with suppress_warnings() as sup:
+            msg = "nperseg = 256 is greater than input length  = 8, using nperseg = 8"
+            sup.filter(UserWarning, msg)
+            f, p = csd(x, x, window='hann')  # default nperseg
+            f1, p1 = csd(x, x, window='hann', nperseg=256)  # user-specified nperseg
+        f2, p2 = csd(x, x, nperseg=8)  # valid nperseg, doesn't give warning
+        assert_allclose(f, f2)
+        assert_allclose(p, p2)
+        assert_allclose(f1, f2)
+        assert_allclose(p1, p2)
+
+    def test_window_long_or_nd(self):
+        assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1,
+                      np.array([1,1,1,1,1]))
+        assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1,
+                      np.arange(6).reshape((2,3)))
+
+    def test_nondefault_noverlap(self):
+        x = np.zeros(64)
+        x[::8] = 1
+        f, p = csd(x, x, nperseg=16, noverlap=4)
+        q = np.array([0, 1./12., 1./3., 1./5., 1./3., 1./5., 1./3., 1./5.,
+                      1./6.])
+        assert_allclose(p, q, atol=1e-12)
+
+    def test_bad_noverlap(self):
+        assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1, 'hann',
+                      2, 7)
+
+    def test_nfft_too_short(self):
+        assert_raises(ValueError, csd, np.ones(12), np.zeros(12), nfft=3,
+                      nperseg=4)
+
+    def test_real_onesided_even_32(self):
+        x = np.zeros(16, 'f')
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=8)
+        assert_allclose(f, np.linspace(0, 0.5, 5))
+        q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+                      0.11111111], 'f')
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+        assert_(p.dtype == q.dtype)
+
+    def test_real_onesided_odd_32(self):
+        x = np.zeros(16, 'f')
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=9)
+        assert_allclose(f, np.arange(5.0)/9.0)
+        q = np.array([0.12477458, 0.23430935, 0.17072113, 0.17072116,
+                      0.17072113], 'f')
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+        assert_(p.dtype == q.dtype)
+
+    def test_real_twosided_32(self):
+        x = np.zeros(16, 'f')
+        x[0] = 1
+        x[8] = 1
+        f, p = csd(x, x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.08333333, 0.07638889, 0.11111111,
+                      0.11111111, 0.11111111, 0.11111111, 0.11111111,
+                      0.07638889], 'f')
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+        assert_(p.dtype == q.dtype)
+
+    def test_complex_32(self):
+        x = np.zeros(16, 'F')
+        x[0] = 1.0 + 2.0j
+        x[8] = 1.0 + 2.0j
+        f, p = csd(x, x, nperseg=8, return_onesided=False)
+        assert_allclose(f, fftfreq(8, 1.0))
+        q = np.array([0.41666666, 0.38194442, 0.55555552, 0.55555552,
+                      0.55555558, 0.55555552, 0.55555552, 0.38194442], 'f')
+        assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+        assert_(p.dtype == q.dtype,
+                f'dtype mismatch, {p.dtype}, {q.dtype}')
+
+    def test_padded_freqs(self):
+        x = np.zeros(12)
+        y = np.ones(12)
+
+        nfft = 24
+        f = fftfreq(nfft, 1.0)[:nfft//2+1]
+        f[-1] *= -1
+        fodd, _ = csd(x, y, nperseg=5, nfft=nfft)
+        feven, _ = csd(x, y, nperseg=6, nfft=nfft)
+        assert_allclose(f, fodd)
+        assert_allclose(f, feven)
+
+        nfft = 25
+        f = fftfreq(nfft, 1.0)[:(nfft + 1)//2]
+        fodd, _ = csd(x, y, nperseg=5, nfft=nfft)
+        feven, _ = csd(x, y, nperseg=6, nfft=nfft)
+        assert_allclose(f, fodd)
+        assert_allclose(f, feven)
+
+    def test_copied_data(self):
+        x = np.random.randn(64)
+        y = x.copy()
+
+        _, p_same = csd(x, x, nperseg=8, average='mean',
+                        return_onesided=False)
+        _, p_copied = csd(x, y, nperseg=8, average='mean',
+                          return_onesided=False)
+        assert_allclose(p_same, p_copied)
+
+        _, p_same = csd(x, x, nperseg=8, average='median',
+                        return_onesided=False)
+        _, p_copied = csd(x, y, nperseg=8, average='median',
+                          return_onesided=False)
+        assert_allclose(p_same, p_copied)
+
+
+class TestCoherence:
+    def test_identical_input(self):
+        x = np.random.randn(20)
+        y = np.copy(x)  # So `y is x` -> False
+
+        f = np.linspace(0, 0.5, 6)
+        C = np.ones(6)
+        f1, C1 = coherence(x, y, nperseg=10)
+
+        assert_allclose(f, f1)
+        assert_allclose(C, C1)
+
+    def test_phase_shifted_input(self):
+        x = np.random.randn(20)
+        y = -x
+
+        f = np.linspace(0, 0.5, 6)
+        C = np.ones(6)
+        f1, C1 = coherence(x, y, nperseg=10)
+
+        assert_allclose(f, f1)
+        assert_allclose(C, C1)
+
+
+class TestSpectrogram:
+    def test_average_all_segments(self):
+        x = np.random.randn(1024)
+
+        fs = 1.0
+        window = ('tukey', 0.25)
+        nperseg = 16
+        noverlap = 2
+
+        f, _, P = spectrogram(x, fs, window, nperseg, noverlap)
+        fw, Pw = welch(x, fs, window, nperseg, noverlap)
+        assert_allclose(f, fw)
+        assert_allclose(np.mean(P, axis=-1), Pw)
+
+    def test_window_external(self):
+        x = np.random.randn(1024)
+
+        fs = 1.0
+        window = ('tukey', 0.25)
+        nperseg = 16
+        noverlap = 2
+        f, _, P = spectrogram(x, fs, window, nperseg, noverlap)
+
+        win = signal.get_window(('tukey', 0.25), 16)
+        fe, _, Pe = spectrogram(x, fs, win, nperseg=None, noverlap=2)
+        assert_array_equal(fe.shape, (9,))  # because win length used as nperseg
+        assert_array_equal(Pe.shape, (9,73))
+        assert_raises(ValueError, spectrogram, x,
+                      fs, win, nperseg=8)  # because nperseg != win.shape[-1]
+        win_err = signal.get_window(('tukey', 0.25), 2048)
+        assert_raises(ValueError, spectrogram, x,
+                      fs, win_err, nperseg=None)  # win longer than signal
+
+    def test_short_data(self):
+        x = np.random.randn(1024)
+        fs = 1.0
+
+        #for string-like window, input signal length < nperseg value gives
+        #UserWarning, sets nperseg to x.shape[-1]
+        f, _, p = spectrogram(x, fs, window=('tukey',0.25))  # default nperseg
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "nperseg = 1025 is greater than input length  = 1024, "
+                       "using nperseg = 1024",)
+            f1, _, p1 = spectrogram(x, fs, window=('tukey',0.25),
+                                    nperseg=1025)  # user-specified nperseg
+        f2, _, p2 = spectrogram(x, fs, nperseg=256)  # to compare w/default
+        f3, _, p3 = spectrogram(x, fs, nperseg=1024)  # compare w/user-spec'd
+        assert_allclose(f, f2)
+        assert_allclose(p, p2)
+        assert_allclose(f1, f3)
+        assert_allclose(p1, p3)
+
+class TestLombscargle:
+    def test_frequency(self):
+        """Test if frequency location of peak corresponds to frequency of
+        generated input signal.
+        """
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0.5 * np.pi
+        nin = 100
+        nout = 1000
+        p = 0.7  # Fraction of points to select
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a sine wave for the selected times
+        y = ampl * np.sin(w*t + phi)
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0.01, 10., nout)
+
+        # Calculate Lomb-Scargle periodogram
+        P = lombscargle(t, y, f)
+
+        # Check if difference between found frequency maximum and input
+        # frequency is less than accuracy
+        delta = f[1] - f[0]
+        assert(w - f[np.argmax(P)] < (delta/2.))
+
+        # also, check that it works with weights
+        P = lombscargle(t, y, f, weights=np.ones_like(t, dtype=f.dtype))
+
+        # Check if difference between found frequency maximum and input
+        # frequency is less than accuracy
+        delta = f[1] - f[0]
+        assert(w - f[np.argmax(P)] < (delta/2.))
+
+
+    def test_amplitude(self):
+        # Test if height of peak in unnormalized Lomb-Scargle periodogram
+        # corresponds to amplitude of the generated input signal.
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0.5 * np.pi
+        nin = 1000
+        nout = 1000
+        p = 0.7  # Fraction of points to select
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a sine wave for the selected times
+        y = ampl * np.sin(w*t + phi)
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0.01, 10., nout)
+
+        # Calculate Lomb-Scargle periodogram
+        pgram = lombscargle(t, y, f)
+
+        # convert to the amplitude
+        pgram = np.sqrt(4.0 * pgram / t.shape[0])
+
+        # Check if amplitude is correct (this will not exactly match, due to
+        # numerical differences when data is removed)
+        assert_allclose(pgram[f==w], ampl, rtol=5e-2)
+
+    def test_precenter(self):
+        # Test if precenter gives the same result as manually precentering
+        # (for a very simple offset)
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0.5 * np.pi
+        nin = 100
+        nout = 1000
+        p = 0.7  # Fraction of points to select
+        offset = 0.15  # Offset to be subtracted in pre-centering
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a sine wave for the selected times
+        y = ampl * np.sin(w*t + phi) + offset
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0.01, 10., nout)
+
+        # Calculate Lomb-Scargle periodogram
+        pgram = lombscargle(t, y, f, precenter=True)
+        pgram2 = lombscargle(t, y - y.mean(), f, precenter=False)
+
+        # check if centering worked
+        assert_allclose(pgram, pgram2)
+
+        # do this again, but with floating_mean=True
+
+        # Calculate Lomb-Scargle periodogram
+        pgram = lombscargle(t, y, f, precenter=True, floating_mean=True)
+        pgram2 = lombscargle(t, y - y.mean(), f, precenter=False, floating_mean=True)
+
+        # check if centering worked
+        assert_allclose(pgram, pgram2)
+
+    def test_normalize(self):
+        # Test normalize option of Lomb-Scarge.
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0.5 * np.pi
+        nin = 100
+        nout = 1000
+        p = 0.7  # Fraction of points to select
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a sine wave for the selected times
+        y = ampl * np.sin(w*t + phi)
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0.01, 10., nout)
+
+        # Calculate Lomb-Scargle periodogram
+        pgram = lombscargle(t, y, f)
+        pgram2 = lombscargle(t, y, f, normalize=True)
+
+        # Calculate the scale to convert from unnormalized to normalized
+        weights = np.ones_like(t)/float(t.shape[0])
+        YY_hat = (weights * y * y).sum()
+        YY = YY_hat  # correct formula for floating_mean=False
+        scale_to_use = 2/(YY*t.shape[0])
+
+        # check if normalization works as expected
+        assert_allclose(pgram * scale_to_use, pgram2)
+        assert_allclose(np.max(pgram2), 1.0)
+
+    def test_wrong_shape(self):
+
+        # different length t and y
+        t = np.linspace(0, 1, 1)
+        y = np.linspace(0, 1, 2)
+        f = np.linspace(0, 1, 3) + 0.1
+        assert_raises(ValueError, lombscargle, t, y, f)
+
+        # t is 2D, with both axes length > 1
+        t = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1)
+        y = np.linspace(0, 1, 2)
+        f = np.linspace(0, 1, 3) + 0.1
+        assert_raises(ValueError, lombscargle, t, y, f)
+
+        # y is 2D, with both axes length > 1
+        t = np.linspace(0, 1, 2)
+        y = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1)
+        f = np.linspace(0, 1, 3) + 0.1
+        assert_raises(ValueError, lombscargle, t, y, f)
+
+        # f is 2D, with both axes length > 1
+        t = np.linspace(0, 1, 2)
+        y = np.linspace(0, 1, 2)
+        f = np.repeat(np.expand_dims(np.linspace(0, 1, 3), 1) + 0.1, 2, axis=1)
+        assert_raises(ValueError, lombscargle, t, y, f)
+
+        # weights is 2D, with both axes length > 1
+        t = np.linspace(0, 1, 2)
+        y = np.linspace(0, 1, 2)
+        f = np.linspace(0, 1, 3) + 0.1
+        weights = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1)
+        assert_raises(ValueError, lombscargle, t, y, f, weights=weights)
+
+    def test_lombscargle_atan_vs_atan2(self):
+        # https://github.com/scipy/scipy/issues/3787
+        # This raised a ZeroDivisionError.
+        t = np.linspace(0, 10, 1000, endpoint=False)
+        y = np.sin(4*t)
+        f = np.linspace(0, 50, 500, endpoint=False) + 0.1
+        lombscargle(t, y, f*2*np.pi)
+
+    def test_wrong_shape_weights(self):
+        # Weights must be the same shape as t
+
+        t = np.linspace(0, 1, 1)
+        y = np.linspace(0, 1, 1)
+        f = np.linspace(0, 1, 3) + 0.1
+        weights = np.linspace(1, 2, 2)
+        assert_raises(ValueError, lombscargle, t, y, f, weights=weights)
+
+    def test_zero_division_weights(self):
+        # Weights cannot sum to 0
+
+        t = np.zeros(1)
+        y = np.zeros(1)
+        f = np.ones(1)
+        weights = np.zeros(1)
+        assert_raises(ValueError, lombscargle, t, y, f, weights=weights)
+
+    def test_normalize_parameter(self):
+        # Test the validity of the normalize parameter input
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0
+        nin = 100
+        nout = 1000
+        p = 0.7  # Fraction of points to select
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a sine wave for the selected times
+        y = ampl * np.sin(w*t + phi)
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0.01, 10., nout)
+
+        # check each of the valid inputs
+        pgram_false = lombscargle(t, y, f, normalize=False)
+        pgram_true = lombscargle(t, y, f, normalize=True)
+        pgram_power = lombscargle(t, y, f, normalize='power')
+        pgram_norm = lombscargle(t, y, f, normalize='normalize')
+        pgram_amp = lombscargle(t, y, f, normalize='amplitude')
+
+        # validate the results that should be the same
+        assert_allclose(pgram_false, pgram_power)
+        assert_allclose(pgram_true, pgram_norm)
+
+        # validate that the power and norm outputs are proper wrt each other
+        weights = np.ones_like(y)/float(y.shape[0])
+        YY_hat = (weights * y * y).sum()
+        YY = YY_hat  # correct formula for floating_mean=False
+        assert_allclose(pgram_power * 2.0 / (float(t.shape[0]) * YY), pgram_norm)
+
+        # validate that the amp output is correct for the given input
+        f_i = np.where(f==w)[0][0]
+        assert_allclose(np.abs(pgram_amp[f_i]), ampl)
+
+        # check invalid inputs
+        #  1) a string that is not allowed
+        assert_raises(ValueError, lombscargle, t, y, f, normalize='lomb')
+        #  2) something besides a bool or str
+        assert_raises(ValueError, lombscargle, t, y, f, normalize=2)
+
+    def test_offset_removal(self):
+        # Verify that the amplitude is the same, even with an offset
+        # must use floating_mean=True, otherwise it will not remove an offset
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0.5 * np.pi
+        nin = 100
+        nout = 1000
+        p = 0.7  # Fraction of points to select
+        offset = 2.15  # Large offset
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a sine wave for the selected times
+        y = ampl * np.sin(w*t + phi)
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0.01, 10., nout)
+
+        # Calculate Lomb-Scargle periodogram
+        pgram = lombscargle(t, y, f, floating_mean=True)
+        pgram_offset = lombscargle(t, y + offset, f, floating_mean=True)
+
+        # check if offset removal works as expected
+        assert_allclose(pgram, pgram_offset)
+
+    def test_floating_mean_false(self):
+        # Verify that when disabling the floating_mean, the calculations are correct
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0
+        nin = 1000
+        nout = 1000
+        p = 0.7  # Fraction of points to select
+        offset = 2  # Large offset
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a cos wave for the selected times
+        y = ampl * np.cos(w*t + phi)
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0.01, 10., nout)
+
+        # Calculate Lomb-Scargle periodogram
+        pgram = lombscargle(t, y, f, normalize=True, floating_mean=False)
+        pgram_offset = lombscargle(t, y + offset, f, normalize=True,
+                                   floating_mean=False)
+
+        # check if disabling floating_mean works as expected
+        # nearly-zero for no offset, exact value will change based on seed
+        assert(pgram[0] < 0.01)
+        # significant value with offset, exact value will change based on seed
+        assert(pgram_offset[0] > 0.5)
+
+    def test_amplitude_is_correct(self):
+        # Verify that the amplitude is correct (when normalize='amplitude')
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0.12
+        nin = 100
+        nout = 1000
+        p = 0.7  # Fraction of points to select
+        offset = 2.15  # Large offset
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a sine wave for the selected times
+        y = ampl * np.cos(w*t + phi) + offset
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0.01, 10., nout)
+
+        # Get the index of where the exact result should be
+        f_indx = np.where(f==w)[0][0]
+
+        # Calculate Lomb-Scargle periodogram (amplitude + phase)
+        pgram = lombscargle(t, y, f, normalize='amplitude', floating_mean=True)
+
+        # Check if amplitude is correct
+        assert_allclose(np.abs(pgram[f_indx]), ampl)
+
+        # Check if phase is correct
+        # (phase angle is the negative of the phase offset)
+        assert_allclose(-np.angle(pgram[f_indx]), phi)
+
+    def test_negative_weight(self):
+        # Test that a negative weight produces an error
+
+        t = np.zeros(1)
+        y = np.zeros(1)
+        f = np.ones(1)
+        weights = -np.ones(1)
+        assert_raises(ValueError, lombscargle, t, y, f, weights=weights)
+
+    def test_list_input(self):
+        # Test that input can be passsed in as lists and with a numerical issue
+        # https://github.com/scipy/scipy/issues/8787
+
+        t = [1.98201652e+09, 1.98201752e+09, 1.98201852e+09, 1.98201952e+09,
+            1.98202052e+09, 1.98202152e+09, 1.98202252e+09, 1.98202352e+09,
+            1.98202452e+09, 1.98202552e+09, 1.98202652e+09, 1.98202752e+09,
+            1.98202852e+09, 1.98202952e+09, 1.98203052e+09, 1.98203152e+09,
+            1.98203252e+09, 1.98203352e+09, 1.98203452e+09, 1.98203552e+09,
+            1.98205452e+09, 1.98205552e+09, 1.98205652e+09, 1.98205752e+09,
+            1.98205852e+09, 1.98205952e+09, 1.98206052e+09, 1.98206152e+09,
+            1.98206252e+09, 1.98206352e+09, 1.98206452e+09, 1.98206552e+09,
+            1.98206652e+09, 1.98206752e+09, 1.98206852e+09, 1.98206952e+09,
+            1.98207052e+09, 1.98207152e+09, 1.98207252e+09, 1.98207352e+09,
+            1.98209652e+09, 1.98209752e+09, 1.98209852e+09, 1.98209952e+09,
+            1.98210052e+09, 1.98210152e+09, 1.98210252e+09, 1.98210352e+09,
+            1.98210452e+09, 1.98210552e+09, 1.98210652e+09, 1.98210752e+09,
+            1.98210852e+09, 1.98210952e+09, 1.98211052e+09, 1.98211152e+09,
+            1.98211252e+09, 1.98211352e+09, 1.98211452e+09, 1.98211552e+09,
+            1.98217252e+09, 1.98217352e+09, 1.98217452e+09, 1.98217552e+09,
+            1.98217652e+09, 1.98217752e+09, 1.98217852e+09, 1.98217952e+09,
+            1.98218052e+09, 1.98218152e+09, 1.98218252e+09, 1.98218352e+09,
+            1.98218452e+09, 1.98218552e+09, 1.98218652e+09, 1.98218752e+09,
+            1.98218852e+09, 1.98218952e+09, 1.98219052e+09, 1.98219152e+09,
+            1.98219352e+09, 1.98219452e+09, 1.98219552e+09, 1.98219652e+09,
+            1.98219752e+09, 1.98219852e+09, 1.98219952e+09, 1.98220052e+09,
+            1.98220152e+09, 1.98220252e+09, 1.98220352e+09, 1.98220452e+09,
+            1.98220552e+09, 1.98220652e+09, 1.98220752e+09, 1.98220852e+09,
+            1.98220952e+09, 1.98221052e+09, 1.98221152e+09, 1.98221252e+09,
+            1.98222752e+09, 1.98222852e+09, 1.98222952e+09, 1.98223052e+09,
+            1.98223152e+09, 1.98223252e+09, 1.98223352e+09, 1.98223452e+09,
+            1.98223552e+09, 1.98223652e+09, 1.98223752e+09, 1.98223852e+09,
+            1.98223952e+09, 1.98224052e+09, 1.98224152e+09, 1.98224252e+09,
+            1.98224352e+09, 1.98224452e+09, 1.98224552e+09, 1.98224652e+09,
+            1.98224752e+09]
+        y = [2.97600000e+03, 3.18200000e+03, 3.74900000e+03, 4.53500000e+03,
+            5.43300000e+03, 6.38000000e+03, 7.34000000e+03, 8.29200000e+03,
+            9.21900000e+03, 1.01120000e+04, 1.09620000e+04, 1.17600000e+04,
+            1.25010000e+04, 1.31790000e+04, 1.37900000e+04, 1.43290000e+04,
+            1.47940000e+04, 1.51800000e+04, 1.54870000e+04, 1.57110000e+04,
+            5.74200000e+03, 4.82300000e+03, 3.99100000e+03, 3.33600000e+03,
+            2.99600000e+03, 3.08400000e+03, 3.56700000e+03, 4.30700000e+03,
+            5.18200000e+03, 6.11900000e+03, 7.07900000e+03, 8.03400000e+03,
+            8.97000000e+03, 9.87300000e+03, 1.07350000e+04, 1.15480000e+04,
+            1.23050000e+04, 1.30010000e+04, 1.36300000e+04, 1.41890000e+04,
+            6.00000000e+03, 5.06800000e+03, 4.20500000e+03, 3.49000000e+03,
+            3.04900000e+03, 3.01600000e+03, 3.40400000e+03, 4.08800000e+03,
+            4.93500000e+03, 5.86000000e+03, 6.81700000e+03, 7.77500000e+03,
+            8.71800000e+03, 9.63100000e+03, 1.05050000e+04, 1.13320000e+04,
+            1.21050000e+04, 1.28170000e+04, 1.34660000e+04, 1.40440000e+04,
+            1.32730000e+04, 1.26040000e+04, 1.18720000e+04, 1.10820000e+04,
+            1.02400000e+04, 9.35300000e+03, 8.43000000e+03, 7.48100000e+03,
+            6.52100000e+03, 5.57000000e+03, 4.66200000e+03, 3.85400000e+03,
+            3.24600000e+03, 2.97900000e+03, 3.14700000e+03, 3.68800000e+03,
+            4.45900000e+03, 5.35000000e+03, 6.29400000e+03, 7.25400000e+03,
+            9.13800000e+03, 1.00340000e+04, 1.08880000e+04, 1.16910000e+04,
+            1.24370000e+04, 1.31210000e+04, 1.37380000e+04, 1.42840000e+04,
+            1.47550000e+04, 1.51490000e+04, 1.54630000e+04, 1.56950000e+04,
+            1.58430000e+04, 1.59070000e+04, 1.58860000e+04, 1.57800000e+04,
+            1.55910000e+04, 1.53190000e+04, 1.49650000e+04, 1.45330000e+04,
+            3.01000000e+03, 3.05900000e+03, 3.51200000e+03, 4.23400000e+03,
+            5.10000000e+03, 6.03400000e+03, 6.99300000e+03, 7.95000000e+03,
+            8.88800000e+03, 9.79400000e+03, 1.06600000e+04, 1.14770000e+04,
+            1.22400000e+04, 1.29410000e+04, 1.35770000e+04, 1.41430000e+04,
+            1.46350000e+04, 1.50500000e+04, 1.53850000e+04, 1.56400000e+04,
+            1.58110000e+04]
+
+        periods = np.linspace(400, 120, 1000)
+        angular_freq = 2 * np.pi / periods
+
+        lombscargle(t, y, angular_freq, precenter=True, normalize=True)
+
+    def test_zero_freq(self):
+        # Verify that function works when freqs includes 0
+        # The value at f=0 will depend on the seed
+
+        # Input parameters
+        ampl = 2.
+        w = 1.
+        phi = 0.12
+        nin = 100
+        nout = 1001
+        p = 0.7  # Fraction of points to select
+        offset = 0
+
+        # Randomly select a fraction of an array with timesteps
+        rng = np.random.RandomState(2353425)
+        r = rng.rand(nin)
+        t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+        # Plot a sine wave for the selected times
+        y = ampl * np.cos(w*t + phi) + offset
+
+        # Define the array of frequencies for which to compute the periodogram
+        f = np.linspace(0, 10., nout)
+
+        # Calculate Lomb-Scargle periodogram
+        pgram = lombscargle(t, y, f, normalize=True, floating_mean=True)
+
+        # exact value will change based on seed
+        # testing to make sure it is very small
+        assert(pgram[0] < 1e-4)
+
+    def test_simple_div_zero(self):
+        # these are bare-minimum examples that would, without the eps adjustments,
+        # cause division-by-zero errors
+
+        # first, test with example that will cause first SS sum to be 0.0
+        t = [t + 1 for t in range(0, 32)]
+        y = np.ones(len(t))
+        freqs = [2.0*np.pi] * 2  # must have 2+ elements
+        lombscargle(t, y, freqs)
+
+        # second, test with example that will cause first CC sum to be 0.0
+        t = [t*4 + 1 for t in range(0, 32)]
+        y = np.ones(len(t))
+        freqs = [np.pi/2.0] * 2  # must have 2+ elements
+
+        lombscargle(t, y, freqs)
+
+
+class TestSTFT:
+    @pytest.mark.thread_unsafe
+    def test_input_validation(self):
+
+        def chk_VE(match):
+            """Assert for a ValueError matching regexp `match`.
+
+            This little wrapper allows a more concise code layout.
+            """
+            return pytest.raises(ValueError, match=match)
+
+        # Checks for check_COLA():
+        with chk_VE('nperseg must be a positive integer'):
+            check_COLA('hann', -10, 0)
+        with chk_VE('noverlap must be less than nperseg.'):
+            check_COLA('hann', 10, 20)
+        with chk_VE('window must be 1-D'):
+            check_COLA(np.ones((2, 2)), 10, 0)
+        with chk_VE('window must have length of nperseg'):
+            check_COLA(np.ones(20), 10, 0)
+
+        # Checks for check_NOLA():
+        with chk_VE('nperseg must be a positive integer'):
+            check_NOLA('hann', -10, 0)
+        with chk_VE('noverlap must be less than nperseg'):
+            check_NOLA('hann', 10, 20)
+        with chk_VE('window must be 1-D'):
+            check_NOLA(np.ones((2, 2)), 10, 0)
+        with chk_VE('window must have length of nperseg'):
+            check_NOLA(np.ones(20), 10, 0)
+        with chk_VE('noverlap must be a nonnegative integer'):
+            check_NOLA('hann', 64, -32)
+
+        x = np.zeros(1024)
+        z = stft(x)[2]
+
+        # Checks for stft():
+        with chk_VE('window must be 1-D'):
+            stft(x, window=np.ones((2, 2)))
+        with chk_VE('value specified for nperseg is different ' +
+                    'from length of window'):
+            stft(x, window=np.ones(10), nperseg=256)
+        with chk_VE('nperseg must be a positive integer'):
+            stft(x, nperseg=-256)
+        with chk_VE('noverlap must be less than nperseg.'):
+            stft(x, nperseg=256, noverlap=1024)
+        with chk_VE('nfft must be greater than or equal to nperseg.'):
+            stft(x, nperseg=256, nfft=8)
+
+        # Checks for istft():
+        with chk_VE('Input stft must be at least 2d!'):
+            istft(x)
+        with chk_VE('window must be 1-D'):
+            istft(z, window=np.ones((2, 2)))
+        with chk_VE('window must have length of 256'):
+            istft(z, window=np.ones(10), nperseg=256)
+        with chk_VE('nperseg must be a positive integer'):
+            istft(z, nperseg=-256)
+        with chk_VE('noverlap must be less than nperseg.'):
+            istft(z, nperseg=256, noverlap=1024)
+        with chk_VE('nfft must be greater than or equal to nperseg.'):
+            istft(z, nperseg=256, nfft=8)
+        with pytest.warns(UserWarning, match="NOLA condition failed, " +
+                          "STFT may not be invertible"):
+            istft(z, nperseg=256, noverlap=0, window='hann')
+        with chk_VE('Must specify differing time and frequency axes!'):
+            istft(z, time_axis=0, freq_axis=0)
+
+        # Checks for _spectral_helper():
+        with chk_VE("Unknown value for mode foo, must be one of: " +
+                    r"\{'psd', 'stft'\}"):
+            _spectral_helper(x, x, mode='foo')
+        with chk_VE("x and y must be equal if mode is 'stft'"):
+            _spectral_helper(x[:512], x[512:], mode='stft')
+        with chk_VE("Unknown boundary option 'foo', must be one of: " +
+                    r"\['even', 'odd', 'constant', 'zeros', None\]"):
+            _spectral_helper(x, x, boundary='foo')
+
+        scaling = "not_valid"
+        with chk_VE(fr"Parameter {scaling=} not in \['spectrum', 'psd'\]!"):
+            stft(x, scaling=scaling)
+        with chk_VE(fr"Parameter {scaling=} not in \['spectrum', 'psd'\]!"):
+            istft(z, scaling=scaling)
+
+    def test_check_COLA(self):
+        settings = [
+                    ('boxcar', 10, 0),
+                    ('boxcar', 10, 9),
+                    ('bartlett', 51, 26),
+                    ('hann', 256, 128),
+                    ('hann', 256, 192),
+                    ('blackman', 300, 200),
+                    (('tukey', 0.5), 256, 64),
+                    ('hann', 256, 255),
+                    ]
+
+        for setting in settings:
+            msg = '{}, {}, {}'.format(*setting)
+            assert_equal(True, check_COLA(*setting), err_msg=msg)
+
+    def test_check_NOLA(self):
+        settings_pass = [
+                    ('boxcar', 10, 0),
+                    ('boxcar', 10, 9),
+                    ('boxcar', 10, 7),
+                    ('bartlett', 51, 26),
+                    ('bartlett', 51, 10),
+                    ('hann', 256, 128),
+                    ('hann', 256, 192),
+                    ('hann', 256, 37),
+                    ('blackman', 300, 200),
+                    ('blackman', 300, 123),
+                    (('tukey', 0.5), 256, 64),
+                    (('tukey', 0.5), 256, 38),
+                    ('hann', 256, 255),
+                    ('hann', 256, 39),
+                    ]
+        for setting in settings_pass:
+            msg = '{}, {}, {}'.format(*setting)
+            assert_equal(True, check_NOLA(*setting), err_msg=msg)
+
+        w_fail = np.ones(16)
+        w_fail[::2] = 0
+        settings_fail = [
+                    (w_fail, len(w_fail), len(w_fail) // 2),
+                    ('hann', 64, 0),
+        ]
+        for setting in settings_fail:
+            msg = '{}, {}, {}'.format(*setting)
+            assert_equal(False, check_NOLA(*setting), err_msg=msg)
+
+    def test_average_all_segments(self):
+        rng = np.random.RandomState(1234)
+        x = rng.randn(1024)
+
+        fs = 1.0
+        window = 'hann'
+        nperseg = 16
+        noverlap = 8
+
+        # Compare twosided, because onesided welch doubles non-DC terms to
+        # account for power at negative frequencies. stft doesn't do this,
+        # because it breaks invertibility.
+        f, _, Z = stft(x, fs, window, nperseg, noverlap, padded=False,
+                       return_onesided=False, boundary=None)
+        fw, Pw = welch(x, fs, window, nperseg, noverlap, return_onesided=False,
+                       scaling='spectrum', detrend=False)
+
+        assert_allclose(f, fw)
+        assert_allclose(np.mean(np.abs(Z)**2, axis=-1), Pw)
+
+    def test_permute_axes(self):
+        rng = np.random.RandomState(1234)
+        x = rng.randn(1024)
+
+        fs = 1.0
+        window = 'hann'
+        nperseg = 16
+        noverlap = 8
+
+        f1, t1, Z1 = stft(x, fs, window, nperseg, noverlap)
+        f2, t2, Z2 = stft(x.reshape((-1, 1, 1)), fs, window, nperseg, noverlap,
+                          axis=0)
+
+        t3, x1 = istft(Z1, fs, window, nperseg, noverlap)
+        t4, x2 = istft(Z2.T, fs, window, nperseg, noverlap, time_axis=0,
+                       freq_axis=-1)
+
+        assert_allclose(f1, f2)
+        assert_allclose(t1, t2)
+        assert_allclose(t3, t4)
+        assert_allclose(Z1, Z2[:, 0, 0, :])
+        assert_allclose(x1, x2[:, 0, 0])
+
+    @pytest.mark.parametrize('scaling', ['spectrum', 'psd'])
+    def test_roundtrip_real(self, scaling):
+        rng = np.random.RandomState(1234)
+
+        settings = [
+                    ('boxcar', 100, 10, 0),           # Test no overlap
+                    ('boxcar', 100, 10, 9),           # Test high overlap
+                    ('bartlett', 101, 51, 26),        # Test odd nperseg
+                    ('hann', 1024, 256, 128),         # Test defaults
+                    (('tukey', 0.5), 1152, 256, 64),  # Test Tukey
+                    ('hann', 1024, 256, 255),         # Test overlapped hann
+                    ]
+
+        for window, N, nperseg, noverlap in settings:
+            t = np.arange(N)
+            x = 10*rng.randn(t.size)
+
+            _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+                            window=window, detrend=None, padded=False,
+                            scaling=scaling)
+
+            tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+                           window=window, scaling=scaling)
+
+            msg = f'{window}, {noverlap}'
+            assert_allclose(t, tr, err_msg=msg)
+            assert_allclose(x, xr, err_msg=msg)
+
+    @pytest.mark.thread_unsafe
+    def test_roundtrip_not_nola(self):
+        rng = np.random.RandomState(1234)
+
+        w_fail = np.ones(16)
+        w_fail[::2] = 0
+        settings = [
+                    (w_fail, 256, len(w_fail), len(w_fail) // 2),
+                    ('hann', 256, 64, 0),
+        ]
+
+        for window, N, nperseg, noverlap in settings:
+            msg = f'{window}, {N}, {nperseg}, {noverlap}'
+            assert not check_NOLA(window, nperseg, noverlap), msg
+
+            t = np.arange(N)
+            x = 10 * rng.randn(t.size)
+
+            _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+                            window=window, detrend=None, padded=True,
+                            boundary='zeros')
+            with pytest.warns(UserWarning, match='NOLA'):
+                tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+                               window=window, boundary=True)
+
+            assert np.allclose(t, tr[:len(t)]), msg
+            assert not np.allclose(x, xr[:len(x)]), msg
+
+    def test_roundtrip_nola_not_cola(self):
+        rng = np.random.RandomState(1234)
+
+        settings = [
+                    ('boxcar', 100, 10, 3),           # NOLA True, COLA False
+                    ('bartlett', 101, 51, 37),        # NOLA True, COLA False
+                    ('hann', 1024, 256, 127),         # NOLA True, COLA False
+                    (('tukey', 0.5), 1152, 256, 14),  # NOLA True, COLA False
+                    ('hann', 1024, 256, 5),           # NOLA True, COLA False
+                    ]
+
+        for window, N, nperseg, noverlap in settings:
+            msg = f'{window}, {nperseg}, {noverlap}'
+            assert check_NOLA(window, nperseg, noverlap), msg
+            assert not check_COLA(window, nperseg, noverlap), msg
+
+            t = np.arange(N)
+            x = 10 * rng.randn(t.size)
+
+            _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+                            window=window, detrend=None, padded=True,
+                            boundary='zeros')
+
+            tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+                           window=window, boundary=True)
+
+            msg = f'{window}, {noverlap}'
+            assert_allclose(t, tr[:len(t)], err_msg=msg)
+            assert_allclose(x, xr[:len(x)], err_msg=msg)
+
+    def test_roundtrip_float32(self):
+        rng = np.random.RandomState(1234)
+
+        settings = [('hann', 1024, 256, 128)]
+
+        for window, N, nperseg, noverlap in settings:
+            t = np.arange(N)
+            x = 10*rng.randn(t.size)
+            x = x.astype(np.float32)
+
+            _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+                            window=window, detrend=None, padded=False)
+
+            tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+                           window=window)
+
+            msg = f'{window}, {noverlap}'
+            assert_allclose(t, t, err_msg=msg)
+            assert_allclose(x, xr, err_msg=msg, rtol=1e-4, atol=1e-5)
+            assert_(x.dtype == xr.dtype)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize('scaling', ['spectrum', 'psd'])
+    def test_roundtrip_complex(self, scaling):
+        rng = np.random.RandomState(1234)
+
+        settings = [
+                    ('boxcar', 100, 10, 0),           # Test no overlap
+                    ('boxcar', 100, 10, 9),           # Test high overlap
+                    ('bartlett', 101, 51, 26),        # Test odd nperseg
+                    ('hann', 1024, 256, 128),         # Test defaults
+                    (('tukey', 0.5), 1152, 256, 64),  # Test Tukey
+                    ('hann', 1024, 256, 255),         # Test overlapped hann
+                    ]
+
+        for window, N, nperseg, noverlap in settings:
+            t = np.arange(N)
+            x = 10*rng.randn(t.size) + 10j*rng.randn(t.size)
+
+            _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+                            window=window, detrend=None, padded=False,
+                            return_onesided=False, scaling=scaling)
+
+            tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+                           window=window, input_onesided=False,
+                           scaling=scaling)
+
+            msg = f'{window}, {nperseg}, {noverlap}'
+            assert_allclose(t, tr, err_msg=msg)
+            assert_allclose(x, xr, err_msg=msg)
+
+        # Check that asking for onesided switches to twosided
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "Input data is complex, switching to return_onesided=False")
+            _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+                            window=window, detrend=None, padded=False,
+                            return_onesided=True, scaling=scaling)
+
+        tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+                       window=window, input_onesided=False, scaling=scaling)
+
+        msg = f'{window}, {nperseg}, {noverlap}'
+        assert_allclose(t, tr, err_msg=msg)
+        assert_allclose(x, xr, err_msg=msg)
+
+    def test_roundtrip_boundary_extension(self):
+        rng = np.random.RandomState(1234)
+
+        # Test against boxcar, since window is all ones, and thus can be fully
+        # recovered with no boundary extension
+
+        settings = [
+                    ('boxcar', 100, 10, 0),           # Test no overlap
+                    ('boxcar', 100, 10, 9),           # Test high overlap
+                    ]
+
+        for window, N, nperseg, noverlap in settings:
+            t = np.arange(N)
+            x = 10*rng.randn(t.size)
+
+            _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+                           window=window, detrend=None, padded=True,
+                           boundary=None)
+
+            _, xr = istft(zz, noverlap=noverlap, window=window, boundary=False)
+
+            for boundary in ['even', 'odd', 'constant', 'zeros']:
+                _, _, zz_ext = stft(x, nperseg=nperseg, noverlap=noverlap,
+                                window=window, detrend=None, padded=True,
+                                boundary=boundary)
+
+                _, xr_ext = istft(zz_ext, noverlap=noverlap, window=window,
+                                boundary=True)
+
+                msg = f'{window}, {noverlap}, {boundary}'
+                assert_allclose(x, xr, err_msg=msg)
+                assert_allclose(x, xr_ext, err_msg=msg)
+
+    def test_roundtrip_padded_signal(self):
+        rng = np.random.RandomState(1234)
+
+        settings = [
+                    ('boxcar', 101, 10, 0),
+                    ('hann', 1000, 256, 128),
+                    ]
+
+        for window, N, nperseg, noverlap in settings:
+            t = np.arange(N)
+            x = 10*rng.randn(t.size)
+
+            _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+                            window=window, detrend=None, padded=True)
+
+            tr, xr = istft(zz, noverlap=noverlap, window=window)
+
+            msg = f'{window}, {noverlap}'
+            # Account for possible zero-padding at the end
+            assert_allclose(t, tr[:t.size], err_msg=msg)
+            assert_allclose(x, xr[:x.size], err_msg=msg)
+
+    def test_roundtrip_padded_FFT(self):
+        rng = np.random.RandomState(1234)
+
+        settings = [
+                    ('hann', 1024, 256, 128, 512),
+                    ('hann', 1024, 256, 128, 501),
+                    ('boxcar', 100, 10, 0, 33),
+                    (('tukey', 0.5), 1152, 256, 64, 1024),
+                    ]
+
+        for window, N, nperseg, noverlap, nfft in settings:
+            t = np.arange(N)
+            x = 10*rng.randn(t.size)
+            xc = x*np.exp(1j*np.pi/4)
+
+            # real signal
+            _, _, z = stft(x, nperseg=nperseg, noverlap=noverlap, nfft=nfft,
+                            window=window, detrend=None, padded=True)
+
+            # complex signal
+            _, _, zc = stft(xc, nperseg=nperseg, noverlap=noverlap, nfft=nfft,
+                            window=window, detrend=None, padded=True,
+                            return_onesided=False)
+
+            tr, xr = istft(z, nperseg=nperseg, noverlap=noverlap, nfft=nfft,
+                           window=window)
+
+            tr, xcr = istft(zc, nperseg=nperseg, noverlap=noverlap, nfft=nfft,
+                            window=window, input_onesided=False)
+
+            msg = f'{window}, {noverlap}'
+            assert_allclose(t, tr, err_msg=msg)
+            assert_allclose(x, xr, err_msg=msg)
+            assert_allclose(xc, xcr, err_msg=msg)
+
+    def test_axis_rolling(self):
+        rng = np.random.RandomState(1234)
+
+        x_flat = rng.randn(1024)
+        _, _, z_flat = stft(x_flat)
+
+        for a in range(3):
+            newshape = [1,]*3
+            newshape[a] = -1
+            x = x_flat.reshape(newshape)
+
+            _, _, z_plus = stft(x, axis=a)  # Positive axis index
+            _, _, z_minus = stft(x, axis=a-x.ndim)  # Negative axis index
+
+            assert_equal(z_flat, z_plus.squeeze(), err_msg=a)
+            assert_equal(z_flat, z_minus.squeeze(), err_msg=a-x.ndim)
+
+        # z_flat has shape [n_freq, n_time]
+
+        # Test vs. transpose
+        _, x_transpose_m = istft(z_flat.T, time_axis=-2, freq_axis=-1)
+        _, x_transpose_p = istft(z_flat.T, time_axis=0, freq_axis=1)
+
+        assert_allclose(x_flat, x_transpose_m, err_msg='istft transpose minus')
+        assert_allclose(x_flat, x_transpose_p, err_msg='istft transpose plus')
+
+    def test_roundtrip_scaling(self):
+        """Verify behavior of scaling parameter. """
+        # Create 1024 sample cosine signal with amplitude 2:
+        X = np.zeros(513, dtype=complex)
+        X[256] = 1024
+        x = np.fft.irfft(X)
+        power_x = sum(x**2) / len(x)  # power of signal x is 2
+
+        # Calculate magnitude-scaled STFT:
+        Zs = stft(x, boundary='even', scaling='spectrum')[2]
+
+        # Test round trip:
+        x1 = istft(Zs, boundary=True, scaling='spectrum')[1]
+        assert_allclose(x1, x)
+
+        # For a Hann-windowed 256 sample length FFT, we expect a peak at
+        # frequency 64 (since it is 1/4 the length of X) with a height of 1
+        # (half the amplitude). A Hann window of a perfectly centered sine has
+        # the magnitude [..., 0, 0, 0.5, 1, 0.5, 0, 0, ...].
+        # Note that in this case the 'even' padding works for the beginning
+        # but not for the end of the STFT.
+        assert_allclose(abs(Zs[63, :-1]), 0.5)
+        assert_allclose(abs(Zs[64, :-1]), 1)
+        assert_allclose(abs(Zs[65, :-1]), 0.5)
+        # All other values should be zero:
+        Zs[63:66, :-1] = 0
+        # Note since 'rtol' does not have influence here, atol needs to be set:
+        assert_allclose(Zs[:, :-1], 0, atol=np.finfo(Zs.dtype).resolution)
+
+        # Calculate two-sided psd-scaled STFT:
+        #  - using 'even' padding since signal is axis symmetric - this ensures
+        #    stationary behavior on the boundaries
+        #  - using the two-sided transform allows determining the spectral
+        #    power by `sum(abs(Zp[:, k])**2) / len(f)` for the k-th time slot.
+        Zp = stft(x, return_onesided=False, boundary='even', scaling='psd')[2]
+
+        # Calculate spectral power of Zd by summing over the frequency axis:
+        psd_Zp = np.sum(Zp.real**2 + Zp.imag**2, axis=0) / Zp.shape[0]
+        # Spectral power of Zp should be equal to the signal's power:
+        assert_allclose(psd_Zp, power_x)
+
+        # Test round trip:
+        x1 = istft(Zp, input_onesided=False, boundary=True, scaling='psd')[1]
+        assert_allclose(x1, x)
+
+        # The power of the one-sided psd-scaled STFT can be determined
+        # analogously (note that the two sides are not of equal shape):
+        Zp0 = stft(x, return_onesided=True, boundary='even', scaling='psd')[2]
+
+        # Since x is real, its Fourier transform is conjugate symmetric, i.e.,
+        # the missing 'second side' can be expressed through the 'first side':
+        Zp1 = np.conj(Zp0[-2:0:-1, :])  # 'second side' is conjugate reversed
+        assert_allclose(Zp[:129, :], Zp0)
+        assert_allclose(Zp[129:, :], Zp1)
+
+        # Calculate the spectral power:
+        s2 = (np.sum(Zp0.real ** 2 + Zp0.imag ** 2, axis=0) +
+              np.sum(Zp1.real ** 2 + Zp1.imag ** 2, axis=0))
+        psd_Zp01 = s2 / (Zp0.shape[0] + Zp1.shape[0])
+        assert_allclose(psd_Zp01, power_x)
+
+        # Test round trip:
+        x1 = istft(Zp0, input_onesided=True, boundary=True, scaling='psd')[1]
+        assert_allclose(x1, x)
+
+
+class TestSampledSpectralRepresentations:
+    """Check energy/power relations from `Spectral Analysis` section in the user guide.
+
+    A 32 sample cosine signal is used to compare the numerical to the expected results
+    stated in :ref:`tutorial_SpectralAnalysis` in
+    file ``doc/source/tutorial/signal.rst``
+    """
+    n: int = 32  #: number of samples
+    T: float = 1/16  #: sampling interval
+    a_ref: float = 3  #: amplitude of reference
+    l_a: int = 3  #: index in fft for defining frequency of test signal
+
+    x_ref: np.ndarray  #: reference signal
+    X_ref: np.ndarray  #: two-sided FFT of x_ref
+    E_ref: float  #: energy of signal
+    P_ref: float  #: power of signal
+
+    def setup_method(self):
+        """Create Cosine signal with amplitude a from spectrum. """
+        f = rfftfreq(self.n, self.T)
+        X_ref = np.zeros_like(f)
+        self.l_a = 3
+        X_ref[self.l_a] = self.a_ref/2 * self.n  # set amplitude
+        self.x_ref = irfft(X_ref)
+        self.X_ref = fft(self.x_ref)
+
+        # Closed form expression for continuous-time signal:
+        self.E_ref = self.tau * self.a_ref**2 / 2  # energy of signal
+        self.P_ref = self.a_ref**2 / 2  # power of signal
+
+    @property
+    def tau(self) -> float:
+        """Duration of signal. """
+        return self.n * self.T
+
+    @property
+    def delta_f(self) -> float:
+        """Bin width """
+        return 1 / (self.n * self.T)
+
+    def test_reference_signal(self):
+        """Test energy and power formulas. """
+        # Verify that amplitude is a:
+        assert_allclose(2*self.a_ref, np.ptp(self.x_ref), rtol=0.1)
+        # Verify that energy expression for sampled signal:
+        assert_allclose(self.T * sum(self.x_ref ** 2), self.E_ref)
+
+        # Verify that spectral energy and power formulas are correct:
+        sum_X_ref_squared = sum(self.X_ref.real**2 + self.X_ref.imag**2)
+        assert_allclose(self.T/self.n * sum_X_ref_squared, self.E_ref)
+        assert_allclose(1/self.n**2 * sum_X_ref_squared, self.P_ref)
+
+    def test_windowed_DFT(self):
+        """Verify spectral representations of windowed DFT.
+
+        Furthermore, the scalings of `periodogram` and `welch` are verified.
+        """
+        w = hann(self.n, sym=False)
+        c_amp, c_rms = abs(sum(w)), np.sqrt(sum(w.real**2 + w.imag**2))
+        Xw = fft(self.x_ref*w)  # unnormalized windowed DFT
+
+        # Verify that the *spectrum* peak is consistent:
+        assert_allclose(self.tau * Xw[self.l_a] / c_amp, self.a_ref * self.tau / 2)
+        # Verify that the *amplitude spectrum* peak is consistent:
+        assert_allclose(Xw[self.l_a] / c_amp, self.a_ref/2)
+
+        # Verify spectral power/energy equals signal's power/energy:
+        X_ESD = self.tau * self.T * abs(Xw / c_rms)**2  # Energy Spectral Density
+        X_PSD = self.T * abs(Xw / c_rms)**2  # Power Spectral Density
+        assert_allclose(self.delta_f * sum(X_ESD), self.E_ref)
+        assert_allclose(self.delta_f * sum(X_PSD), self.P_ref)
+
+        # Verify scalings of periodogram:
+        kw = dict(fs=1/self.T, window=w, detrend=False, return_onesided=False)
+        _, P_mag = periodogram(self.x_ref, scaling='spectrum', **kw)
+        _, P_psd = periodogram(self.x_ref, scaling='density', **kw)
+
+        # Verify that periodogram calculates a squared magnitude spectrum:
+        float_res = np.finfo(P_mag.dtype).resolution
+        assert_allclose(P_mag, abs(Xw/c_amp)**2, atol=float_res*max(P_mag))
+        # Verify that periodogram calculates a PSD:
+        assert_allclose(P_psd, X_PSD, atol=float_res*max(P_psd))
+
+        # Ensure that scaling of welch is the same as of periodogram:
+        kw = dict(nperseg=len(self.x_ref), noverlap=0, **kw)
+        assert_allclose(welch(self.x_ref, scaling='spectrum', **kw)[1], P_mag,
+                        atol=float_res*max(P_mag))
+        assert_allclose(welch(self.x_ref, scaling='density', **kw)[1], P_psd,
+                        atol=float_res*max(P_psd))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1be4083436f457582c7d8229198fd63ff0f9584
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/tests/test_splines.py
@@ -0,0 +1,362 @@
+# pylint: disable=missing-docstring
+import numpy as np
+import pytest
+from scipy._lib._array_api import xp_assert_close
+
+from scipy.signal._spline import (
+    symiirorder1_ic, symiirorder2_ic_fwd, symiirorder2_ic_bwd)
+from scipy.signal import symiirorder1, symiirorder2
+
+
+def _compute_symiirorder2_bwd_hs(k, cs, rsq, omega):
+    cssq = cs * cs
+    k = np.abs(k)
+    rsupk = np.power(rsq, k / 2.0)
+
+    c0 = (cssq * (1.0 + rsq) / (1.0 - rsq) /
+          (1 - 2 * rsq * np.cos(2 * omega) + rsq * rsq))
+    gamma = (1.0 - rsq) / (1.0 + rsq) / np.tan(omega)
+    return c0 * rsupk * (np.cos(omega * k) + gamma * np.sin(omega * k))
+
+
+class TestSymIIR:
+    @pytest.mark.parametrize(
+        'dtype', [np.float32, np.float64, np.complex64, np.complex128])
+    @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+    def test_symiir1_ic(self, dtype, precision):
+        c_precision = precision
+        if precision <= 0.0 or precision > 1.0:
+            if dtype in {np.float32, np.complex64}:
+                c_precision = 1e-6
+            else:
+                c_precision = 1e-11
+
+        # Symmetrical initial conditions for a IIR filter of order 1 are:
+        # x[0] + z1 * \sum{k = 0}^{n - 1} x[k] * z1^k
+
+        # Check the initial condition for a low-pass filter
+        # with coefficient b = 0.85 on a step signal. The initial condition is
+        # a geometric series: 1 + b * \sum_{k = 0}^{n - 1} u[k] b^k.
+
+        # Finding the initial condition corresponds to
+        # 1. Computing the index n such that b**n < precision, which
+        # corresponds to ceil(log(precision) / log(b))
+        # 2. Computing the geometric series until n, this can be computed
+        # using the partial sum formula: (1 - b**n) / (1 - b)
+        # This holds due to the input being a step signal.
+        b = 0.85
+        n_exp = int(np.ceil(np.log(c_precision) / np.log(b)))
+        expected = np.asarray([[(1 - b ** n_exp) / (1 - b)]], dtype=dtype)
+        expected = 1 + b * expected
+
+        # Create a step signal of size n + 1
+        x = np.ones(n_exp + 1, dtype=dtype)
+        xp_assert_close(symiirorder1_ic(x, b, precision), expected,
+                        atol=2e-6, rtol=2e-7)
+
+        # Check the conditions for a exponential decreasing signal with base 2.
+        # Same conditions hold, as the product of 0.5^n * 0.85^n is
+        # still a geometric series
+        b_d = np.asarray(b, dtype=dtype)
+        expected = np.asarray(
+            [[(1 - (0.5 * b_d) ** n_exp) / (1 - (0.5 * b_d))]], dtype=dtype)
+        expected = 1 + b_d * expected
+
+        # Create an exponential decreasing signal of size n + 1
+        x = 2 ** -np.arange(n_exp + 1, dtype=dtype)
+        xp_assert_close(symiirorder1_ic(x, b, precision), expected,
+                        atol=2e-6, rtol=2e-7)
+
+    def test_symiir1_ic_fails(self):
+        # Test that symiirorder1_ic fails whenever \sum_{n = 1}^{n} b^n > eps
+        b = 0.85
+        # Create a step signal of size 100
+        x = np.ones(100, dtype=np.float64)
+
+        # Compute the closed form for the geometrical series
+        precision = 1 / (1 - b)
+        pytest.raises(ValueError, symiirorder1_ic, x, b, precision)
+
+        # Test that symiirorder1_ic fails when |z1| >= 1
+        pytest.raises(ValueError, symiirorder1_ic, x, 1.0, -1)
+        pytest.raises(ValueError, symiirorder1_ic, x, 2.0, -1)
+
+    @pytest.mark.parametrize(
+        'dtype', [np.float32, np.float64, np.complex64, np.complex128])
+    @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+    def test_symiir1(self, dtype, precision):
+        c_precision = precision
+        if precision <= 0.0 or precision > 1.0:
+            if dtype in {np.float32, np.complex64}:
+                c_precision = 1e-6
+            else:
+                c_precision = 1e-11
+
+        # Test for a low-pass filter with c0 = 0.15 and z1 = 0.85
+        # using an unit step over 200 samples.
+        c0 = 0.15
+        z1 = 0.85
+        n = 200
+        signal = np.ones(n, dtype=dtype)
+
+        # Find the initial condition. See test_symiir1_ic for a detailed
+        # explanation
+        n_exp = int(np.ceil(np.log(c_precision) / np.log(z1)))
+        initial = np.asarray((1 - z1 ** n_exp) / (1 - z1), dtype=dtype)
+        initial = 1 + z1 * initial
+
+        # Forward pass
+        # The transfer function for the system 1 / (1 - z1 * z^-1) when
+        # applied to an unit step with initial conditions y0 is
+        # 1 / (1 - z1 * z^-1) * (z^-1 / (1 - z^-1) + y0)
+
+        # Solving the inverse Z-transform for the given expression yields:
+        # y[n] = y0 * z1**n * u[n] +
+        #        -z1 / (1 - z1) * z1**(k - 1) * u[k - 1] +
+        #        1 / (1 - z1) * u[k - 1]
+        # d is the Kronecker delta function, and u is the unit step
+
+        # y0 * z1**n * u[n]
+        pos = np.arange(n, dtype=dtype)
+        comp1 = initial * z1**pos
+
+        # -z1 / (1 - z1) * z1**(k - 1) * u[k - 1]
+        comp2 = np.zeros(n, dtype=dtype)
+        comp2[1:] = -z1 / (1 - z1) * z1**pos[:-1]
+
+        # 1 / (1 - z1) * u[k - 1]
+        comp3 = np.zeros(n, dtype=dtype)
+        comp3[1:] = 1 / (1 - z1)
+
+        expected_fwd = comp1 + comp2 + comp3
+
+        # Reverse condition
+        sym_cond = -c0 / (z1 - 1.0) * expected_fwd[-1]
+
+        # Backward pass
+        # The transfer function for the forward result is equivalent to
+        # the forward system times c0 / (1 - z1 * z).
+
+        # Computing a closed form for the complete expression is difficult
+        # The result will be computed iteratively from the difference equation
+        exp_out = np.zeros(n, dtype=dtype)
+        exp_out[0] = sym_cond
+
+        for i in range(1, n):
+            exp_out[i] = c0 * expected_fwd[n - 1 - i] + z1 * exp_out[i - 1]
+
+        exp_out = exp_out[::-1]
+
+        out = symiirorder1(signal, c0, z1, precision)
+        xp_assert_close(out, exp_out, atol=4e-6, rtol=6e-7)
+
+    @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+    def test_symiir1_values(self, dtype):
+        rng = np.random.RandomState(1234)
+        dtype = getattr(np, dtype)
+        s = rng.uniform(size=16).astype(dtype)
+        res = symiirorder1(s, 0.5, 0.1)
+
+        # values from scipy 1.9.1
+        exp_res = np.array([0.14387447, 0.35166047, 0.29735238, 0.46295986, 0.45174927,
+                            0.19982875, 0.20355805, 0.47378628, 0.57232247, 0.51597393,
+                           0.25935107, 0.31438554, 0.41096728, 0.4190693 , 0.25812255,
+                           0.33671467], dtype=res.dtype)
+        assert res.dtype == dtype
+        atol = {np.float64: 1e-15, np.float32: 1e-7}[dtype]
+        xp_assert_close(res, exp_res, atol=atol)
+
+        s = s + 1j*s
+        res = symiirorder1(s, 0.5, 0.1)
+        assert res.dtype == np.complex64 if dtype == np.float32 else np.complex128
+        xp_assert_close(res, exp_res + 1j*exp_res, atol=atol)
+
+    @pytest.mark.parametrize(
+        'dtype', ['float32', 'float64'])
+    @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+    def test_symiir2_initial_fwd(self, dtype, precision):
+        dtype = getattr(np, dtype)
+        c_precision = precision
+        if precision <= 0.0 or precision > 1.0:
+            if dtype in {np.float32, np.complex64}:
+                c_precision = 1e-6
+            else:
+                c_precision = 1e-11
+
+        # Compute the initial conditions for a order-two symmetrical low-pass
+        # filter with r = 0.5 and omega = pi / 3 for an unit step input.
+        r = np.asarray(0.5, dtype=dtype)
+        omega = np.asarray(np.pi / 3.0, dtype=dtype)
+        cs = 1 - 2 * r * np.cos(omega) + r**2
+
+        # The index n for the initial condition is bound from 0 to the
+        # first position where sin(omega * (n + 2)) = 0 => omega * (n + 2) = pi
+        # For omega = pi / 3, the maximum initial condition occurs when
+        # sqrt(3) / 2 * r**n < precision.
+        # => n = log(2 * sqrt(3) / 3 * precision) / log(r)
+        ub = np.ceil(np.log(c_precision / np.sin(omega)) / np.log(c_precision))
+        lb = np.ceil(np.pi / omega) - 2
+        n_exp = min(ub, lb)
+
+        # The forward initial condition for a filter of order two is:
+        # \frac{cs}{\sin(\omega)} \sum_{n = 0}^{N - 1} {
+        #    r^(n + 1) \sin{\omega(n + 2)}} + cs
+        # The closed expression for this sum is:
+        # s[n] = 2 * r * np.cos(omega) -
+        #        r**2 - r**(n + 2) * np.sin(omega * (n + 3)) / np.sin(omega) +
+        #        r**(n + 3) * np.sin(omega * (n + 2)) / np.sin(omega) + cs
+        fwd_initial_1 = (
+            cs +
+            2 * r * np.cos(omega) -
+            r**2 -
+            r**(n_exp + 2) * np.sin(omega * (n_exp + 3)) / np.sin(omega) +
+            r**(n_exp + 3) * np.sin(omega * (n_exp + 2)) / np.sin(omega))
+
+        # The second initial condition is given by
+        # s[n] = 1 / np.sin(omega) * (
+        #        r**2 * np.sin(3 * omega) -
+        #        r**3 * np.sin(2 * omega) -
+        #        r**(n + 3) * np.sin(omega * (n + 4)) +
+        #        r**(n + 4) * np.sin(omega * (n + 3)))
+        ub = np.ceil(np.log(c_precision / np.sin(omega)) / np.log(c_precision))
+        lb = np.ceil(np.pi / omega) - 3
+        n_exp = min(ub, lb)
+
+        fwd_initial_2 = (
+            cs + cs * 2 * r * np.cos(omega) +
+            (r**2 * np.sin(3 * omega) -
+             r**3 * np.sin(2 * omega) -
+             r**(n_exp + 3) * np.sin(omega * (n_exp + 4)) +
+             r**(n_exp + 4) * np.sin(omega * (n_exp + 3))) / np.sin(omega))
+
+        expected = np.r_[fwd_initial_1, fwd_initial_2][None, :]
+        expected = expected.astype(dtype)
+
+        n = 100
+        signal = np.ones(n, dtype=dtype)
+
+        out = symiirorder2_ic_fwd(signal, r, omega, precision)
+        xp_assert_close(out, expected, atol=4e-6, rtol=6e-7)
+
+    @pytest.mark.parametrize(
+        'dtype', [np.float32, np.float64])
+    @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+    def test_symiir2_initial_bwd(self, dtype, precision):
+        c_precision = precision
+        if precision <= 0.0 or precision > 1.0:
+            if dtype in {np.float32, np.complex64}:
+                c_precision = 1e-6
+            else:
+                c_precision = 1e-11
+
+        r = np.asarray(0.5, dtype=dtype)
+        omega = np.asarray(np.pi / 3.0, dtype=dtype)
+        cs = 1 - 2 * r * np.cos(omega) + r * r
+        a2 = 2 * r * np.cos(omega)
+        a3 = -r * r
+
+        n = 100
+        signal = np.ones(n, dtype=dtype)
+
+        # Compute initial forward conditions
+        ic = symiirorder2_ic_fwd(signal, r, omega, precision)
+        out = np.zeros(n + 2, dtype=dtype)
+        out[:2] = ic[0]
+
+        # Apply the forward system cs / (1 - a2 * z^-1 - a3 * z^-2))
+        for i in range(2, n + 2):
+            out[i] = cs * signal[i - 2] + a2 * out[i - 1] + a3 * out[i - 2]
+
+        # Find the backward initial conditions
+        ic2 = np.zeros(2, dtype=dtype)
+        idx = np.arange(n)
+
+        diff = (_compute_symiirorder2_bwd_hs(idx, cs, r * r, omega) +
+                _compute_symiirorder2_bwd_hs(idx + 1, cs, r * r, omega))
+        ic2_0_all = np.cumsum(diff * out[:1:-1])
+        pos = np.where(diff ** 2 < c_precision)[0]
+        ic2[0] = ic2_0_all[pos[0]]
+
+        diff = (_compute_symiirorder2_bwd_hs(idx - 1, cs, r * r, omega) +
+                _compute_symiirorder2_bwd_hs(idx + 2, cs, r * r, omega))
+        ic2_1_all = np.cumsum(diff * out[:1:-1])
+        pos = np.where(diff ** 2 < c_precision)[0]
+        ic2[1] = ic2_1_all[pos[0]]
+
+        out_ic = symiirorder2_ic_bwd(out, r, omega, precision)[0]
+        xp_assert_close(out_ic, ic2, atol=4e-6, rtol=6e-7)
+
+    @pytest.mark.parametrize(
+        'dtype', [np.float32, np.float64])
+    @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+    def test_symiir2(self, dtype, precision):
+        r = np.asarray(0.5, dtype=dtype)
+        omega = np.asarray(np.pi / 3.0, dtype=dtype)
+        cs = 1 - 2 * r * np.cos(omega) + r * r
+        a2 = 2 * r * np.cos(omega)
+        a3 = -r * r
+
+        n = 100
+        signal = np.ones(n, dtype=dtype)
+
+        # Compute initial forward conditions
+        ic = symiirorder2_ic_fwd(signal, r, omega, precision)
+        out1 = np.zeros(n + 2, dtype=dtype)
+        out1[:2] = ic[0]
+
+        # Apply the forward system cs / (1 - a2 * z^-1 - a3 * z^-2))
+        for i in range(2, n + 2):
+            out1[i] = cs * signal[i - 2] + a2 * out1[i - 1] + a3 * out1[i - 2]
+
+        # Find the backward initial conditions
+        ic2 = symiirorder2_ic_bwd(out1, r, omega, precision)[0]
+
+        # Apply the system cs / (1 - a2 * z - a3 * z^2)) in backwards
+        exp = np.empty(n, dtype=dtype)
+        exp[-2:] = ic2[::-1]
+
+        for i in range(n - 3, -1, -1):
+            exp[i] = cs * out1[i] + a2 * exp[i + 1] + a3 * exp[i + 2]
+
+        out = symiirorder2(signal, r, omega, precision)
+        xp_assert_close(out, exp, atol=4e-6, rtol=6e-7)
+
+    @pytest.mark.parametrize('dtyp', ['float32', 'float64'])
+    def test_symiir2_values(self, dtyp):
+        dtyp = getattr(np, dtyp)
+        rng = np.random.RandomState(1234)
+        s = rng.uniform(size=16).astype(dtyp)
+        res = symiirorder2(s, 0.1, 0.1, precision=1e-10)
+
+        # values from scipy 1.9.1
+        exp_res = np.array([0.26572609, 0.53408018, 0.51032696, 0.72115829, 0.69486885,
+           0.3649055 , 0.37349478, 0.74165032, 0.89718521, 0.80582483,
+           0.46758053, 0.51898709, 0.65025605, 0.65394321, 0.45273595,
+           0.53539183], dtype=dtyp)
+
+        assert res.dtype == dtyp
+        # The values in SciPy 1.14 agree with those in SciPy 1.9.1 to this
+        # accuracy only. Implementation differences are twofold:
+        # 1. boundary conditions are computed differently
+        # 2. the filter itself uses sosfilt instead of a hardcoded iteration
+        # The boundary conditions seem are tested separately (see
+        # test_symiir2_initial_{fwd,bwd} above, so the difference is likely
+        # due to a different way roundoff errors accumulate in the filter.
+        # In that respect, sosfilt is likely doing a better job.
+        xp_assert_close(res, exp_res, atol=2e-6)
+
+        s = s + 1j*s
+        with pytest.raises(TypeError):
+            res = symiirorder2(s, 0.5, 0.1)
+
+    def test_symiir1_integer_input(self):
+        s = np.where(np.arange(100) % 2, -1, 1)
+        expected = symiirorder1(s.astype(float), 0.5, 0.5)
+        out = symiirorder1(s, 0.5, 0.5)
+        xp_assert_close(out, expected)
+
+    def test_symiir2_integer_input(self):
+        s = np.where(np.arange(100) % 2, -1, 1)
+        expected = symiirorder2(s.astype(float), 0.5, np.pi / 3.0)
+        out = symiirorder2(s, 0.5, np.pi / 3.0)
+        xp_assert_close(out, expected)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..967a7c758f69c1c8002d886d78832904c402d2b3
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/__init__.py
@@ -0,0 +1,52 @@
+"""
+Window functions (:mod:`scipy.signal.windows`)
+==============================================
+
+The suite of window functions for filtering and spectral estimation.
+
+.. currentmodule:: scipy.signal.windows
+
+.. autosummary::
+   :toctree: generated/
+
+   get_window              -- Return a window of a given length and type.
+
+   barthann                -- Bartlett-Hann window
+   bartlett                -- Bartlett window
+   blackman                -- Blackman window
+   blackmanharris          -- Minimum 4-term Blackman-Harris window
+   bohman                  -- Bohman window
+   boxcar                  -- Boxcar window
+   chebwin                 -- Dolph-Chebyshev window
+   cosine                  -- Cosine window
+   dpss                    -- Discrete prolate spheroidal sequences
+   exponential             -- Exponential window
+   flattop                 -- Flat top window
+   gaussian                -- Gaussian window
+   general_cosine          -- Generalized Cosine window
+   general_gaussian        -- Generalized Gaussian window
+   general_hamming         -- Generalized Hamming window
+   hamming                 -- Hamming window
+   hann                    -- Hann window
+   kaiser                  -- Kaiser window
+   kaiser_bessel_derived   -- Kaiser-Bessel derived window
+   lanczos                 -- Lanczos window also known as a sinc window
+   nuttall                 -- Nuttall's minimum 4-term Blackman-Harris window
+   parzen                  -- Parzen window
+   taylor                  -- Taylor window
+   triang                  -- Triangular window
+   tukey                   -- Tukey window
+
+"""
+
+from ._windows import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import windows
+
+__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
+           'blackmanharris', 'flattop', 'bartlett', 'barthann',
+           'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian',
+           'general_gaussian', 'general_cosine', 'general_hamming',
+           'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor',
+           'get_window', 'dpss', 'lanczos']
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/_windows.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/_windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..e89c1aee6aba661f11a86cb2213904964d870782
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/_windows.py
@@ -0,0 +1,2374 @@
+"""The suite of window functions."""
+
+import operator
+import warnings
+
+import numpy as np
+from scipy import linalg, special, fft as sp_fft
+
+__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
+           'blackmanharris', 'flattop', 'bartlett', 'barthann',
+           'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian',
+           'general_cosine', 'general_gaussian', 'general_hamming',
+           'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor',
+           'dpss', 'get_window', 'lanczos']
+
+
+def _len_guards(M):
+    """Handle small or incorrect window lengths"""
+    if int(M) != M or M < 0:
+        raise ValueError('Window length M must be a non-negative integer')
+    return M <= 1
+
+
+def _extend(M, sym):
+    """Extend window by 1 sample if needed for DFT-even symmetry"""
+    if not sym:
+        return M + 1, True
+    else:
+        return M, False
+
+
+def _truncate(w, needed):
+    """Truncate window by 1 sample if needed for DFT-even symmetry"""
+    if needed:
+        return w[:-1]
+    else:
+        return w
+
+
+def general_cosine(M, a, sym=True):
+    r"""
+    Generic weighted sum of cosine terms window
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window
+    a : array_like
+        Sequence of weighting coefficients. This uses the convention of being
+        centered on the origin, so these will typically all be positive
+        numbers, not alternating sign.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The array of window values.
+
+    References
+    ----------
+    .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE
+           Transactions on Acoustics, Speech, and Signal Processing, vol. 29,
+           no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`.
+    .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the
+           Discrete Fourier transform (DFT), including a comprehensive list of
+           window functions and some new flat-top windows", February 15, 2002
+           https://holometer.fnal.gov/GH_FFT.pdf
+
+    Examples
+    --------
+    Heinzel describes a flat-top window named "HFT90D" with formula: [2]_
+
+    .. math::  w_j = 1 - 1.942604 \cos(z) + 1.340318 \cos(2z)
+               - 0.440811 \cos(3z) + 0.043097 \cos(4z)
+
+    where
+
+    .. math::  z = \frac{2 \pi j}{N}, j = 0...N - 1
+
+    Since this uses the convention of starting at the origin, to reproduce the
+    window, we need to convert every other coefficient to a positive number:
+
+    >>> HFT90D = [1, 1.942604, 1.340318, 0.440811, 0.043097]
+
+    The paper states that the highest sidelobe is at -90.2 dB.  Reproduce
+    Figure 42 by plotting the window and its frequency response, and confirm
+    the sidelobe level in red:
+
+    >>> import numpy as np
+    >>> from scipy.signal.windows import general_cosine
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = general_cosine(1000, HFT90D, sym=False)
+    >>> plt.plot(window)
+    >>> plt.title("HFT90D window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 10000) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = np.abs(fftshift(A / abs(A).max()))
+    >>> response = 20 * np.log10(np.maximum(response, 1e-10))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-50/1000, 50/1000, -140, 0])
+    >>> plt.title("Frequency response of the HFT90D window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+    >>> plt.axhline(-90.2, color='red')
+    >>> plt.show()
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    fac = np.linspace(-np.pi, np.pi, M)
+    w = np.zeros(M)
+    for k in range(len(a)):
+        w += a[k] * np.cos(k * fac)
+
+    return _truncate(w, needs_trunc)
+
+
+def boxcar(M, sym=True):
+    """Return a boxcar or rectangular window.
+
+    Also known as a rectangular window or Dirichlet window, this is equivalent
+    to no window at all.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        Whether the window is symmetric. (Has no effect for boxcar.)
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1.
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.boxcar(51)
+    >>> plt.plot(window)
+    >>> plt.title("Boxcar window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the boxcar window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    w = np.ones(M, float)
+
+    return _truncate(w, needs_trunc)
+
+
+def triang(M, sym=True):
+    """Return a triangular window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    See Also
+    --------
+    bartlett : A triangular window that touches zero
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.triang(51)
+    >>> plt.plot(window)
+    >>> plt.title("Triangular window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = np.abs(fftshift(A / abs(A).max()))
+    >>> response = 20 * np.log10(np.maximum(response, 1e-10))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the triangular window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    n = np.arange(1, (M + 1) // 2 + 1)
+    if M % 2 == 0:
+        w = (2 * n - 1.0) / M
+        w = np.r_[w, w[::-1]]
+    else:
+        w = 2 * n / (M + 1.0)
+        w = np.r_[w, w[-2::-1]]
+
+    return _truncate(w, needs_trunc)
+
+
+def parzen(M, sym=True):
+    """Return a Parzen window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    References
+    ----------
+    .. [1] E. Parzen, "Mathematical Considerations in the Estimation of
+           Spectra", Technometrics,  Vol. 3, No. 2 (May, 1961), pp. 167-190
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.parzen(51)
+    >>> plt.plot(window)
+    >>> plt.title("Parzen window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Parzen window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    n = np.arange(-(M - 1) / 2.0, (M - 1) / 2.0 + 0.5, 1.0)
+    na = np.extract(n < -(M - 1) / 4.0, n)
+    nb = np.extract(abs(n) <= (M - 1) / 4.0, n)
+    wa = 2 * (1 - np.abs(na) / (M / 2.0)) ** 3.0
+    wb = (1 - 6 * (np.abs(nb) / (M / 2.0)) ** 2.0 +
+          6 * (np.abs(nb) / (M / 2.0)) ** 3.0)
+    w = np.r_[wa, wb, wa[::-1]]
+
+    return _truncate(w, needs_trunc)
+
+
+def bohman(M, sym=True):
+    """Return a Bohman window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.bohman(51)
+    >>> plt.plot(window)
+    >>> plt.title("Bohman window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2047) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Bohman window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    fac = np.abs(np.linspace(-1, 1, M)[1:-1])
+    w = (1 - fac) * np.cos(np.pi * fac) + 1.0 / np.pi * np.sin(np.pi * fac)
+    w = np.r_[0, w, 0]
+
+    return _truncate(w, needs_trunc)
+
+
+def blackman(M, sym=True):
+    r"""
+    Return a Blackman window.
+
+    The Blackman window is a taper formed by using the first three terms of
+    a summation of cosines. It was designed to have close to the minimal
+    leakage possible.  It is close to optimal, only slightly worse than a
+    Kaiser window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    The Blackman window is defined as
+
+    .. math::  w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
+
+    The "exact Blackman" window was designed to null out the third and fourth
+    sidelobes, but has discontinuities at the boundaries, resulting in a
+    6 dB/oct fall-off.  This window is an approximation of the "exact" window,
+    which does not null the sidelobes as well, but is smooth at the edges,
+    improving the fall-off rate to 18 dB/oct. [3]_
+
+    Most references to the Blackman window come from the signal processing
+    literature, where it is used as one of many windowing functions for
+    smoothing values.  It is also known as an apodization (which means
+    "removing the foot", i.e. smoothing discontinuities at the beginning
+    and end of the sampled signal) or tapering function. It is known as a
+    "near optimal" tapering function, almost as good (by some measures)
+    as the Kaiser window.
+
+    References
+    ----------
+    .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
+           spectra, Dover Publications, New York.
+    .. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
+           Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
+    .. [3] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
+           Analysis with the Discrete Fourier Transform". Proceedings of the
+           IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`.
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.blackman(51)
+    >>> plt.plot(window)
+    >>> plt.title("Blackman window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = np.abs(fftshift(A / abs(A).max()))
+    >>> response = 20 * np.log10(np.maximum(response, 1e-10))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Blackman window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    # Docstring adapted from NumPy's blackman function
+    return general_cosine(M, [0.42, 0.50, 0.08], sym)
+
+
+def nuttall(M, sym=True):
+    """Return a minimum 4-term Blackman-Harris window according to Nuttall.
+
+    This variation is called "Nuttall4c" by Heinzel. [2]_
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    References
+    ----------
+    .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE
+           Transactions on Acoustics, Speech, and Signal Processing, vol. 29,
+           no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`.
+    .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the
+           Discrete Fourier transform (DFT), including a comprehensive list of
+           window functions and some new flat-top windows", February 15, 2002
+           https://holometer.fnal.gov/GH_FFT.pdf
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.nuttall(51)
+    >>> plt.plot(window)
+    >>> plt.title("Nuttall window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Nuttall window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    return general_cosine(M, [0.3635819, 0.4891775, 0.1365995, 0.0106411], sym)
+
+
+def blackmanharris(M, sym=True):
+    """Return a minimum 4-term Blackman-Harris window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.blackmanharris(51)
+    >>> plt.plot(window)
+    >>> plt.title("Blackman-Harris window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Blackman-Harris window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    return general_cosine(M, [0.35875, 0.48829, 0.14128, 0.01168], sym)
+
+
+def flattop(M, sym=True):
+    """Return a flat top window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    Flat top windows are used for taking accurate measurements of signal
+    amplitude in the frequency domain, with minimal scalloping error from the
+    center of a frequency bin to its edges, compared to others.  This is a
+    5th-order cosine window, with the 5 terms optimized to make the main lobe
+    maximally flat. [1]_
+
+    References
+    ----------
+    .. [1] D'Antona, Gabriele, and A. Ferrero, "Digital Signal Processing for
+           Measurement Systems", Springer Media, 2006, p. 70
+           :doi:`10.1007/0-387-28666-7`.
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.flattop(51)
+    >>> plt.plot(window)
+    >>> plt.title("Flat top window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the flat top window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    a = [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368]
+    return general_cosine(M, a, sym)
+
+
+def bartlett(M, sym=True):
+    r"""
+    Return a Bartlett window.
+
+    The Bartlett window is very similar to a triangular window, except
+    that the end points are at zero.  It is often used in signal
+    processing for tapering a signal, without generating too much
+    ripple in the frequency domain.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The triangular window, with the first and last samples equal to zero
+        and the maximum value normalized to 1 (though the value 1 does not
+        appear if `M` is even and `sym` is True).
+
+    See Also
+    --------
+    triang : A triangular window that does not touch zero at the ends
+
+    Notes
+    -----
+    The Bartlett window is defined as
+
+    .. math:: w(n) = \frac{2}{M-1} \left(
+              \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right|
+              \right)
+
+    Most references to the Bartlett window come from the signal
+    processing literature, where it is used as one of many windowing
+    functions for smoothing values.  Note that convolution with this
+    window produces linear interpolation.  It is also known as an
+    apodization (which means"removing the foot", i.e. smoothing
+    discontinuities at the beginning and end of the sampled signal) or
+    tapering function. The Fourier transform of the Bartlett is the product
+    of two sinc functions.
+    Note the excellent discussion in Kanasewich. [2]_
+
+    References
+    ----------
+    .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
+           Biometrika 37, 1-16, 1950.
+    .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
+           The University of Alberta Press, 1975, pp. 109-110.
+    .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
+           Processing", Prentice-Hall, 1999, pp. 468-471.
+    .. [4] Wikipedia, "Window function",
+           https://en.wikipedia.org/wiki/Window_function
+    .. [5] W.H. Press,  B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
+           "Numerical Recipes", Cambridge University Press, 1986, page 429.
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.bartlett(51)
+    >>> plt.plot(window)
+    >>> plt.title("Bartlett window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Bartlett window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    # Docstring adapted from NumPy's bartlett function
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    n = np.arange(0, M)
+    w = np.where(np.less_equal(n, (M - 1) / 2.0),
+                 2.0 * n / (M - 1), 2.0 - 2.0 * n / (M - 1))
+
+    return _truncate(w, needs_trunc)
+
+
+def hann(M, sym=True):
+    r"""
+    Return a Hann window.
+
+    The Hann window is a taper formed by using a raised cosine or sine-squared
+    with ends that touch zero.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    The Hann window is defined as
+
+    .. math::  w(n) = 0.5 - 0.5 \cos\left(\frac{2\pi{n}}{M-1}\right)
+               \qquad 0 \leq n \leq M-1
+
+    The window was named for Julius von Hann, an Austrian meteorologist. It is
+    also known as the Cosine Bell. It is sometimes erroneously referred to as
+    the "Hanning" window, from the use of "hann" as a verb in the original
+    paper and confusion with the very similar Hamming window.
+
+    Most references to the Hann window come from the signal processing
+    literature, where it is used as one of many windowing functions for
+    smoothing values.  It is also known as an apodization (which means
+    "removing the foot", i.e. smoothing discontinuities at the beginning
+    and end of the sampled signal) or tapering function.
+
+    References
+    ----------
+    .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
+           spectra, Dover Publications, New York.
+    .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
+           The University of Alberta Press, 1975, pp. 106-108.
+    .. [3] Wikipedia, "Window function",
+           https://en.wikipedia.org/wiki/Window_function
+    .. [4] W.H. Press,  B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
+           "Numerical Recipes", Cambridge University Press, 1986, page 425.
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.hann(51)
+    >>> plt.plot(window)
+    >>> plt.title("Hann window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = np.abs(fftshift(A / abs(A).max()))
+    >>> response = 20 * np.log10(np.maximum(response, 1e-10))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Hann window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    # Docstring adapted from NumPy's hanning function
+    return general_hamming(M, 0.5, sym)
+
+
+def tukey(M, alpha=0.5, sym=True):
+    r"""Return a Tukey window, also known as a tapered cosine window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    alpha : float, optional
+        Shape parameter of the Tukey window, representing the fraction of the
+        window inside the cosine tapered region.
+        If zero, the Tukey window is equivalent to a rectangular window.
+        If one, the Tukey window is equivalent to a Hann window.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    References
+    ----------
+    .. [1] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
+           Analysis with the Discrete Fourier Transform". Proceedings of the
+           IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`
+    .. [2] Wikipedia, "Window function",
+           https://en.wikipedia.org/wiki/Window_function#Tukey_window
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.tukey(51)
+    >>> plt.plot(window)
+    >>> plt.title("Tukey window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+    >>> plt.ylim([0, 1.1])
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Tukey window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+
+    if alpha <= 0:
+        return np.ones(M, 'd')
+    elif alpha >= 1.0:
+        return hann(M, sym=sym)
+
+    M, needs_trunc = _extend(M, sym)
+
+    n = np.arange(0, M)
+    width = int(np.floor(alpha*(M-1)/2.0))
+    n1 = n[0:width+1]
+    n2 = n[width+1:M-width-1]
+    n3 = n[M-width-1:]
+
+    w1 = 0.5 * (1 + np.cos(np.pi * (-1 + 2.0*n1/alpha/(M-1))))
+    w2 = np.ones(n2.shape)
+    w3 = 0.5 * (1 + np.cos(np.pi * (-2.0/alpha + 1 + 2.0*n3/alpha/(M-1))))
+
+    w = np.concatenate((w1, w2, w3))
+
+    return _truncate(w, needs_trunc)
+
+
+def barthann(M, sym=True):
+    """Return a modified Bartlett-Hann window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.barthann(51)
+    >>> plt.plot(window)
+    >>> plt.title("Bartlett-Hann window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Bartlett-Hann window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    n = np.arange(0, M)
+    fac = np.abs(n / (M - 1.0) - 0.5)
+    w = 0.62 - 0.48 * fac + 0.38 * np.cos(2 * np.pi * fac)
+
+    return _truncate(w, needs_trunc)
+
+
+def general_hamming(M, alpha, sym=True):
+    r"""Return a generalized Hamming window.
+
+    The generalized Hamming window is constructed by multiplying a rectangular
+    window by one period of a cosine function [1]_.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    alpha : float
+        The window coefficient, :math:`\alpha`
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    See Also
+    --------
+    hamming, hann
+
+    Notes
+    -----
+    The generalized Hamming window is defined as
+
+    .. math:: w(n) = \alpha - \left(1 - \alpha\right)
+              \cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1
+
+    Both the common Hamming window and Hann window are special cases of the
+    generalized Hamming window with :math:`\alpha` = 0.54 and :math:`\alpha` =
+    0.5, respectively [2]_.
+
+    References
+    ----------
+    .. [1] DSPRelated, "Generalized Hamming Window Family",
+           https://www.dsprelated.com/freebooks/sasp/Generalized_Hamming_Window_Family.html
+    .. [2] Wikipedia, "Window function",
+           https://en.wikipedia.org/wiki/Window_function
+    .. [3] Riccardo Piantanida ESA, "Sentinel-1 Level 1 Detailed Algorithm
+           Definition",
+           https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Level-1-Detailed-Algorithm-Definition
+    .. [4] Matthieu Bourbigot ESA, "Sentinel-1 Product Definition",
+           https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Product-Definition
+
+    Examples
+    --------
+    The Sentinel-1A/B Instrument Processing Facility uses generalized Hamming
+    windows in the processing of spaceborne Synthetic Aperture Radar (SAR)
+    data [3]_. The facility uses various values for the :math:`\alpha`
+    parameter based on operating mode of the SAR instrument. Some common
+    :math:`\alpha` values include 0.75, 0.7 and 0.52 [4]_. As an example, we
+    plot these different windows.
+
+    >>> import numpy as np
+    >>> from scipy.signal.windows import general_hamming
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> fig1, spatial_plot = plt.subplots()
+    >>> spatial_plot.set_title("Generalized Hamming Windows")
+    >>> spatial_plot.set_ylabel("Amplitude")
+    >>> spatial_plot.set_xlabel("Sample")
+
+    >>> fig2, freq_plot = plt.subplots()
+    >>> freq_plot.set_title("Frequency Responses")
+    >>> freq_plot.set_ylabel("Normalized magnitude [dB]")
+    >>> freq_plot.set_xlabel("Normalized frequency [cycles per sample]")
+
+    >>> for alpha in [0.75, 0.7, 0.52]:
+    ...     window = general_hamming(41, alpha)
+    ...     spatial_plot.plot(window, label="{:.2f}".format(alpha))
+    ...     A = fft(window, 2048) / (len(window)/2.0)
+    ...     freq = np.linspace(-0.5, 0.5, len(A))
+    ...     response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    ...     freq_plot.plot(freq, response, label="{:.2f}".format(alpha))
+    >>> freq_plot.legend(loc="upper right")
+    >>> spatial_plot.legend(loc="upper right")
+
+    """
+    return general_cosine(M, [alpha, 1. - alpha], sym)
+
+
+def hamming(M, sym=True):
+    r"""Return a Hamming window.
+
+    The Hamming window is a taper formed by using a raised cosine with
+    non-zero endpoints, optimized to minimize the nearest side lobe.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    The Hamming window is defined as
+
+    .. math::  w(n) = 0.54 - 0.46 \cos\left(\frac{2\pi{n}}{M-1}\right)
+               \qquad 0 \leq n \leq M-1
+
+    The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and
+    is described in Blackman and Tukey. It was recommended for smoothing the
+    truncated autocovariance function in the time domain.
+    Most references to the Hamming window come from the signal processing
+    literature, where it is used as one of many windowing functions for
+    smoothing values.  It is also known as an apodization (which means
+    "removing the foot", i.e. smoothing discontinuities at the beginning
+    and end of the sampled signal) or tapering function.
+
+    References
+    ----------
+    .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
+           spectra, Dover Publications, New York.
+    .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
+           University of Alberta Press, 1975, pp. 109-110.
+    .. [3] Wikipedia, "Window function",
+           https://en.wikipedia.org/wiki/Window_function
+    .. [4] W.H. Press,  B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
+           "Numerical Recipes", Cambridge University Press, 1986, page 425.
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.hamming(51)
+    >>> plt.plot(window)
+    >>> plt.title("Hamming window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Hamming window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    # Docstring adapted from NumPy's hamming function
+    return general_hamming(M, 0.54, sym)
+
+
+def kaiser(M, beta, sym=True):
+    r"""Return a Kaiser window.
+
+    The Kaiser window is a taper formed by using a Bessel function.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    beta : float
+        Shape parameter, determines trade-off between main-lobe width and
+        side lobe level. As beta gets large, the window narrows.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    The Kaiser window is defined as
+
+    .. math::  w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}}
+               \right)/I_0(\beta)
+
+    with
+
+    .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},
+
+    where :math:`I_0` is the modified zeroth-order Bessel function.
+
+    The Kaiser was named for Jim Kaiser, who discovered a simple approximation
+    to the DPSS window based on Bessel functions.
+    The Kaiser window is a very good approximation to the discrete prolate
+    spheroidal sequence, or Slepian window, which is the transform which
+    maximizes the energy in the main lobe of the window relative to total
+    energy.
+
+    The Kaiser can approximate other windows by varying the beta parameter.
+    (Some literature uses alpha = beta/pi.) [4]_
+
+    ====  =======================
+    beta  Window shape
+    ====  =======================
+    0     Rectangular
+    5     Similar to a Hamming
+    6     Similar to a Hann
+    8.6   Similar to a Blackman
+    ====  =======================
+
+    A beta value of 14 is probably a good starting point. Note that as beta
+    gets large, the window narrows, and so the number of samples needs to be
+    large enough to sample the increasingly narrow spike, otherwise NaNs will
+    be returned.
+
+    Most references to the Kaiser window come from the signal processing
+    literature, where it is used as one of many windowing functions for
+    smoothing values.  It is also known as an apodization (which means
+    "removing the foot", i.e. smoothing discontinuities at the beginning
+    and end of the sampled signal) or tapering function.
+
+    References
+    ----------
+    .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
+           digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
+           John Wiley and Sons, New York, (1966).
+    .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
+           University of Alberta Press, 1975, pp. 177-178.
+    .. [3] Wikipedia, "Window function",
+           https://en.wikipedia.org/wiki/Window_function
+    .. [4] F. J. Harris, "On the use of windows for harmonic analysis with the
+           discrete Fourier transform," Proceedings of the IEEE, vol. 66,
+           no. 1, pp. 51-83, Jan. 1978. :doi:`10.1109/PROC.1978.10837`.
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.kaiser(51, beta=14)
+    >>> plt.plot(window)
+    >>> plt.title(r"Kaiser window ($\beta$=14)")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title(r"Frequency response of the Kaiser window ($\beta$=14)")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    # Docstring adapted from NumPy's kaiser function
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    n = np.arange(0, M)
+    alpha = (M - 1) / 2.0
+    w = (special.i0(beta * np.sqrt(1 - ((n - alpha) / alpha) ** 2.0)) /
+         special.i0(beta))
+
+    return _truncate(w, needs_trunc)
+
+
+def kaiser_bessel_derived(M, beta, *, sym=True):
+    """Return a Kaiser-Bessel derived window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+        Note that this window is only defined for an even
+        number of points.
+    beta : float
+        Kaiser window shape parameter.
+    sym : bool, optional
+        This parameter only exists to comply with the interface offered by
+        the other window functions and to be callable by `get_window`.
+        When True (default), generates a symmetric window, for use in filter
+        design.
+
+    Returns
+    -------
+    w : ndarray
+        The window, normalized to fulfil the Princen-Bradley condition.
+
+    See Also
+    --------
+    kaiser
+
+    Notes
+    -----
+    It is designed to be suitable for use with the modified discrete cosine
+    transform (MDCT) and is mainly used in audio signal processing and
+    audio coding.
+
+    .. versionadded:: 1.9.0
+
+    References
+    ----------
+    .. [1] Bosi, Marina, and Richard E. Goldberg. Introduction to Digital
+           Audio Coding and Standards. Dordrecht: Kluwer, 2003.
+    .. [2] Wikipedia, "Kaiser window",
+           https://en.wikipedia.org/wiki/Kaiser_window
+
+    Examples
+    --------
+    Plot the Kaiser-Bessel derived window based on the wikipedia
+    reference [2]_:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> N = 50
+    >>> for alpha in [0.64, 2.55, 7.64, 31.83]:
+    ...     ax.plot(signal.windows.kaiser_bessel_derived(2*N, np.pi*alpha),
+    ...             label=f"{alpha=}")
+    >>> ax.grid(True)
+    >>> ax.set_title("Kaiser-Bessel derived window")
+    >>> ax.set_ylabel("Amplitude")
+    >>> ax.set_xlabel("Sample")
+    >>> ax.set_xticks([0, N, 2*N-1])
+    >>> ax.set_xticklabels(["0", "N", "2N+1"])  # doctest: +SKIP
+    >>> ax.set_yticks([0.0, 0.2, 0.4, 0.6, 0.707, 0.8, 1.0])
+    >>> fig.legend(loc="center")
+    >>> fig.tight_layout()
+    >>> fig.show()
+    """
+    if not sym:
+        raise ValueError(
+            "Kaiser-Bessel Derived windows are only defined for symmetric "
+            "shapes"
+        )
+    elif M < 1:
+        return np.array([])
+    elif M % 2:
+        raise ValueError(
+            "Kaiser-Bessel Derived windows are only defined for even number "
+            "of points"
+        )
+
+    kaiser_window = kaiser(M // 2 + 1, beta)
+    csum = np.cumsum(kaiser_window)
+    half_window = np.sqrt(csum[:-1] / csum[-1])
+    w = np.concatenate((half_window, half_window[::-1]), axis=0)
+    return w
+
+
+def gaussian(M, std, sym=True):
+    r"""Return a Gaussian window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    std : float
+        The standard deviation, sigma.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    The Gaussian window is defined as
+
+    .. math::  w(n) = e^{ -\frac{1}{2}\left(\frac{n}{\sigma}\right)^2 }
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.gaussian(51, std=7)
+    >>> plt.plot(window)
+    >>> plt.title(r"Gaussian window ($\sigma$=7)")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title(r"Frequency response of the Gaussian window ($\sigma$=7)")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    n = np.arange(0, M) - (M - 1.0) / 2.0
+    sig2 = 2 * std * std
+    w = np.exp(-n ** 2 / sig2)
+
+    return _truncate(w, needs_trunc)
+
+
+def general_gaussian(M, p, sig, sym=True):
+    r"""Return a window with a generalized Gaussian shape.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    p : float
+        Shape parameter.  p = 1 is identical to `gaussian`, p = 0.5 is
+        the same shape as the Laplace distribution.
+    sig : float
+        The standard deviation, sigma.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    The generalized Gaussian window is defined as
+
+    .. math::  w(n) = e^{ -\frac{1}{2}\left|\frac{n}{\sigma}\right|^{2p} }
+
+    the half-power point is at
+
+    .. math::  (2 \log(2))^{1/(2 p)} \sigma
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.general_gaussian(51, p=1.5, sig=7)
+    >>> plt.plot(window)
+    >>> plt.title(r"Generalized Gaussian window (p=1.5, $\sigma$=7)")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title(r"Freq. resp. of the gen. Gaussian "
+    ...           r"window (p=1.5, $\sigma$=7)")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    n = np.arange(0, M) - (M - 1.0) / 2.0
+    w = np.exp(-0.5 * np.abs(n / sig) ** (2 * p))
+
+    return _truncate(w, needs_trunc)
+
+
+# `chebwin` contributed by Kumar Appaiah.
+def chebwin(M, at, sym=True):
+    r"""Return a Dolph-Chebyshev window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    at : float
+        Attenuation (in dB).
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value always normalized to 1
+
+    Notes
+    -----
+    This window optimizes for the narrowest main lobe width for a given order
+    `M` and sidelobe equiripple attenuation `at`, using Chebyshev
+    polynomials.  It was originally developed by Dolph to optimize the
+    directionality of radio antenna arrays.
+
+    Unlike most windows, the Dolph-Chebyshev is defined in terms of its
+    frequency response:
+
+    .. math:: W(k) = \frac
+              {\cos\{M \cos^{-1}[\beta \cos(\frac{\pi k}{M})]\}}
+              {\cosh[M \cosh^{-1}(\beta)]}
+
+    where
+
+    .. math:: \beta = \cosh \left [\frac{1}{M}
+              \cosh^{-1}(10^\frac{A}{20}) \right ]
+
+    and 0 <= abs(k) <= M-1. A is the attenuation in decibels (`at`).
+
+    The time domain window is then generated using the IFFT, so
+    power-of-two `M` are the fastest to generate, and prime number `M` are
+    the slowest.
+
+    The equiripple condition in the frequency domain creates impulses in the
+    time domain, which appear at the ends of the window.
+
+    References
+    ----------
+    .. [1] C. Dolph, "A current distribution for broadside arrays which
+           optimizes the relationship between beam width and side-lobe level",
+           Proceedings of the IEEE, Vol. 34, Issue 6
+    .. [2] Peter Lynch, "The Dolph-Chebyshev Window: A Simple Optimal Filter",
+           American Meteorological Society (April 1997)
+           http://mathsci.ucd.ie/~plynch/Publications/Dolph.pdf
+    .. [3] F. J. Harris, "On the use of windows for harmonic analysis with the
+           discrete Fourier transforms", Proceedings of the IEEE, Vol. 66,
+           No. 1, January 1978
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.chebwin(51, at=100)
+    >>> plt.plot(window)
+    >>> plt.title("Dolph-Chebyshev window (100 dB)")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """
+    if np.abs(at) < 45:
+        warnings.warn("This window is not suitable for spectral analysis "
+                      "for attenuation values lower than about 45dB because "
+                      "the equivalent noise bandwidth of a Chebyshev window "
+                      "does not grow monotonically with increasing sidelobe "
+                      "attenuation when the attenuation is smaller than "
+                      "about 45 dB.",
+                      stacklevel=2)
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    # compute the parameter beta
+    order = M - 1.0
+    beta = np.cosh(1.0 / order * np.arccosh(10 ** (np.abs(at) / 20.)))
+    k = np.r_[0:M] * 1.0
+    x = beta * np.cos(np.pi * k / M)
+    # Find the window's DFT coefficients
+    # Use analytic definition of Chebyshev polynomial instead of expansion
+    # from scipy.special. Using the expansion in scipy.special leads to errors.
+    p = np.zeros(x.shape)
+    p[x > 1] = np.cosh(order * np.arccosh(x[x > 1]))
+    p[x < -1] = (2 * (M % 2) - 1) * np.cosh(order * np.arccosh(-x[x < -1]))
+    p[np.abs(x) <= 1] = np.cos(order * np.arccos(x[np.abs(x) <= 1]))
+
+    # Appropriate IDFT and filling up
+    # depending on even/odd M
+    if M % 2:
+        w = np.real(sp_fft.fft(p))
+        n = (M + 1) // 2
+        w = w[:n]
+        w = np.concatenate((w[n - 1:0:-1], w))
+    else:
+        p = p * np.exp(1.j * np.pi / M * np.r_[0:M])
+        w = np.real(sp_fft.fft(p))
+        n = M // 2 + 1
+        w = np.concatenate((w[n - 1:0:-1], w[1:n]))
+    w = w / max(w)
+
+    return _truncate(w, needs_trunc)
+
+
+def cosine(M, sym=True):
+    """Return a window with a simple cosine shape.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.cosine(51)
+    >>> plt.plot(window)
+    >>> plt.title("Cosine window")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2047) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the cosine window")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+    >>> plt.show()
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    w = np.sin(np.pi / M * (np.arange(0, M) + .5))
+
+    return _truncate(w, needs_trunc)
+
+
+def exponential(M, center=None, tau=1., sym=True):
+    r"""Return an exponential (or Poisson) window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    center : float, optional
+        Parameter defining the center location of the window function.
+        The default value if not given is ``center = (M-1) / 2``.  This
+        parameter must take its default value for symmetric windows.
+    tau : float, optional
+        Parameter defining the decay.  For ``center = 0`` use
+        ``tau = -(M-1) / ln(x)`` if ``x`` is the fraction of the window
+        remaining at the end.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    The Exponential window is defined as
+
+    .. math::  w(n) = e^{-|n-center| / \tau}
+
+    References
+    ----------
+    .. [1] S. Gade and H. Herlufsen, "Windows to FFT analysis (Part I)",
+           Technical Review 3, Bruel & Kjaer, 1987.
+
+    Examples
+    --------
+    Plot the symmetric window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> M = 51
+    >>> tau = 3.0
+    >>> window = signal.windows.exponential(M, tau=tau)
+    >>> plt.plot(window)
+    >>> plt.title("Exponential Window (tau=3.0)")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -35, 0])
+    >>> plt.title("Frequency response of the Exponential window (tau=3.0)")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    This function can also generate non-symmetric windows:
+
+    >>> tau2 = -(M-1) / np.log(0.01)
+    >>> window2 = signal.windows.exponential(M, 0, tau2, False)
+    >>> plt.figure()
+    >>> plt.plot(window2)
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+    """
+    if sym and center is not None:
+        raise ValueError("If sym==True, center must be None.")
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    if center is None:
+        center = (M-1) / 2
+
+    n = np.arange(0, M)
+    w = np.exp(-np.abs(n-center) / tau)
+
+    return _truncate(w, needs_trunc)
+
+
+def taylor(M, nbar=4, sll=30, norm=True, sym=True):
+    """
+    Return a Taylor window.
+
+    The Taylor window taper function approximates the Dolph-Chebyshev window's
+    constant sidelobe level for a parameterized number of near-in sidelobes,
+    but then allows a taper beyond [2]_.
+
+    The SAR (synthetic aperture radar) community commonly uses Taylor
+    weighting for image formation processing because it provides strong,
+    selectable sidelobe suppression with minimum broadening of the
+    mainlobe [1]_.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    nbar : int, optional
+        Number of nearly constant level sidelobes adjacent to the mainlobe.
+    sll : float, optional
+        Desired suppression of sidelobe level in decibels (dB) relative to the
+        DC gain of the mainlobe. This should be a positive number.
+    norm : bool, optional
+        When True (default), divides the window by the largest (middle) value
+        for odd-length windows or the value that would occur between the two
+        repeated middle values for even-length windows such that all values
+        are less than or equal to 1. When False the DC gain will remain at 1
+        (0 dB) and the sidelobes will be `sll` dB down.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    out : array
+        The window. When `norm` is True (default), the maximum value is
+        normalized to 1 (though the value 1 does not appear if `M` is
+        even and `sym` is True).
+
+    See Also
+    --------
+    chebwin, kaiser, bartlett, blackman, hamming, hann
+
+    References
+    ----------
+    .. [1] W. Carrara, R. Goodman, and R. Majewski, "Spotlight Synthetic
+           Aperture Radar: Signal Processing Algorithms" Pages 512-513,
+           July 1995.
+    .. [2] Armin Doerry, "Catalog of Window Taper Functions for
+           Sidelobe Control", 2017.
+           https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf
+
+    Examples
+    --------
+    Plot the window and its frequency response:
+
+    >>> import numpy as np
+    >>> from scipy import signal
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+
+    >>> window = signal.windows.taylor(51, nbar=20, sll=100, norm=False)
+    >>> plt.plot(window)
+    >>> plt.title("Taylor window (100 dB)")
+    >>> plt.ylabel("Amplitude")
+    >>> plt.xlabel("Sample")
+
+    >>> plt.figure()
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> plt.plot(freq, response)
+    >>> plt.axis([-0.5, 0.5, -120, 0])
+    >>> plt.title("Frequency response of the Taylor window (100 dB)")
+    >>> plt.ylabel("Normalized magnitude [dB]")
+    >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+    """  # noqa: E501
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    # Original text uses a negative sidelobe level parameter and then negates
+    # it in the calculation of B. To keep consistent with other methods we
+    # assume the sidelobe level parameter to be positive.
+    B = 10**(sll / 20)
+    A = np.arccosh(B) / np.pi
+    s2 = nbar**2 / (A**2 + (nbar - 0.5)**2)
+    ma = np.arange(1, nbar)
+
+    Fm = np.empty(nbar-1)
+    signs = np.empty_like(ma)
+    signs[::2] = 1
+    signs[1::2] = -1
+    m2 = ma*ma
+    for mi, m in enumerate(ma):
+        numer = signs[mi] * np.prod(1 - m2[mi]/s2/(A**2 + (ma - 0.5)**2))
+        denom = 2 * np.prod(1 - m2[mi]/m2[:mi]) * np.prod(1 - m2[mi]/m2[mi+1:])
+        Fm[mi] = numer / denom
+
+    def W(n):
+        return 1 + 2*np.dot(Fm, np.cos(
+            2*np.pi*ma[:, np.newaxis]*(n-M/2.+0.5)/M))
+
+    w = W(np.arange(M))
+
+    # normalize (Note that this is not described in the original text [1])
+    if norm:
+        scale = 1.0 / W((M - 1) / 2)
+        w *= scale
+
+    return _truncate(w, needs_trunc)
+
+
+def dpss(M, NW, Kmax=None, sym=True, norm=None, return_ratios=False):
+    """
+    Compute the Discrete Prolate Spheroidal Sequences (DPSS).
+
+    DPSS (or Slepian sequences) are often used in multitaper power spectral
+    density estimation (see [1]_). The first window in the sequence can be
+    used to maximize the energy concentration in the main lobe, and is also
+    called the Slepian window.
+
+    Parameters
+    ----------
+    M : int
+        Window length.
+    NW : float
+        Standardized half bandwidth corresponding to ``2*NW = BW/f0 = BW*M*dt``
+        where ``dt`` is taken as 1.
+    Kmax : int | None, optional
+        Number of DPSS windows to return (orders ``0`` through ``Kmax-1``).
+        If None (default), return only a single window of shape ``(M,)``
+        instead of an array of windows of shape ``(Kmax, M)``.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+    norm : {2, 'approximate', 'subsample'} | None, optional
+        If 'approximate' or 'subsample', then the windows are normalized by the
+        maximum, and a correction scale-factor for even-length windows
+        is applied either using ``M**2/(M**2+NW)`` ("approximate") or
+        a FFT-based subsample shift ("subsample"), see Notes for details.
+        If None, then "approximate" is used when ``Kmax=None`` and 2 otherwise
+        (which uses the l2 norm).
+    return_ratios : bool, optional
+        If True, also return the concentration ratios in addition to the
+        windows.
+
+    Returns
+    -------
+    v : ndarray, shape (Kmax, M) or (M,)
+        The DPSS windows. Will be 1D if `Kmax` is None.
+    r : ndarray, shape (Kmax,) or float, optional
+        The concentration ratios for the windows. Only returned if
+        `return_ratios` evaluates to True. Will be 0D if `Kmax` is None.
+
+    Notes
+    -----
+    This computation uses the tridiagonal eigenvector formulation given
+    in [2]_.
+
+    The default normalization for ``Kmax=None``, i.e. window-generation mode,
+    simply using the l-infinity norm would create a window with two unity
+    values, which creates slight normalization differences between even and odd
+    orders. The approximate correction of ``M**2/float(M**2+NW)`` for even
+    sample numbers is used to counteract this effect (see Examples below).
+
+    For very long signals (e.g., 1e6 elements), it can be useful to compute
+    windows orders of magnitude shorter and use interpolation (e.g.,
+    `scipy.interpolate.interp1d`) to obtain tapers of length `M`,
+    but this in general will not preserve orthogonality between the tapers.
+
+    .. versionadded:: 1.1
+
+    References
+    ----------
+    .. [1] Percival DB, Walden WT. Spectral Analysis for Physical Applications:
+       Multitaper and Conventional Univariate Techniques.
+       Cambridge University Press; 1993.
+    .. [2] Slepian, D. Prolate spheroidal wave functions, Fourier analysis, and
+       uncertainty V: The discrete case. Bell System Technical Journal,
+       Volume 57 (1978), 1371430.
+    .. [3] Kaiser, JF, Schafer RW. On the Use of the I0-Sinh Window for
+       Spectrum Analysis. IEEE Transactions on Acoustics, Speech and
+       Signal Processing. ASSP-28 (1): 105-107; 1980.
+
+    Examples
+    --------
+    We can compare the window to `kaiser`, which was invented as an alternative
+    that was easier to calculate [3]_ (example adapted from
+    `here `_):
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.signal import windows, freqz
+    >>> M = 51
+    >>> fig, axes = plt.subplots(3, 2, figsize=(5, 7))
+    >>> for ai, alpha in enumerate((1, 3, 5)):
+    ...     win_dpss = windows.dpss(M, alpha)
+    ...     beta = alpha*np.pi
+    ...     win_kaiser = windows.kaiser(M, beta)
+    ...     for win, c in ((win_dpss, 'k'), (win_kaiser, 'r')):
+    ...         win /= win.sum()
+    ...         axes[ai, 0].plot(win, color=c, lw=1.)
+    ...         axes[ai, 0].set(xlim=[0, M-1], title=r'$\\alpha$ = %s' % alpha,
+    ...                         ylabel='Amplitude')
+    ...         w, h = freqz(win)
+    ...         axes[ai, 1].plot(w, 20 * np.log10(np.abs(h)), color=c, lw=1.)
+    ...         axes[ai, 1].set(xlim=[0, np.pi],
+    ...                         title=r'$\\beta$ = %0.2f' % beta,
+    ...                         ylabel='Magnitude (dB)')
+    >>> for ax in axes.ravel():
+    ...     ax.grid(True)
+    >>> axes[2, 1].legend(['DPSS', 'Kaiser'])
+    >>> fig.tight_layout()
+    >>> plt.show()
+
+    And here are examples of the first four windows, along with their
+    concentration ratios:
+
+    >>> M = 512
+    >>> NW = 2.5
+    >>> win, eigvals = windows.dpss(M, NW, 4, return_ratios=True)
+    >>> fig, ax = plt.subplots(1)
+    >>> ax.plot(win.T, linewidth=1.)
+    >>> ax.set(xlim=[0, M-1], ylim=[-0.1, 0.1], xlabel='Samples',
+    ...        title='DPSS, M=%d, NW=%0.1f' % (M, NW))
+    >>> ax.legend(['win[%d] (%0.4f)' % (ii, ratio)
+    ...            for ii, ratio in enumerate(eigvals)])
+    >>> fig.tight_layout()
+    >>> plt.show()
+
+    Using a standard :math:`l_{\\infty}` norm would produce two unity values
+    for even `M`, but only one unity value for odd `M`. This produces uneven
+    window power that can be counteracted by the approximate correction
+    ``M**2/float(M**2+NW)``, which can be selected by using
+    ``norm='approximate'`` (which is the same as ``norm=None`` when
+    ``Kmax=None``, as is the case here). Alternatively, the slower
+    ``norm='subsample'`` can be used, which uses subsample shifting in the
+    frequency domain (FFT) to compute the correction:
+
+    >>> Ms = np.arange(1, 41)
+    >>> factors = (50, 20, 10, 5, 2.0001)
+    >>> energy = np.empty((3, len(Ms), len(factors)))
+    >>> for mi, M in enumerate(Ms):
+    ...     for fi, factor in enumerate(factors):
+    ...         NW = M / float(factor)
+    ...         # Corrected using empirical approximation (default)
+    ...         win = windows.dpss(M, NW)
+    ...         energy[0, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
+    ...         # Corrected using subsample shifting
+    ...         win = windows.dpss(M, NW, norm='subsample')
+    ...         energy[1, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
+    ...         # Uncorrected (using l-infinity norm)
+    ...         win /= win.max()
+    ...         energy[2, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
+    >>> fig, ax = plt.subplots(1)
+    >>> hs = ax.plot(Ms, energy[2], '-o', markersize=4,
+    ...              markeredgecolor='none')
+    >>> leg = [hs[-1]]
+    >>> for hi, hh in enumerate(hs):
+    ...     h1 = ax.plot(Ms, energy[0, :, hi], '-o', markersize=4,
+    ...                  color=hh.get_color(), markeredgecolor='none',
+    ...                  alpha=0.66)
+    ...     h2 = ax.plot(Ms, energy[1, :, hi], '-o', markersize=4,
+    ...                  color=hh.get_color(), markeredgecolor='none',
+    ...                  alpha=0.33)
+    ...     if hi == len(hs) - 1:
+    ...         leg.insert(0, h1[0])
+    ...         leg.insert(0, h2[0])
+    >>> ax.set(xlabel='M (samples)', ylabel=r'Power / $\\sqrt{M}$')
+    >>> ax.legend(leg, ['Uncorrected', r'Corrected: $\\frac{M^2}{M^2+NW}$',
+    ...                 'Corrected (subsample)'])
+    >>> fig.tight_layout()
+
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    if norm is None:
+        norm = 'approximate' if Kmax is None else 2
+    known_norms = (2, 'approximate', 'subsample')
+    if norm not in known_norms:
+        raise ValueError(f'norm must be one of {known_norms}, got {norm}')
+    if Kmax is None:
+        singleton = True
+        Kmax = 1
+    else:
+        singleton = False
+    Kmax = operator.index(Kmax)
+    if not 0 < Kmax <= M:
+        raise ValueError('Kmax must be greater than 0 and less than M')
+    if NW >= M/2.:
+        raise ValueError('NW must be less than M/2.')
+    if NW <= 0:
+        raise ValueError('NW must be positive')
+    M, needs_trunc = _extend(M, sym)
+    W = float(NW) / M
+    nidx = np.arange(M)
+
+    # Here we want to set up an optimization problem to find a sequence
+    # whose energy is maximally concentrated within band [-W,W].
+    # Thus, the measure lambda(T,W) is the ratio between the energy within
+    # that band, and the total energy. This leads to the eigen-system
+    # (A - (l1)I)v = 0, where the eigenvector corresponding to the largest
+    # eigenvalue is the sequence with maximally concentrated energy. The
+    # collection of eigenvectors of this system are called Slepian
+    # sequences, or discrete prolate spheroidal sequences (DPSS). Only the
+    # first K, K = 2NW/dt orders of DPSS will exhibit good spectral
+    # concentration
+    # [see https://en.wikipedia.org/wiki/Spectral_concentration_problem]
+
+    # Here we set up an alternative symmetric tri-diagonal eigenvalue
+    # problem such that
+    # (B - (l2)I)v = 0, and v are our DPSS (but eigenvalues l2 != l1)
+    # the main diagonal = ([M-1-2*t]/2)**2 cos(2PIW), t=[0,1,2,...,M-1]
+    # and the first off-diagonal = t(M-t)/2, t=[1,2,...,M-1]
+    # [see Percival and Walden, 1993]
+    d = ((M - 1 - 2 * nidx) / 2.) ** 2 * np.cos(2 * np.pi * W)
+    e = nidx[1:] * (M - nidx[1:]) / 2.
+
+    # only calculate the highest Kmax eigenvalues
+    w, windows = linalg.eigh_tridiagonal(
+        d, e, select='i', select_range=(M - Kmax, M - 1))
+    w = w[::-1]
+    windows = windows[:, ::-1].T
+
+    # By convention (Percival and Walden, 1993 pg 379)
+    # * symmetric tapers (k=0,2,4,...) should have a positive average.
+    fix_even = (windows[::2].sum(axis=1) < 0)
+    for i, f in enumerate(fix_even):
+        if f:
+            windows[2 * i] *= -1
+    # * antisymmetric tapers should begin with a positive lobe
+    #   (this depends on the definition of "lobe", here we'll take the first
+    #   point above the numerical noise, which should be good enough for
+    #   sufficiently smooth functions, and more robust than relying on an
+    #   algorithm that uses max(abs(w)), which is susceptible to numerical
+    #   noise problems)
+    thresh = max(1e-7, 1. / M)
+    for i, w in enumerate(windows[1::2]):
+        if w[w * w > thresh][0] < 0:
+            windows[2 * i + 1] *= -1
+
+    # Now find the eigenvalues of the original spectral concentration problem
+    # Use the autocorr sequence technique from Percival and Walden, 1993 pg 390
+    if return_ratios:
+        dpss_rxx = _fftautocorr(windows)
+        r = 4 * W * np.sinc(2 * W * nidx)
+        r[0] = 2 * W
+        ratios = np.dot(dpss_rxx, r)
+        if singleton:
+            ratios = ratios[0]
+    # Deal with sym and Kmax=None
+    if norm != 2:
+        windows /= windows.max()
+        if M % 2 == 0:
+            if norm == 'approximate':
+                correction = M**2 / float(M**2 + NW)
+            else:
+                s = sp_fft.rfft(windows[0])
+                shift = -(1 - 1./M) * np.arange(1, M//2 + 1)
+                s[1:] *= 2 * np.exp(-1j * np.pi * shift)
+                correction = M / s.real.sum()
+            windows *= correction
+    # else we're already l2 normed, so do nothing
+    if needs_trunc:
+        windows = windows[:, :-1]
+    if singleton:
+        windows = windows[0]
+    return (windows, ratios) if return_ratios else windows
+
+
+def lanczos(M, *, sym=True):
+    r"""Return a Lanczos window also known as a sinc window.
+
+    Parameters
+    ----------
+    M : int
+        Number of points in the output window. If zero, an empty array
+        is returned. An exception is thrown when it is negative.
+    sym : bool, optional
+        When True (default), generates a symmetric window, for use in filter
+        design.
+        When False, generates a periodic window, for use in spectral analysis.
+
+    Returns
+    -------
+    w : ndarray
+        The window, with the maximum value normalized to 1 (though the value 1
+        does not appear if `M` is even and `sym` is True).
+
+    Notes
+    -----
+    The Lanczos window is defined as
+
+    .. math::  w(n) = sinc \left( \frac{2n}{M - 1} - 1 \right)
+
+    where
+
+    .. math::  sinc(x) = \frac{\sin(\pi x)}{\pi x}
+
+    The Lanczos window has reduced Gibbs oscillations and is widely used for
+    filtering climate timeseries with good properties in the physical and
+    spectral domains.
+
+    .. versionadded:: 1.10
+
+    References
+    ----------
+    .. [1] Lanczos, C., and Teichmann, T. (1957). Applied analysis.
+           Physics Today, 10, 44.
+    .. [2] Duchon C. E. (1979) Lanczos Filtering in One and Two Dimensions.
+           Journal of Applied Meteorology, Vol 18, pp 1016-1022.
+    .. [3] Thomson, R. E. and Emery, W. J. (2014) Data Analysis Methods in
+           Physical Oceanography (Third Edition), Elsevier, pp 593-637.
+    .. [4] Wikipedia, "Window function",
+           http://en.wikipedia.org/wiki/Window_function
+
+    Examples
+    --------
+    Plot the window
+
+    >>> import numpy as np
+    >>> from scipy.signal.windows import lanczos
+    >>> from scipy.fft import fft, fftshift
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1)
+    >>> window = lanczos(51)
+    >>> ax.plot(window)
+    >>> ax.set_title("Lanczos window")
+    >>> ax.set_ylabel("Amplitude")
+    >>> ax.set_xlabel("Sample")
+    >>> fig.tight_layout()
+    >>> plt.show()
+
+    and its frequency response:
+
+    >>> fig, ax = plt.subplots(1)
+    >>> A = fft(window, 2048) / (len(window)/2.0)
+    >>> freq = np.linspace(-0.5, 0.5, len(A))
+    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+    >>> ax.plot(freq, response)
+    >>> ax.set_xlim(-0.5, 0.5)
+    >>> ax.set_ylim(-120, 0)
+    >>> ax.set_title("Frequency response of the lanczos window")
+    >>> ax.set_ylabel("Normalized magnitude [dB]")
+    >>> ax.set_xlabel("Normalized frequency [cycles per sample]")
+    >>> fig.tight_layout()
+    >>> plt.show()
+    """
+    if _len_guards(M):
+        return np.ones(M)
+    M, needs_trunc = _extend(M, sym)
+
+    # To make sure that the window is symmetric, we concatenate the right hand
+    # half of the window and the flipped one which is the left hand half of
+    # the window.
+    def _calc_right_side_lanczos(n, m):
+        return np.sinc(2. * np.arange(n, m) / (m - 1) - 1.0)
+
+    if M % 2 == 0:
+        wh = _calc_right_side_lanczos(M/2, M)
+        w = np.r_[np.flip(wh), wh]
+    else:
+        wh = _calc_right_side_lanczos((M+1)/2, M)
+        w = np.r_[np.flip(wh), 1.0, wh]
+
+    return _truncate(w, needs_trunc)
+
+
+def _fftautocorr(x):
+    """Compute the autocorrelation of a real array and crop the result."""
+    N = x.shape[-1]
+    use_N = sp_fft.next_fast_len(2*N-1)
+    x_fft = sp_fft.rfft(x, use_N, axis=-1)
+    cxy = sp_fft.irfft(x_fft * x_fft.conj(), n=use_N)[:, :N]
+    # Or equivalently (but in most cases slower):
+    # cxy = np.array([np.convolve(xx, yy[::-1], mode='full')
+    #                 for xx, yy in zip(x, x)])[:, N-1:2*N-1]
+    return cxy
+
+
+_win_equiv_raw = {
+    ('barthann', 'brthan', 'bth'): (barthann, False),
+    ('bartlett', 'bart', 'brt'): (bartlett, False),
+    ('blackman', 'black', 'blk'): (blackman, False),
+    ('blackmanharris', 'blackharr', 'bkh'): (blackmanharris, False),
+    ('bohman', 'bman', 'bmn'): (bohman, False),
+    ('boxcar', 'box', 'ones',
+        'rect', 'rectangular'): (boxcar, False),
+    ('chebwin', 'cheb'): (chebwin, True),
+    ('cosine', 'halfcosine'): (cosine, False),
+    ('dpss',): (dpss, True),
+    ('exponential', 'poisson'): (exponential, False),
+    ('flattop', 'flat', 'flt'): (flattop, False),
+    ('gaussian', 'gauss', 'gss'): (gaussian, True),
+    ('general cosine', 'general_cosine'): (general_cosine, True),
+    ('general gaussian', 'general_gaussian',
+        'general gauss', 'general_gauss', 'ggs'): (general_gaussian, True),
+    ('general hamming', 'general_hamming'): (general_hamming, True),
+    ('hamming', 'hamm', 'ham'): (hamming, False),
+    ('hann', 'han'): (hann, False),
+    ('kaiser', 'ksr'): (kaiser, True),
+    ('kaiser bessel derived', 'kbd'): (kaiser_bessel_derived, True),
+    ('lanczos', 'sinc'): (lanczos, False),
+    ('nuttall', 'nutl', 'nut'): (nuttall, False),
+    ('parzen', 'parz', 'par'): (parzen, False),
+    ('taylor', 'taylorwin'): (taylor, False),
+    ('triangle', 'triang', 'tri'): (triang, False),
+    ('tukey', 'tuk'): (tukey, False),
+}
+
+# Fill dict with all valid window name strings
+_win_equiv = {}
+for k, v in _win_equiv_raw.items():
+    for key in k:
+        _win_equiv[key] = v[0]
+
+# Keep track of which windows need additional parameters
+_needs_param = set()
+for k, v in _win_equiv_raw.items():
+    if v[1]:
+        _needs_param.update(k)
+
+
+def get_window(window, Nx, fftbins=True):
+    """
+    Return a window of a given length and type.
+
+    Parameters
+    ----------
+    window : string, float, or tuple
+        The type of window to create. See below for more details.
+    Nx : int
+        The number of samples in the window.
+    fftbins : bool, optional
+        If True (default), create a "periodic" window, ready to use with
+        `ifftshift` and be multiplied by the result of an FFT (see also
+        :func:`~scipy.fft.fftfreq`).
+        If False, create a "symmetric" window, for use in filter design.
+
+    Returns
+    -------
+    get_window : ndarray
+        Returns a window of length `Nx` and type `window`
+
+    Notes
+    -----
+    Window types:
+
+    - `~scipy.signal.windows.boxcar`
+    - `~scipy.signal.windows.triang`
+    - `~scipy.signal.windows.blackman`
+    - `~scipy.signal.windows.hamming`
+    - `~scipy.signal.windows.hann`
+    - `~scipy.signal.windows.bartlett`
+    - `~scipy.signal.windows.flattop`
+    - `~scipy.signal.windows.parzen`
+    - `~scipy.signal.windows.bohman`
+    - `~scipy.signal.windows.blackmanharris`
+    - `~scipy.signal.windows.nuttall`
+    - `~scipy.signal.windows.barthann`
+    - `~scipy.signal.windows.cosine`
+    - `~scipy.signal.windows.exponential`
+    - `~scipy.signal.windows.tukey`
+    - `~scipy.signal.windows.taylor`
+    - `~scipy.signal.windows.lanczos`
+    - `~scipy.signal.windows.kaiser` (needs beta)
+    - `~scipy.signal.windows.kaiser_bessel_derived` (needs beta)
+    - `~scipy.signal.windows.gaussian` (needs standard deviation)
+    - `~scipy.signal.windows.general_cosine` (needs weighting coefficients)
+    - `~scipy.signal.windows.general_gaussian` (needs power, width)
+    - `~scipy.signal.windows.general_hamming` (needs window coefficient)
+    - `~scipy.signal.windows.dpss` (needs normalized half-bandwidth)
+    - `~scipy.signal.windows.chebwin` (needs attenuation)
+
+
+    If the window requires no parameters, then `window` can be a string.
+
+    If the window requires parameters, then `window` must be a tuple
+    with the first argument the string name of the window, and the next
+    arguments the needed parameters.
+
+    If `window` is a floating point number, it is interpreted as the beta
+    parameter of the `~scipy.signal.windows.kaiser` window.
+
+    Each of the window types listed above is also the name of
+    a function that can be called directly to create a window of
+    that type.
+
+    Examples
+    --------
+    >>> from scipy import signal
+    >>> signal.get_window('triang', 7)
+    array([ 0.125,  0.375,  0.625,  0.875,  0.875,  0.625,  0.375])
+    >>> signal.get_window(('kaiser', 4.0), 9)
+    array([ 0.08848053,  0.29425961,  0.56437221,  0.82160913,  0.97885093,
+            0.97885093,  0.82160913,  0.56437221,  0.29425961])
+    >>> signal.get_window(('exponential', None, 1.), 9)
+    array([ 0.011109  ,  0.03019738,  0.082085  ,  0.22313016,  0.60653066,
+            0.60653066,  0.22313016,  0.082085  ,  0.03019738])
+    >>> signal.get_window(4.0, 9)
+    array([ 0.08848053,  0.29425961,  0.56437221,  0.82160913,  0.97885093,
+            0.97885093,  0.82160913,  0.56437221,  0.29425961])
+
+    """
+    sym = not fftbins
+    try:
+        beta = float(window)
+    except (TypeError, ValueError) as e:
+        args = ()
+        if isinstance(window, tuple):
+            winstr = window[0]
+            if len(window) > 1:
+                args = window[1:]
+        elif isinstance(window, str):
+            if window in _needs_param:
+                raise ValueError("The '" + window + "' window needs one or "
+                                 "more parameters -- pass a tuple.") from e
+            else:
+                winstr = window
+        else:
+            raise ValueError(
+                f"{str(type(window))} as window type is not supported.") from e
+
+        try:
+            winfunc = _win_equiv[winstr]
+        except KeyError as e:
+            raise ValueError("Unknown window type.") from e
+
+        if winfunc is dpss:
+            params = (Nx,) + args + (None,)
+        else:
+            params = (Nx,) + args
+    else:
+        winfunc = kaiser
+        params = (Nx, beta)
+
+    return winfunc(*params, sym=sym)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/windows.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..6858f71aceeb29ca6110864d01fb250e8c8ce403
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/signal/windows/windows.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.signal.windows` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
+    'blackmanharris', 'flattop', 'bartlett', 'barthann',
+    'hamming', 'kaiser', 'gaussian', 'general_cosine',
+    'general_gaussian', 'general_hamming', 'chebwin', 'cosine',
+    'hann', 'exponential', 'tukey', 'taylor', 'dpss', 'get_window',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="signal.windows", module="windows",
+                                   private_modules=["_windows"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..18fe7e011db102f57a8263d1db343818715aeeee
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__init__.py
@@ -0,0 +1,331 @@
+"""
+===================================
+Sparse arrays (:mod:`scipy.sparse`)
+===================================
+
+.. currentmodule:: scipy.sparse
+
+.. toctree::
+   :hidden:
+
+   sparse.csgraph
+   sparse.linalg
+   sparse.migration_to_sparray
+
+SciPy 2-D sparse array package for numeric data.
+
+.. note::
+
+   This package is switching to an array interface, compatible with
+   NumPy arrays, from the older matrix interface.  We recommend that
+   you use the array objects (`bsr_array`, `coo_array`, etc.) for
+   all new work.
+
+   When using the array interface, please note that:
+
+   - ``x * y`` no longer performs matrix multiplication, but
+     element-wise multiplication (just like with NumPy arrays).  To
+     make code work with both arrays and matrices, use ``x @ y`` for
+     matrix multiplication.
+   - Operations such as ``sum``, that used to produce dense matrices, now
+     produce arrays, whose multiplication behavior differs similarly.
+   - Sparse arrays use array style *slicing* operations, returning scalars,
+     1D, or 2D sparse arrays. If you need 2D results, use an appropriate index.
+     E.g. ``A[:, i, None]`` or ``A[:, [i]]``.
+
+   The construction utilities (`eye`, `kron`, `random`, `diags`, etc.)
+   have appropriate replacements (see :ref:`sparse-construction-functions`).
+
+   For more information see
+   :ref:`Migration from spmatrix to sparray `.
+
+
+Submodules
+==========
+
+.. autosummary::
+
+   csgraph - Compressed sparse graph routines
+   linalg - Sparse linear algebra routines
+
+
+Sparse array classes
+====================
+
+.. autosummary::
+   :toctree: generated/
+
+   bsr_array - Block Sparse Row array
+   coo_array - A sparse array in COOrdinate format
+   csc_array - Compressed Sparse Column array
+   csr_array - Compressed Sparse Row array
+   dia_array - Sparse array with DIAgonal storage
+   dok_array - Dictionary Of Keys based sparse array
+   lil_array - Row-based list of lists sparse array
+   sparray - Sparse array base class
+
+.. _sparse-construction-functions:
+
+Building sparse arrays
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   diags_array - Return a sparse array from diagonals
+   eye_array - Sparse MxN array whose k-th diagonal is all ones
+   random_array - Random values in a given shape array
+   block_array - Build a sparse array from sub-blocks
+
+.. _combining-arrays:
+
+Combining arrays
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   kron - Kronecker product of two sparse arrays
+   kronsum - Kronecker sum of sparse arrays
+   block_diag - Build a block diagonal sparse array
+   tril - Lower triangular portion of a sparse array
+   triu - Upper triangular portion of a sparse array
+   hstack - Stack sparse arrays horizontally (column wise)
+   vstack - Stack sparse arrays vertically (row wise)
+
+Sparse tools
+------------
+
+.. autosummary::
+   :toctree: generated/
+
+   save_npz - Save a sparse array to a file using ``.npz`` format.
+   load_npz - Load a sparse array from a file using ``.npz`` format.
+   find - Return the indices and values of the nonzero elements
+   get_index_dtype - determine a good dtype for index arrays.
+   safely_cast_index_arrays - cast index array dtype or raise if shape too big
+
+Identifying sparse arrays
+-------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   issparse - Check if the argument is a sparse object (array or matrix).
+
+
+Sparse matrix classes
+=====================
+
+.. autosummary::
+   :toctree: generated/
+
+   bsr_matrix - Block Sparse Row matrix
+   coo_matrix - A sparse matrix in COOrdinate format
+   csc_matrix - Compressed Sparse Column matrix
+   csr_matrix - Compressed Sparse Row matrix
+   dia_matrix - Sparse matrix with DIAgonal storage
+   dok_matrix - Dictionary Of Keys based sparse matrix
+   lil_matrix - Row-based list of lists sparse matrix
+   spmatrix - Sparse matrix base class
+
+Building sparse matrices
+------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   eye - Sparse MxN matrix whose k-th diagonal is all ones
+   identity - Identity matrix in sparse matrix format
+   diags - Return a sparse matrix from diagonals
+   spdiags - Return a sparse matrix from diagonals
+   bmat - Build a sparse matrix from sparse sub-blocks
+   random - Random values in a given shape matrix
+   rand - Random values in a given shape matrix (old interface)
+
+**Combining matrices use the same functions as for** :ref:`combining-arrays`.
+
+Identifying sparse matrices
+---------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   issparse
+   isspmatrix
+   isspmatrix_csc
+   isspmatrix_csr
+   isspmatrix_bsr
+   isspmatrix_lil
+   isspmatrix_dok
+   isspmatrix_coo
+   isspmatrix_dia
+
+
+Warnings
+========
+
+.. autosummary::
+   :toctree: generated/
+
+   SparseEfficiencyWarning
+   SparseWarning
+
+
+Usage information
+=================
+
+There are seven available sparse array types:
+
+    1. csc_array: Compressed Sparse Column format
+    2. csr_array: Compressed Sparse Row format
+    3. bsr_array: Block Sparse Row format
+    4. lil_array: List of Lists format
+    5. dok_array: Dictionary of Keys format
+    6. coo_array: COOrdinate format (aka IJV, triplet format)
+    7. dia_array: DIAgonal format
+
+To construct an array efficiently, use any of `coo_array`,
+`dok_array` or `lil_array`. `dok_array` and `lil_array`
+support basic slicing and fancy indexing with a similar syntax
+to NumPy arrays. The COO format does not support indexing (yet)
+but can also be used to efficiently construct arrays using coord
+and value info.
+
+Despite their similarity to NumPy arrays, it is **strongly discouraged**
+to use NumPy functions directly on these arrays because NumPy typically
+treats them as generic Python objects rather than arrays, leading to
+unexpected (and incorrect) results. If you do want to apply a NumPy
+function to these arrays, first check if SciPy has its own implementation
+for the given sparse array class, or **convert the sparse array to
+a NumPy array** (e.g., using the `toarray` method of the class)
+before applying the method.
+
+All conversions among the CSR, CSC, and COO formats are efficient,
+linear-time operations.
+
+To perform manipulations such as multiplication or inversion, first
+convert the array to either CSC or CSR format. The `lil_array`
+format is row-based, so conversion to CSR is efficient, whereas
+conversion to CSC is less so.
+
+Matrix vector product
+---------------------
+
+To do a vector product between a 2D sparse array and a vector use
+the matmul operator (i.e., ``@``) which performs a dot product (like the
+``dot`` method):
+
+>>> import numpy as np
+>>> from scipy.sparse import csr_array
+>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+>>> v = np.array([1, 0, -1])
+>>> A @ v
+array([ 1, -3, -1], dtype=int64)
+
+The CSR format is especially suitable for fast matrix vector products.
+
+Example 1
+---------
+
+Construct a 1000x1000 `lil_array` and add some values to it:
+
+>>> from scipy.sparse import lil_array
+>>> from scipy.sparse.linalg import spsolve
+>>> from numpy.linalg import solve, norm
+>>> from numpy.random import rand
+
+>>> A = lil_array((1000, 1000))
+>>> A[0, :100] = rand(100)
+>>> A.setdiag(rand(1000))
+
+Now convert it to CSR format and solve A x = b for x:
+
+>>> A = A.tocsr()
+>>> b = rand(1000)
+>>> x = spsolve(A, b)
+
+Convert it to a dense array and solve, and check that the result
+is the same:
+
+>>> x_ = solve(A.toarray(), b)
+
+Now we can compute norm of the error with:
+
+>>> err = norm(x-x_)
+>>> err < 1e-10
+True
+
+It should be small :)
+
+
+Example 2
+---------
+
+Construct an array in COO format:
+
+>>> from scipy import sparse
+>>> from numpy import array
+>>> I = array([0,3,1,0])
+>>> J = array([0,3,1,2])
+>>> V = array([4,5,7,9])
+>>> A = sparse.coo_array((V,(I,J)),shape=(4,4))
+
+Notice that the indices do not need to be sorted.
+
+Duplicate (i,j) entries are summed when converting to CSR or CSC.
+
+>>> I = array([0,0,1,3,1,0,0])
+>>> J = array([0,2,1,3,1,0,0])
+>>> V = array([1,1,1,1,1,1,1])
+>>> B = sparse.coo_array((V,(I,J)),shape=(4,4)).tocsr()
+
+This is useful for constructing finite-element stiffness and mass matrices.
+
+Further details
+---------------
+
+CSR column indices are not necessarily sorted. Likewise for CSC row
+indices. Use the ``.sorted_indices()`` and ``.sort_indices()`` methods when
+sorted indices are required (e.g., when passing data to other libraries).
+
+"""
+
+# Original code by Travis Oliphant.
+# Modified and extended by Ed Schofield, Robert Cimrman,
+# Nathan Bell, and Jake Vanderplas.
+
+import warnings as _warnings
+
+from ._base import *
+from ._csr import *
+from ._csc import *
+from ._lil import *
+from ._dok import *
+from ._coo import *
+from ._dia import *
+from ._bsr import *
+from ._construct import *
+from ._extract import *
+from ._matrix import spmatrix
+from ._matrix_io import *
+from ._sputils import get_index_dtype, safely_cast_index_arrays
+
+# For backward compatibility with v0.19.
+from . import csgraph
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+    base, bsr, compressed, construct, coo, csc, csr, data, dia, dok, extract,
+    lil, sparsetools, sputils
+)
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+# Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15
+msg = 'the matrix subclass is not the recommended way'
+_warnings.filterwarnings('ignore', message=msg)
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f7a31d9d62e7bdf42fb8d8bd8d072a94c8c2ad4
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63ce8efe75bacfad794fec43b70f1e926965bbf7
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db01e2a012cf73737afc685c5269d46e44c0c723
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..981924789fb5ba3089cb64bda2936fc77fe88cf1
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6da3d7a0c58b8aa288d79ba573432bd5dddf3655
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17597640318da1e266dbca38e76deb8f322fd8fc
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62cd9eb6dbea9c9a2784077bb1a21200d008af7b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f38b4778fc93095d1a4bff30d629fa8c976659d
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dcdbc1726ce614a44ec06882e5969ccf3d458659
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d712606822d17d63a41bb8b4b3a938750eaf482
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1118d12343bc0694c9aa707e7a4cb4eb63a8350e
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8327ec23543dcc294ac5b4fd14099a547fb36f63
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ee2c0775cd6c304a628ad3a822e59914be92250
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0bd3afcc96ee77312f3af5bd690dcb6703907ee
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64d6d5f03cb10c02aa53841f896578daf99e1c03
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5129f1bb4f31c9c6891803669e6f124523b87da8
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b486d66b20e511b6a5b9938d696c0f9a0ec5c1a2
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b171a0da4ad34da67b087f3d08ff48517413c5c
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acda056c76a77db1c81fa965eef2977b4146e120
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81ddea6e29462d00b3d79deb76144f83e2567103
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..592ea11fd81ef5af0078493cf0126af25a29706d
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e69d822306f2c4f7385cfee93c19bf232808352e
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..829564152d2267aff5fec707c73a8c59a3309b7b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1a874536c657f7a083975afa22645251584d30f
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1719edc6f61b60ee78daf38a39100b74c2603c39
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b86ba15a0233927b2168440e3924e0dae1374e4
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed1d7e3fbf7077a77ada38a50baa38db4e016206
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0097f1748baefe081579c75809ab014730e9cc7b
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e507a781b9c8da49194d363935be1720f48cb66e
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26da3ce3bca5ea197a698856775f606f88e6bfbb
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42fe5a0d64a0e20774919d56007e73155c3ff465
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_base.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..926e191013c7cacebab7a8e025a017358ba82f50
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_base.py
@@ -0,0 +1,1448 @@
+"""Base class for sparse matrices"""
+
+import numpy as np
+
+from ._sputils import (asmatrix, check_reshape_kwargs, check_shape,
+                       get_sum_dtype, isdense, isscalarlike,
+                       matrix, validateaxis, getdtype)
+
+from ._matrix import spmatrix
+
+__all__ = ['isspmatrix', 'issparse', 'sparray',
+           'SparseWarning', 'SparseEfficiencyWarning']
+
+
+class SparseWarning(Warning):
+    pass
+
+
+class SparseFormatWarning(SparseWarning):
+    pass
+
+
+class SparseEfficiencyWarning(SparseWarning):
+    pass
+
+
+# The formats that we might potentially understand.
+_formats = {'csc': [0, "Compressed Sparse Column"],
+            'csr': [1, "Compressed Sparse Row"],
+            'dok': [2, "Dictionary Of Keys"],
+            'lil': [3, "List of Lists"],
+            'dod': [4, "Dictionary of Dictionaries"],
+            'sss': [5, "Symmetric Sparse Skyline"],
+            'coo': [6, "COOrdinate"],
+            'lba': [7, "Linpack BAnded"],
+            'egd': [8, "Ellpack-itpack Generalized Diagonal"],
+            'dia': [9, "DIAgonal"],
+            'bsr': [10, "Block Sparse Row"],
+            'msr': [11, "Modified compressed Sparse Row"],
+            'bsc': [12, "Block Sparse Column"],
+            'msc': [13, "Modified compressed Sparse Column"],
+            'ssk': [14, "Symmetric SKyline"],
+            'nsk': [15, "Nonsymmetric SKyline"],
+            'jad': [16, "JAgged Diagonal"],
+            'uss': [17, "Unsymmetric Sparse Skyline"],
+            'vbr': [18, "Variable Block Row"],
+            'und': [19, "Undefined"]
+            }
+
+
+# These univariate ufuncs preserve zeros.
+_ufuncs_with_fixed_point_at_zero = frozenset([
+        np.sin, np.tan, np.arcsin, np.arctan, np.sinh, np.tanh, np.arcsinh,
+        np.arctanh, np.rint, np.sign, np.expm1, np.log1p, np.deg2rad,
+        np.rad2deg, np.floor, np.ceil, np.trunc, np.sqrt])
+
+
+MAXPRINT = 50
+
+
+class _spbase:
+    """ This class provides a base class for all sparse arrays.  It
+    cannot be instantiated.  Most of the work is provided by subclasses.
+    """
+
+    __array_priority__ = 10.1
+    _format = 'und'  # undefined
+    _allow_nd = (2,)
+
+    @property
+    def ndim(self) -> int:
+        return len(self._shape)
+
+    @property
+    def _shape_as_2d(self):
+        s = self._shape
+        return (1, s[-1]) if len(s) == 1 else s
+
+    @property
+    def _bsr_container(self):
+        from ._bsr import bsr_array
+        return bsr_array
+
+    @property
+    def _coo_container(self):
+        from ._coo import coo_array
+        return coo_array
+
+    @property
+    def _csc_container(self):
+        from ._csc import csc_array
+        return csc_array
+
+    @property
+    def _csr_container(self):
+        from ._csr import csr_array
+        return csr_array
+
+    @property
+    def _dia_container(self):
+        from ._dia import dia_array
+        return dia_array
+
+    @property
+    def _dok_container(self):
+        from ._dok import dok_array
+        return dok_array
+
+    @property
+    def _lil_container(self):
+        from ._lil import lil_array
+        return lil_array
+
+    def __init__(self, arg1, *, maxprint=None):
+        self._shape = None
+        if self.__class__.__name__ == '_spbase':
+            raise ValueError("This class is not intended"
+                             " to be instantiated directly.")
+        if isinstance(self, sparray) and np.isscalar(arg1):
+            raise ValueError(
+                "scipy sparse array classes do not support instantiation from a scalar"
+            )
+        self.maxprint = MAXPRINT if maxprint is None else maxprint
+
+    @property
+    def shape(self):
+        return self._shape
+
+    def reshape(self, *args, **kwargs):
+        """reshape(self, shape, order='C', copy=False)
+
+        Gives a new shape to a sparse array/matrix without changing its data.
+
+        Parameters
+        ----------
+        shape : length-2 tuple of ints
+            The new shape should be compatible with the original shape.
+        order : {'C', 'F'}, optional
+            Read the elements using this index order. 'C' means to read and
+            write the elements using C-like index order; e.g., read entire first
+            row, then second row, etc. 'F' means to read and write the elements
+            using Fortran-like index order; e.g., read entire first column, then
+            second column, etc.
+        copy : bool, optional
+            Indicates whether or not attributes of self should be copied
+            whenever possible. The degree to which attributes are copied varies
+            depending on the type of sparse array being used.
+
+        Returns
+        -------
+        reshaped : sparse array/matrix
+            A sparse array/matrix with the given `shape`, not necessarily of the same
+            format as the current object.
+
+        See Also
+        --------
+        numpy.reshape : NumPy's implementation of 'reshape' for ndarrays
+        """
+        # If the shape already matches, don't bother doing an actual reshape
+        # Otherwise, the default is to convert to COO and use its reshape
+        # Don't restrict ndim on this first call. That happens in constructor
+        shape = check_shape(args, self.shape, allow_nd=range(1, 65))
+        order, copy = check_reshape_kwargs(kwargs)
+        if shape == self.shape:
+            if copy:
+                return self.copy()
+            else:
+                return self
+
+        return self.tocoo(copy=copy).reshape(shape, order=order, copy=False)
+
+    def resize(self, shape):
+        """Resize the array/matrix in-place to dimensions given by ``shape``
+
+        Any elements that lie within the new shape will remain at the same
+        indices, while non-zero elements lying outside the new shape are
+        removed.
+
+        Parameters
+        ----------
+        shape : (int, int)
+            number of rows and columns in the new array/matrix
+
+        Notes
+        -----
+        The semantics are not identical to `numpy.ndarray.resize` or
+        `numpy.resize`. Here, the same data will be maintained at each index
+        before and after reshape, if that index is within the new bounds. In
+        numpy, resizing maintains contiguity of the array, moving elements
+        around in the logical array but not within a flattened representation.
+
+        We give no guarantees about whether the underlying data attributes
+        (arrays, etc.) will be modified in place or replaced with new objects.
+        """
+        # As an inplace operation, this requires implementation in each format.
+        raise NotImplementedError(
+            f'{type(self).__name__}.resize is not implemented')
+
+    def astype(self, dtype, casting='unsafe', copy=True):
+        """Cast the array/matrix elements to a specified type.
+
+        Parameters
+        ----------
+        dtype : string or numpy dtype
+            Typecode or data-type to which to cast the data.
+        casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+            Controls what kind of data casting may occur.
+            Defaults to 'unsafe' for backwards compatibility.
+            'no' means the data types should not be cast at all.
+            'equiv' means only byte-order changes are allowed.
+            'safe' means only casts which can preserve values are allowed.
+            'same_kind' means only safe casts or casts within a kind,
+            like float64 to float32, are allowed.
+            'unsafe' means any data conversions may be done.
+        copy : bool, optional
+            If `copy` is `False`, the result might share some memory with this
+            array/matrix. If `copy` is `True`, it is guaranteed that the result and
+            this array/matrix do not share any memory.
+        """
+
+        dtype = getdtype(dtype)
+        if self.dtype != dtype:
+            return self.tocsr().astype(
+                dtype, casting=casting, copy=copy).asformat(self.format)
+        elif copy:
+            return self.copy()
+        else:
+            return self
+
+    @classmethod
+    def _ascontainer(cls, X, **kwargs):
+        if issubclass(cls, sparray):
+            return np.asarray(X, **kwargs)
+        else:
+            return asmatrix(X, **kwargs)
+
+    @classmethod
+    def _container(cls, X, **kwargs):
+        if issubclass(cls, sparray):
+            return np.array(X, **kwargs)
+        else:
+            return matrix(X, **kwargs)
+
+    def _asfptype(self):
+        """Upcast array to a floating point format (if necessary)"""
+
+        fp_types = ['f', 'd', 'F', 'D']
+
+        if self.dtype.char in fp_types:
+            return self
+        else:
+            for fp_type in fp_types:
+                if self.dtype <= np.dtype(fp_type):
+                    return self.astype(fp_type)
+
+            raise TypeError(
+                f'cannot upcast [{self.dtype.name}] to a floating point format'
+            )
+
+    def __iter__(self):
+        for r in range(self.shape[0]):
+            yield self[r]
+
+    def _getmaxprint(self):
+        """Maximum number of elements to display when printed."""
+        return self.maxprint
+
+    def count_nonzero(self, axis=None):
+        """Number of non-zero entries, equivalent to
+
+        np.count_nonzero(a.toarray(), axis=axis)
+
+        Unlike the nnz property, which return the number of stored
+        entries (the length of the data attribute), this method counts the
+        actual number of non-zero entries in data.
+
+        Duplicate entries are summed before counting.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Count nonzeros for the whole array, or along a specified axis.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        numpy array
+            A reduced array (no axis `axis`) holding the number of nonzero values
+            for each of the indices of the nonaxis dimensions.
+
+        Notes
+        -----
+        If you want to count nonzero and explicit zero stored values (e.g. nnz)
+        along an axis, two fast idioms are provided by `numpy` functions for the
+        common CSR, CSC, COO formats.
+
+        For the major axis in CSR (rows) and CSC (cols) use `np.diff`:
+
+            >>> import numpy as np
+            >>> import scipy as sp
+            >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
+            >>> major_axis_stored_values = np.diff(A.indptr)  # -> np.array([2, 1])
+
+        For the minor axis in CSR (cols) and CSC (rows) use `numpy.bincount` with
+        minlength ``A.shape[1]`` for CSR and ``A.shape[0]`` for CSC:
+
+            >>> csr_minor_stored_values = np.bincount(A.indices, minlength=A.shape[1])
+
+        For COO, use the minor axis approach for either `axis`:
+
+            >>> A = A.tocoo()
+            >>> coo_axis0_stored_values = np.bincount(A.coords[0], minlength=A.shape[1])
+            >>> coo_axis1_stored_values = np.bincount(A.coords[1], minlength=A.shape[0])
+
+        Examples
+        --------
+
+            >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
+            >>> A.count_nonzero(axis=0)
+            array([2, 1, 0])
+        """
+        clsname = self.__class__.__name__
+        raise NotImplementedError(f"count_nonzero not implemented for {clsname}.")
+
+    def _getnnz(self, axis=None):
+        """Number of stored values, including explicit zeros.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Report stored values for the whole array, or along a specified axis.
+
+        See also
+        --------
+        count_nonzero : Number of non-zero entries
+        """
+        clsname = self.__class__.__name__
+        raise NotImplementedError(f"getnnz not implemented for {clsname}.")
+
+    @property
+    def nnz(self) -> int:
+        """Number of stored values, including explicit zeros.
+
+        See also
+        --------
+        count_nonzero : Number of non-zero entries
+        """
+        return self._getnnz()
+
+    @property
+    def size(self) -> int:
+        """Number of stored values.
+
+        See also
+        --------
+        count_nonzero : Number of non-zero values.
+        """
+        return self._getnnz()
+
+    @property
+    def format(self) -> str:
+        """Format string for matrix."""
+        return self._format
+
+    @property
+    def T(self):
+        """Transpose."""
+        return self.transpose()
+
+    @property
+    def real(self):
+        return self._real()
+
+    @property
+    def imag(self):
+        return self._imag()
+
+    def __repr__(self):
+        _, format_name = _formats[self.format]
+        sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
+        return (
+            f"<{format_name} sparse {sparse_cls} of dtype '{self.dtype}'\n"
+            f"\twith {self.nnz} stored elements and shape {self.shape}>"
+        )
+
+    def __str__(self):
+        maxprint = self._getmaxprint()
+
+        A = self.tocoo()
+
+        # helper function, outputs "(i,j)  v"
+        def tostr(coords, data):
+            pairs = zip(zip(*(c.tolist() for c in coords)), data)
+            return '\n'.join(f'  {idx}\t{val}' for idx, val in pairs)
+
+        out = repr(self)
+        if self.nnz == 0:
+            return out
+
+        out += '\n  Coords\tValues\n'
+        if self.nnz > maxprint:
+            half = maxprint // 2
+            out += tostr(tuple(c[:half] for c in A.coords), A.data[:half])
+            out += "\n  :\t:\n"
+            half = maxprint - half
+            out += tostr(tuple(c[-half:] for c in A.coords), A.data[-half:])
+        else:
+            out += tostr(A.coords, A.data)
+
+        return out
+
+    def __bool__(self):  # Simple -- other ideas?
+        if self.shape == (1, 1):
+            return self.nnz != 0
+        else:
+            raise ValueError("The truth value of an array with more than one "
+                             "element is ambiguous. Use a.any() or a.all().")
+    __nonzero__ = __bool__
+
+    # What should len(sparse) return? For consistency with dense matrices,
+    # perhaps it should be the number of rows?  But for some uses the number of
+    # non-zeros is more important.  For now, raise an exception!
+    def __len__(self):
+        raise TypeError("sparse array length is ambiguous; use getnnz()"
+                        " or shape[0]")
+
+    def asformat(self, format, copy=False):
+        """Return this array/matrix in the passed format.
+
+        Parameters
+        ----------
+        format : {str, None}
+            The desired sparse format ("csr", "csc", "lil", "dok", "array", ...)
+            or None for no conversion.
+        copy : bool, optional
+            If True, the result is guaranteed to not share data with self.
+
+        Returns
+        -------
+        A : This array/matrix in the passed format.
+        """
+        if format is None or format == self.format:
+            if copy:
+                return self.copy()
+            else:
+                return self
+        else:
+            try:
+                convert_method = getattr(self, 'to' + format)
+            except AttributeError as e:
+                raise ValueError(f'Format {format} is unknown.') from e
+
+            # Forward the copy kwarg, if it's accepted.
+            try:
+                return convert_method(copy=copy)
+            except TypeError:
+                return convert_method()
+
+    ###################################################################
+    #  NOTE: All arithmetic operations use csr_matrix by default.
+    # Therefore a new sparse array format just needs to define a
+    # .tocsr() method to provide arithmetic support. Any of these
+    # methods can be overridden for efficiency.
+    ####################################################################
+
+    def multiply(self, other):
+        """Point-wise multiplication by another array/matrix."""
+        if isscalarlike(other):
+            return self._mul_scalar(other)
+        return self.tocsr().multiply(other)
+
+    def maximum(self, other):
+        """Element-wise maximum between this and another array/matrix."""
+        return self.tocsr().maximum(other)
+
+    def minimum(self, other):
+        """Element-wise minimum between this and another array/matrix."""
+        return self.tocsr().minimum(other)
+
+    def dot(self, other):
+        """Ordinary dot product
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.sparse import csr_array
+        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+        >>> v = np.array([1, 0, -1])
+        >>> A.dot(v)
+        array([ 1, -3, -1], dtype=int64)
+
+        """
+        if np.isscalar(other):
+            return self * other
+        else:
+            return self @ other
+
+    def power(self, n, dtype=None):
+        """Element-wise power."""
+        return self.tocsr().power(n, dtype=dtype)
+
+    def _broadcast_to(self, shape, copy=False):
+        if self.shape == shape:
+            return self.copy() if copy else self
+        else:
+            return self.tocsr()._broadcast_to(shape, copy)
+
+    def __eq__(self, other):
+        return self.tocsr().__eq__(other)
+
+    def __ne__(self, other):
+        return self.tocsr().__ne__(other)
+
+    def __lt__(self, other):
+        return self.tocsr().__lt__(other)
+
+    def __gt__(self, other):
+        return self.tocsr().__gt__(other)
+
+    def __le__(self, other):
+        return self.tocsr().__le__(other)
+
+    def __ge__(self, other):
+        return self.tocsr().__ge__(other)
+
+    def __abs__(self):
+        return abs(self.tocsr())
+
+    def __round__(self, ndigits=0):
+        return round(self.tocsr(), ndigits=ndigits)
+
+    def _add_sparse(self, other):
+        return self.tocsr()._add_sparse(other)
+
+    def _add_dense(self, other):
+        return self.tocoo()._add_dense(other)
+
+    def _sub_sparse(self, other):
+        return self.tocsr()._sub_sparse(other)
+
+    def _sub_dense(self, other):
+        return self.todense() - other
+
+    def _rsub_dense(self, other):
+        # note: this can't be replaced by other + (-self) for unsigned types
+        return other - self.todense()
+
+    def __add__(self, other):  # self + other
+        if isscalarlike(other):
+            if other == 0:
+                return self.copy()
+            # Now we would add this scalar to every element.
+            raise NotImplementedError('adding a nonzero scalar to a '
+                                      'sparse array is not supported')
+        elif issparse(other):
+            if other.shape != self.shape:
+                raise ValueError("inconsistent shapes")
+            return self._add_sparse(other)
+        elif isdense(other):
+            other = np.broadcast_to(other, self.shape)
+            return self._add_dense(other)
+        else:
+            return NotImplemented
+
+    def __radd__(self,other):  # other + self
+        return self.__add__(other)
+
+    def __sub__(self, other):  # self - other
+        if isscalarlike(other):
+            if other == 0:
+                return self.copy()
+            raise NotImplementedError('subtracting a nonzero scalar from a '
+                                      'sparse array is not supported')
+        elif issparse(other):
+            if other.shape != self.shape:
+                raise ValueError("inconsistent shapes")
+            return self._sub_sparse(other)
+        elif isdense(other):
+            other = np.broadcast_to(other, self.shape)
+            return self._sub_dense(other)
+        else:
+            return NotImplemented
+
+    def __rsub__(self,other):  # other - self
+        if isscalarlike(other):
+            if other == 0:
+                return -self.copy()
+            raise NotImplementedError('subtracting a sparse array from a '
+                                      'nonzero scalar is not supported')
+        elif isdense(other):
+            other = np.broadcast_to(other, self.shape)
+            return self._rsub_dense(other)
+        else:
+            return NotImplemented
+
+    def _matmul_dispatch(self, other):
+        """np.array-like matmul & `np.matrix`-like mul, i.e. `dot` or `NotImplemented`
+
+        interpret other and call one of the following
+        self._mul_scalar()
+        self._matmul_vector()
+        self._matmul_multivector()
+        self._matmul_sparse()
+        """
+        # This method has to be different from `__matmul__` because it is also
+        # called by sparse matrix classes.
+
+        # Currently matrix multiplication is only supported
+        # for 2D arrays. Hence we unpacked and use only the
+        # two last axes' lengths.
+        M, N = self._shape_as_2d
+
+        if other.__class__ is np.ndarray:
+            # Fast path for the most common case
+            if other.shape == (N,):
+                return self._matmul_vector(other)
+            elif other.shape == (N, 1):
+                result = self._matmul_vector(other.ravel())
+                if self.ndim == 1:
+                    return result.reshape(1)
+                return result.reshape(M, 1)
+            elif other.ndim == 2 and other.shape[0] == N:
+                return self._matmul_multivector(other)
+
+        if isscalarlike(other):
+            # scalar value
+            return self._mul_scalar(other)
+
+        err_prefix = "matmul: dimension mismatch with signature"
+        if issparse(other):
+            if N != other.shape[0]:
+                raise ValueError(
+                    f"{err_prefix} (n,k={N}),(k={other.shape[0]},m)->(n,m)"
+                )
+            return self._matmul_sparse(other)
+
+        # If it's a list or whatever, treat it like an array
+        other_a = np.asanyarray(other)
+
+        if other_a.ndim == 0 and other_a.dtype == np.object_:
+            # Not interpretable as an array; return NotImplemented so that
+            # other's __rmatmul__ can kick in if that's implemented.
+            return NotImplemented
+
+        try:
+            other.shape
+        except AttributeError:
+            other = other_a
+
+        if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:
+            # dense row or column vector
+            if other.shape[0] != N:
+                raise ValueError(
+                    f"{err_prefix} (n,k={N}),(k={other.shape[0]},1?)->(n,1?)"
+                )
+
+            result = self._matmul_vector(np.ravel(other))
+
+            if isinstance(other, np.matrix):
+                result = self._ascontainer(result)
+
+            if other.ndim == 2 and other.shape[1] == 1:
+                # If 'other' was an (nx1) column vector, reshape the result
+                if self.ndim == 1:
+                    result = result.reshape(1)
+                else:
+                    result = result.reshape(-1, 1)
+
+            return result
+
+        elif other.ndim == 2:
+            ##
+            # dense 2D array or matrix ("multivector")
+
+            if other.shape[0] != N:
+                raise ValueError(
+                    f"{err_prefix} (n,k={N}),(k={other.shape[0]},m)->(n,m)"
+                )
+
+            result = self._matmul_multivector(np.asarray(other))
+
+            if isinstance(other, np.matrix):
+                result = self._ascontainer(result)
+
+            return result
+
+        else:
+            raise ValueError('could not interpret dimensions')
+
+    def __mul__(self, other):
+        return self.multiply(other)
+
+    def __rmul__(self, other):  # other * self
+        return self.multiply(other)
+
+    # by default, use CSR for __mul__ handlers
+    def _mul_scalar(self, other):
+        return self.tocsr()._mul_scalar(other)
+
+    def _matmul_vector(self, other):
+        return self.tocsr()._matmul_vector(other)
+
+    def _matmul_multivector(self, other):
+        return self.tocsr()._matmul_multivector(other)
+
+    def _matmul_sparse(self, other):
+        return self.tocsr()._matmul_sparse(other)
+
+    def _rmatmul_dispatch(self, other):
+        if isscalarlike(other):
+            return self._mul_scalar(other)
+        else:
+            # Don't use asarray unless we have to
+            try:
+                tr = other.transpose()
+            except AttributeError:
+                tr = np.asarray(other).transpose()
+            ret = self.transpose()._matmul_dispatch(tr)
+            if ret is NotImplemented:
+                return NotImplemented
+            return ret.transpose()
+
+    #######################
+    # matmul (@) operator #
+    #######################
+
+    def __matmul__(self, other):
+        if isscalarlike(other):
+            raise ValueError("Scalar operands are not allowed, "
+                             "use '*' instead")
+        return self._matmul_dispatch(other)
+
+    def __rmatmul__(self, other):
+        if isscalarlike(other):
+            raise ValueError("Scalar operands are not allowed, "
+                             "use '*' instead")
+        return self._rmatmul_dispatch(other)
+
+    ####################
+    # Other Arithmetic #
+    ####################
+
+    def _divide(self, other, true_divide=False, rdivide=False):
+        if isscalarlike(other):
+            if rdivide:
+                if true_divide:
+                    return np.true_divide(other, self.todense())
+                else:
+                    return np.divide(other, self.todense())
+
+            if true_divide and np.can_cast(self.dtype, np.float64):
+                return self.astype(np.float64)._mul_scalar(1./other)
+            else:
+                r = self._mul_scalar(1./other)
+
+                scalar_dtype = np.asarray(other).dtype
+                if (np.issubdtype(self.dtype, np.integer) and
+                        np.issubdtype(scalar_dtype, np.integer)):
+                    return r.astype(self.dtype)
+                else:
+                    return r
+
+        elif isdense(other):
+            if not rdivide:
+                if true_divide:
+                    recip = np.true_divide(1., other)
+                else:
+                    recip = np.divide(1., other)
+                return self.multiply(recip)
+            else:
+                if true_divide:
+                    return np.true_divide(other, self.todense())
+                else:
+                    return np.divide(other, self.todense())
+        elif issparse(other):
+            if rdivide:
+                return other._divide(self, true_divide, rdivide=False)
+
+            self_csr = self.tocsr()
+            if true_divide and np.can_cast(self.dtype, np.float64):
+                return self_csr.astype(np.float64)._divide_sparse(other)
+            else:
+                return self_csr._divide_sparse(other)
+        else:
+            return NotImplemented
+
+    def __truediv__(self, other):
+        return self._divide(other, true_divide=True)
+
+    def __div__(self, other):
+        # Always do true division
+        return self._divide(other, true_divide=True)
+
+    def __rtruediv__(self, other):
+        # Implementing this as the inverse would be too magical -- bail out
+        return NotImplemented
+
+    def __rdiv__(self, other):
+        # Implementing this as the inverse would be too magical -- bail out
+        return NotImplemented
+
+    def __neg__(self):
+        return -self.tocsr()
+
+    def __iadd__(self, other):
+        return NotImplemented
+
+    def __isub__(self, other):
+        return NotImplemented
+
+    def __imul__(self, other):
+        return NotImplemented
+
+    def __idiv__(self, other):
+        return self.__itruediv__(other)
+
+    def __itruediv__(self, other):
+        return NotImplemented
+
+    def __pow__(self, *args, **kwargs):
+        return self.power(*args, **kwargs)
+
+    def transpose(self, axes=None, copy=False):
+        """
+        Reverses the dimensions of the sparse array/matrix.
+
+        Parameters
+        ----------
+        axes : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except
+            for the default value.
+        copy : bool, optional
+            Indicates whether or not attributes of `self` should be
+            copied whenever possible. The degree to which attributes
+            are copied varies depending on the type of sparse array/matrix
+            being used.
+
+        Returns
+        -------
+        p : `self` with the dimensions reversed.
+
+        Notes
+        -----
+        If `self` is a `csr_array` or a `csc_array`, then this will return a
+        `csc_array` or a `csr_array`, respectively.
+
+        See Also
+        --------
+        numpy.transpose : NumPy's implementation of 'transpose' for ndarrays
+        """
+        return self.tocsr(copy=copy).transpose(axes=axes, copy=False)
+
+    def conjugate(self, copy=True):
+        """Element-wise complex conjugation.
+
+        If the array/matrix is of non-complex data type and `copy` is False,
+        this method does nothing and the data is not copied.
+
+        Parameters
+        ----------
+        copy : bool, optional
+            If True, the result is guaranteed to not share data with self.
+
+        Returns
+        -------
+        A : The element-wise complex conjugate.
+
+        """
+        if np.issubdtype(self.dtype, np.complexfloating):
+            return self.tocsr(copy=copy).conjugate(copy=False)
+        elif copy:
+            return self.copy()
+        else:
+            return self
+
+    def conj(self, copy=True):
+        return self.conjugate(copy=copy)
+
+    conj.__doc__ = conjugate.__doc__
+
+    def _real(self):
+        return self.tocsr()._real()
+
+    def _imag(self):
+        return self.tocsr()._imag()
+
+    def nonzero(self):
+        """Nonzero indices of the array/matrix.
+
+        Returns a tuple of arrays (row,col) containing the indices
+        of the non-zero elements of the array.
+
+        Examples
+        --------
+        >>> from scipy.sparse import csr_array
+        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+        >>> A.nonzero()
+        (array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32))
+
+        """
+
+        # convert to COOrdinate format
+        A = self.tocoo()
+        nz_mask = A.data != 0
+        return tuple(idx[nz_mask] for idx in A.coords)
+
+    def _getcol(self, j):
+        """Returns a copy of column j of the array, as an (m x 1) sparse
+        array (column vector).
+        """
+        if self.ndim == 1:
+            raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]")
+        # Subclasses should override this method for efficiency.
+        # Post-multiply by a (n x 1) column vector 'a' containing all zeros
+        # except for a_j = 1
+        N = self.shape[-1]
+        if j < 0:
+            j += N
+        if j < 0 or j >= N:
+            raise IndexError("index out of bounds")
+        col_selector = self._csc_container(([1], [[j], [0]]),
+                                           shape=(N, 1), dtype=self.dtype)
+        result = self @ col_selector
+        return result
+
+    def _getrow(self, i):
+        """Returns a copy of row i of the array, as a (1 x n) sparse
+        array (row vector).
+        """
+        if self.ndim == 1:
+            raise ValueError("getrow not meaningful for a 1d array")
+        # Subclasses should override this method for efficiency.
+        # Pre-multiply by a (1 x m) row vector 'a' containing all zeros
+        # except for a_i = 1
+        M = self.shape[0]
+        if i < 0:
+            i += M
+        if i < 0 or i >= M:
+            raise IndexError("index out of bounds")
+        row_selector = self._csr_container(([1], [[0], [i]]),
+                                           shape=(1, M), dtype=self.dtype)
+        return row_selector @ self
+
+    # The following dunder methods cannot be implemented.
+    #
+    # def __array__(self):
+    #     # Sparse matrices rely on NumPy wrapping them in object arrays under
+    #     # the hood to make unary ufuncs work on them. So we cannot raise
+    #     # TypeError here - which would be handy to not give users object
+    #     # arrays they probably don't want (they're looking for `.toarray()`).
+    #     #
+    #     # Conversion with `toarray()` would also break things because of the
+    #     # behavior discussed above, plus we want to avoid densification by
+    #     # accident because that can too easily blow up memory.
+    #
+    # def __array_ufunc__(self):
+    #     # We cannot implement __array_ufunc__ due to mismatching semantics.
+    #     # See gh-7707 and gh-7349 for details.
+    #
+    # def __array_function__(self):
+    #     # We cannot implement __array_function__ due to mismatching semantics.
+    #     # See gh-10362 for details.
+
+    def todense(self, order=None, out=None):
+        """
+        Return a dense representation of this sparse array.
+
+        Parameters
+        ----------
+        order : {'C', 'F'}, optional
+            Whether to store multi-dimensional data in C (row-major)
+            or Fortran (column-major) order in memory. The default
+            is 'None', which provides no ordering guarantees.
+            Cannot be specified in conjunction with the `out`
+            argument.
+
+        out : ndarray, 2-D, optional
+            If specified, uses this array as the output buffer
+            instead of allocating a new array to return. The
+            provided array must have the same shape and dtype as
+            the sparse array on which you are calling the method.
+
+        Returns
+        -------
+        arr : ndarray, 2-D
+            An array with the same shape and containing the same
+            data represented by the sparse array, with the requested
+            memory order. If `out` was passed, the same object is
+            returned after being modified in-place to contain the
+            appropriate values.
+        """
+        return self._ascontainer(self.toarray(order=order, out=out))
+
+    def toarray(self, order=None, out=None):
+        """
+        Return a dense ndarray representation of this sparse array/matrix.
+
+        Parameters
+        ----------
+        order : {'C', 'F'}, optional
+            Whether to store multidimensional data in C (row-major)
+            or Fortran (column-major) order in memory. The default
+            is 'None', which provides no ordering guarantees.
+            Cannot be specified in conjunction with the `out`
+            argument.
+
+        out : ndarray, 2-D, optional
+            If specified, uses this array as the output buffer
+            instead of allocating a new array to return. The provided
+            array must have the same shape and dtype as the sparse
+            array/matrix on which you are calling the method. For most
+            sparse types, `out` is required to be memory contiguous
+            (either C or Fortran ordered).
+
+        Returns
+        -------
+        arr : ndarray, 2-D
+            An array with the same shape and containing the same
+            data represented by the sparse array/matrix, with the requested
+            memory order. If `out` was passed, the same object is
+            returned after being modified in-place to contain the
+            appropriate values.
+        """
+        return self.tocoo(copy=False).toarray(order=order, out=out)
+
+    # Any sparse array format deriving from _spbase must define one of
+    # tocsr or tocoo. The other conversion methods may be implemented for
+    # efficiency, but are not required.
+    def tocsr(self, copy=False):
+        """Convert this array/matrix to Compressed Sparse Row format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant csr_array/matrix.
+        """
+        return self.tocoo(copy=copy).tocsr(copy=False)
+
+    def todok(self, copy=False):
+        """Convert this array/matrix to Dictionary Of Keys format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant dok_array/matrix.
+        """
+        return self.tocoo(copy=copy).todok(copy=False)
+
+    def tocoo(self, copy=False):
+        """Convert this array/matrix to COOrdinate format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant coo_array/matrix.
+        """
+        return self.tocsr(copy=False).tocoo(copy=copy)
+
+    def tolil(self, copy=False):
+        """Convert this array/matrix to List of Lists format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant lil_array/matrix.
+        """
+        return self.tocsr(copy=False).tolil(copy=copy)
+
+    def todia(self, copy=False):
+        """Convert this array/matrix to sparse DIAgonal format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant dia_array/matrix.
+        """
+        return self.tocoo(copy=copy).todia(copy=False)
+
+    def tobsr(self, blocksize=None, copy=False):
+        """Convert this array/matrix to Block Sparse Row format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant bsr_array/matrix.
+
+        When blocksize=(R, C) is provided, it will be used for construction of
+        the bsr_array/matrix.
+        """
+        return self.tocsr(copy=False).tobsr(blocksize=blocksize, copy=copy)
+
+    def tocsc(self, copy=False):
+        """Convert this array/matrix to Compressed Sparse Column format.
+
+        With copy=False, the data/indices may be shared between this array/matrix and
+        the resultant csc_array/matrix.
+        """
+        return self.tocsr(copy=copy).tocsc(copy=False)
+
+    def copy(self):
+        """Returns a copy of this array/matrix.
+
+        No data/indices will be shared between the returned value and current
+        array/matrix.
+        """
+        return self.__class__(self, copy=True)
+
+    def sum(self, axis=None, dtype=None, out=None):
+        """
+        Sum the array/matrix elements over a given axis.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the sum is computed. The default is to
+            compute the sum of all the array/matrix elements, returning a scalar
+            (i.e., `axis` = `None`).
+        dtype : dtype, optional
+            The type of the returned array/matrix and of the accumulator in which
+            the elements are summed.  The dtype of `a` is used by default
+            unless `a` has an integer dtype of less precision than the default
+            platform integer.  In that case, if `a` is signed then the platform
+            integer is used while if `a` is unsigned then an unsigned integer
+            of the same precision as the platform integer is used.
+
+            .. versionadded:: 0.18.0
+
+        out : np.matrix, optional
+            Alternative output matrix in which to place the result. It must
+            have the same shape as the expected output, but the type of the
+            output values will be cast if necessary.
+
+            .. versionadded:: 0.18.0
+
+        Returns
+        -------
+        sum_along_axis : np.matrix
+            A matrix with the same shape as `self`, with the specified
+            axis removed.
+
+        See Also
+        --------
+        numpy.matrix.sum : NumPy's implementation of 'sum' for matrices
+
+        """
+        validateaxis(axis)
+
+        # Mimic numpy's casting.
+        res_dtype = get_sum_dtype(self.dtype)
+
+        if self.ndim == 1:
+            if axis not in (None, -1, 0):
+                raise ValueError("axis must be None, -1 or 0")
+            res = self @ np.ones(self.shape, dtype=res_dtype)
+            return res.sum(dtype=dtype, out=out)
+
+        # We use multiplication by a matrix of ones to achieve this.
+        # For some sparse array formats more efficient methods are
+        # possible -- these should override this function.
+        M, N = self.shape
+
+        if axis is None:
+            # sum over rows and columns
+            return (
+                self @ self._ascontainer(np.ones((N, 1), dtype=res_dtype))
+            ).sum(dtype=dtype, out=out)
+
+        if axis < 0:
+            axis += 2
+
+        # axis = 0 or 1 now
+        if axis == 0:
+            # sum over columns
+            ret = self._ascontainer(
+                np.ones((1, M), dtype=res_dtype)
+            ) @ self
+        else:
+            # sum over rows
+            ret = self @ self._ascontainer(
+                np.ones((N, 1), dtype=res_dtype)
+            )
+
+        return ret.sum(axis=axis, dtype=dtype, out=out)
+
+    def mean(self, axis=None, dtype=None, out=None):
+        """
+        Compute the arithmetic mean along the specified axis.
+
+        Returns the average of the array/matrix elements. The average is taken
+        over all elements in the array/matrix by default, otherwise over the
+        specified axis. `float64` intermediate and return values are used
+        for integer inputs.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the mean is computed. The default is to compute
+            the mean of all elements in the array/matrix (i.e., `axis` = `None`).
+        dtype : data-type, optional
+            Type to use in computing the mean. For integer inputs, the default
+            is `float64`; for floating point inputs, it is the same as the
+            input dtype.
+
+            .. versionadded:: 0.18.0
+
+        out : np.matrix, optional
+            Alternative output matrix in which to place the result. It must
+            have the same shape as the expected output, but the type of the
+            output values will be cast if necessary.
+
+            .. versionadded:: 0.18.0
+
+        Returns
+        -------
+        m : np.matrix
+
+        See Also
+        --------
+        numpy.matrix.mean : NumPy's implementation of 'mean' for matrices
+
+        """
+        validateaxis(axis)
+
+        res_dtype = self.dtype.type
+        integral = (np.issubdtype(self.dtype, np.integer) or
+                    np.issubdtype(self.dtype, np.bool_))
+
+        # output dtype
+        if dtype is None:
+            if integral:
+                res_dtype = np.float64
+        else:
+            res_dtype = np.dtype(dtype).type
+
+        # intermediate dtype for summation
+        inter_dtype = np.float64 if integral else res_dtype
+        inter_self = self.astype(inter_dtype)
+
+        if self.ndim == 1:
+            if axis not in (None, -1, 0):
+                raise ValueError("axis must be None, -1 or 0")
+            res = inter_self / self.shape[-1]
+            return res.sum(dtype=res_dtype, out=out)
+
+        if axis is None:
+            return (inter_self / (self.shape[0] * self.shape[1]))\
+                .sum(dtype=res_dtype, out=out)
+
+        if axis < 0:
+            axis += 2
+
+        # axis = 0 or 1 now
+        if axis == 0:
+            return (inter_self * (1.0 / self.shape[0])).sum(
+                axis=0, dtype=res_dtype, out=out)
+        else:
+            return (inter_self * (1.0 / self.shape[1])).sum(
+                axis=1, dtype=res_dtype, out=out)
+
+    def diagonal(self, k=0):
+        """Returns the kth diagonal of the array/matrix.
+
+        Parameters
+        ----------
+        k : int, optional
+            Which diagonal to get, corresponding to elements a[i, i+k].
+            Default: 0 (the main diagonal).
+
+            .. versionadded:: 1.0
+
+        See also
+        --------
+        numpy.diagonal : Equivalent numpy function.
+
+        Examples
+        --------
+        >>> from scipy.sparse import csr_array
+        >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+        >>> A.diagonal()
+        array([1, 0, 5])
+        >>> A.diagonal(k=1)
+        array([2, 3])
+        """
+        return self.tocsr().diagonal(k=k)
+
+    def trace(self, offset=0):
+        """Returns the sum along diagonals of the sparse array/matrix.
+
+        Parameters
+        ----------
+        offset : int, optional
+            Which diagonal to get, corresponding to elements a[i, i+offset].
+            Default: 0 (the main diagonal).
+
+        """
+        return self.diagonal(k=offset).sum()
+
+    def setdiag(self, values, k=0):
+        """
+        Set diagonal or off-diagonal elements of the array/matrix.
+
+        Parameters
+        ----------
+        values : array_like
+            New values of the diagonal elements.
+
+            Values may have any length. If the diagonal is longer than values,
+            then the remaining diagonal entries will not be set. If values are
+            longer than the diagonal, then the remaining values are ignored.
+
+            If a scalar value is given, all of the diagonal is set to it.
+
+        k : int, optional
+            Which off-diagonal to set, corresponding to elements a[i,i+k].
+            Default: 0 (the main diagonal).
+
+        """
+        M, N = self.shape
+        if (k > 0 and k >= N) or (k < 0 and -k >= M):
+            raise ValueError("k exceeds array dimensions")
+        self._setdiag(np.asarray(values), k)
+
+    def _setdiag(self, values, k):
+        """This part of the implementation gets overridden by the
+        different formats.
+        """
+        M, N = self.shape
+        if k < 0:
+            if values.ndim == 0:
+                # broadcast
+                max_index = min(M+k, N)
+                for i in range(max_index):
+                    self[i - k, i] = values
+            else:
+                max_index = min(M+k, N, len(values))
+                if max_index <= 0:
+                    return
+                for i, v in enumerate(values[:max_index]):
+                    self[i - k, i] = v
+        else:
+            if values.ndim == 0:
+                # broadcast
+                max_index = min(M, N-k)
+                for i in range(max_index):
+                    self[i, i + k] = values
+            else:
+                max_index = min(M, N-k, len(values))
+                if max_index <= 0:
+                    return
+                for i, v in enumerate(values[:max_index]):
+                    self[i, i + k] = v
+
+    def _process_toarray_args(self, order, out):
+        if out is not None:
+            if order is not None:
+                raise ValueError('order cannot be specified if out '
+                                 'is not None')
+            if out.shape != self.shape or out.dtype != self.dtype:
+                raise ValueError('out array must be same dtype and shape as '
+                                 'sparse array')
+            out[...] = 0.
+            return out
+        else:
+            return np.zeros(self.shape, dtype=self.dtype, order=order)
+
+    def _get_index_dtype(self, arrays=(), maxval=None, check_contents=False):
+        """
+        Determine index dtype for array.
+
+        This wraps _sputils.get_index_dtype, providing compatibility for both
+        array and matrix API sparse matrices. Matrix API sparse matrices would
+        attempt to downcast the indices - which can be computationally
+        expensive and undesirable for users. The array API changes this
+        behaviour.
+
+        See discussion: https://github.com/scipy/scipy/issues/16774
+
+        The get_index_dtype import is due to implementation details of the test
+        suite. It allows the decorator ``with_64bit_maxval_limit`` to mock a
+        lower int32 max value for checks on the matrix API's downcasting
+        behaviour.
+        """
+        from ._sputils import get_index_dtype
+
+        # Don't check contents for array API
+        return get_index_dtype(arrays,
+                               maxval,
+                               (check_contents and not isinstance(self, sparray)))
+
+
+class sparray:
+    """A namespace class to separate sparray from spmatrix"""
+
+
+sparray.__doc__ = _spbase.__doc__
+
+
+def issparse(x):
+    """Is `x` of a sparse array or sparse matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a sparse array or sparse matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a sparse array or a sparse matrix, False otherwise
+
+    Notes
+    -----
+    Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix.
+    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
+    """
+    return isinstance(x, _spbase)
+
+
+def isspmatrix(x):
+    """Is `x` of a sparse matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a sparse matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a sparse matrix, False otherwise
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_array, csr_matrix, isspmatrix
+    >>> isspmatrix(csr_matrix([[5]]))
+    True
+    >>> isspmatrix(csr_array([[5]]))
+    False
+    >>> isspmatrix(np.array([[5]]))
+    False
+    >>> isspmatrix(5)
+    False
+    """
+    return isinstance(x, spmatrix)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_bsr.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_bsr.py
new file mode 100644
index 0000000000000000000000000000000000000000..14cf85f8ccf8d7d2b4c63d19938b215e54a9736b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_bsr.py
@@ -0,0 +1,877 @@
+"""Compressed Block Sparse Row format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['bsr_array', 'bsr_matrix', 'isspmatrix_bsr']
+
+from warnings import warn
+
+import numpy as np
+
+from scipy._lib._util import copy_if_needed
+from ._matrix import spmatrix
+from ._data import _data_matrix, _minmax_mixin
+from ._compressed import _cs_matrix
+from ._base import issparse, _formats, _spbase, sparray
+from ._sputils import (isshape, getdtype, getdata, to_native, upcast,
+                       check_shape)
+from . import _sparsetools
+from ._sparsetools import (bsr_matvec, bsr_matvecs, csr_matmat_maxnnz,
+                           bsr_matmat, bsr_transpose, bsr_sort_indices,
+                           bsr_tocsr)
+
+
+class _bsr_base(_cs_matrix, _minmax_mixin):
+    _format = 'bsr'
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False,
+                 blocksize=None, *, maxprint=None):
+        _data_matrix.__init__(self, arg1, maxprint=maxprint)
+
+        if issparse(arg1):
+            if arg1.format == self.format and copy:
+                arg1 = arg1.copy()
+            else:
+                arg1 = arg1.tobsr(blocksize=blocksize)
+            self.indptr, self.indices, self.data, self._shape = (
+                arg1.indptr, arg1.indices, arg1.data, arg1._shape
+            )
+
+        elif isinstance(arg1,tuple):
+            if isshape(arg1):
+                # it's a tuple of matrix dimensions (M,N)
+                self._shape = check_shape(arg1)
+                M,N = self.shape
+                # process blocksize
+                if blocksize is None:
+                    blocksize = (1,1)
+                else:
+                    if not isshape(blocksize):
+                        raise ValueError(f'invalid blocksize={blocksize}')
+                    blocksize = tuple(blocksize)
+                self.data = np.zeros((0,) + blocksize, getdtype(dtype, default=float))
+
+                R,C = blocksize
+                if (M % R) != 0 or (N % C) != 0:
+                    raise ValueError('shape must be multiple of blocksize')
+
+                # Select index dtype large enough to pass array and
+                # scalar parameters to sparsetools
+                idx_dtype = self._get_index_dtype(maxval=max(M//R, N//C, R, C))
+                self.indices = np.zeros(0, dtype=idx_dtype)
+                self.indptr = np.zeros(M//R + 1, dtype=idx_dtype)
+
+            elif len(arg1) == 2:
+                # (data,(row,col)) format
+                coo = self._coo_container(arg1, dtype=dtype, shape=shape)
+                bsr = coo.tobsr(blocksize=blocksize)
+                self.indptr, self.indices, self.data, self._shape = (
+                    bsr.indptr, bsr.indices, bsr.data, bsr._shape
+                )
+
+            elif len(arg1) == 3:
+                # (data,indices,indptr) format
+                (data, indices, indptr) = arg1
+
+                # Select index dtype large enough to pass array and
+                # scalar parameters to sparsetools
+                maxval = 1
+                if shape is not None:
+                    maxval = max(shape)
+                if blocksize is not None:
+                    maxval = max(maxval, max(blocksize))
+                idx_dtype = self._get_index_dtype((indices, indptr), maxval=maxval,
+                                                  check_contents=True)
+                if not copy:
+                    copy = copy_if_needed
+                self.indices = np.array(indices, copy=copy, dtype=idx_dtype)
+                self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype)
+                self.data = getdata(data, copy=copy, dtype=dtype)
+                if self.data.ndim != 3:
+                    raise ValueError(
+                        f'BSR data must be 3-dimensional, got shape={self.data.shape}'
+                    )
+                if blocksize is not None:
+                    if not isshape(blocksize):
+                        raise ValueError(f'invalid blocksize={blocksize}')
+                    if tuple(blocksize) != self.data.shape[1:]:
+                        raise ValueError(
+                            f'mismatching blocksize={blocksize}'
+                            f' vs {self.data.shape[1:]}'
+                        )
+            else:
+                raise ValueError('unrecognized bsr_array constructor usage')
+        else:
+            # must be dense
+            try:
+                arg1 = np.asarray(arg1)
+            except Exception as e:
+                raise ValueError("unrecognized form for "
+                                 f"{self.format}_matrix constructor") from e
+            if isinstance(self, sparray) and arg1.ndim != 2:
+                raise ValueError(f"BSR arrays don't support {arg1.ndim}D input. Use 2D")
+            arg1 = self._coo_container(arg1, dtype=dtype).tobsr(blocksize=blocksize)
+            self.indptr, self.indices, self.data, self._shape = (
+                arg1.indptr, arg1.indices, arg1.data, arg1._shape
+            )
+
+        if shape is not None:
+            self._shape = check_shape(shape)
+        else:
+            if self.shape is None:
+                # shape not already set, try to infer dimensions
+                try:
+                    M = len(self.indptr) - 1
+                    N = self.indices.max() + 1
+                except Exception as e:
+                    raise ValueError('unable to infer matrix dimensions') from e
+                else:
+                    R,C = self.blocksize
+                    self._shape = check_shape((M*R,N*C))
+
+        if self.shape is None:
+            if shape is None:
+                # TODO infer shape here
+                raise ValueError('need to infer shape')
+            else:
+                self._shape = check_shape(shape)
+
+        if dtype is not None:
+            self.data = self.data.astype(getdtype(dtype, self.data), copy=False)
+
+        self.check_format(full_check=False)
+
+    def check_format(self, full_check=True):
+        """Check whether the array/matrix respects the BSR format.
+
+        Parameters
+        ----------
+        full_check : bool, optional
+            If `True`, run rigorous check, scanning arrays for valid values.
+            Note that activating those check might copy arrays for casting,
+            modifying indices and index pointers' inplace.
+            If `False`, run basic checks on attributes. O(1) operations.
+            Default is `True`.
+        """
+        M,N = self.shape
+        R,C = self.blocksize
+
+        # index arrays should have integer data types
+        if self.indptr.dtype.kind != 'i':
+            warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})",
+                 stacklevel=2)
+        if self.indices.dtype.kind != 'i':
+            warn(f"indices array has non-integer dtype ({self.indices.dtype.name})",
+                 stacklevel=2)
+
+        # check array shapes
+        if self.indices.ndim != 1 or self.indptr.ndim != 1:
+            raise ValueError("indices, and indptr should be 1-D")
+        if self.data.ndim != 3:
+            raise ValueError("data should be 3-D")
+
+        # check index pointer
+        if (len(self.indptr) != M//R + 1):
+            raise ValueError("index pointer size (%d) should be (%d)" %
+                                (len(self.indptr), M//R + 1))
+        if (self.indptr[0] != 0):
+            raise ValueError("index pointer should start with 0")
+
+        # check index and data arrays
+        if (len(self.indices) != len(self.data)):
+            raise ValueError("indices and data should have the same size")
+        if (self.indptr[-1] > len(self.indices)):
+            raise ValueError("Last value of index pointer should be less than "
+                                "the size of index and data arrays")
+
+        self.prune()
+
+        if full_check:
+            # check format validity (more expensive)
+            if self.nnz > 0:
+                if self.indices.max() >= N//C:
+                    raise ValueError("column index values must be < %d (now max %d)"
+                                     % (N//C, self.indices.max()))
+                if self.indices.min() < 0:
+                    raise ValueError("column index values must be >= 0")
+                if np.diff(self.indptr).min() < 0:
+                    raise ValueError("index pointer values must form a "
+                                        "non-decreasing sequence")
+
+            idx_dtype = self._get_index_dtype((self.indices, self.indptr))
+            self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
+            self.indices = np.asarray(self.indices, dtype=idx_dtype)
+            self.data = to_native(self.data)
+        # if not self.has_sorted_indices():
+        #    warn('Indices were not in sorted order. Sorting indices.')
+        #    self.sort_indices(check_first=False)
+
+    @property
+    def blocksize(self) -> tuple:
+        """Block size of the matrix."""
+        return self.data.shape[1:]
+
+    def _getnnz(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError("_getnnz over an axis is not implemented "
+                                      "for BSR format")
+        R, C = self.blocksize
+        return int(self.indptr[-1]) * R * C
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def count_nonzero(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError(
+                "count_nonzero over axis is not implemented for BSR format."
+            )
+        return np.count_nonzero(self._deduped_data())
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def __repr__(self):
+        _, fmt = _formats[self.format]
+        sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
+        b = 'x'.join(str(x) for x in self.blocksize)
+        return (
+            f"<{fmt} sparse {sparse_cls} of dtype '{self.dtype}'\n"
+            f"\twith {self.nnz} stored elements (blocksize={b}) and shape {self.shape}>"
+        )
+
+    def diagonal(self, k=0):
+        rows, cols = self.shape
+        if k <= -rows or k >= cols:
+            return np.empty(0, dtype=self.data.dtype)
+        R, C = self.blocksize
+        y = np.zeros(min(rows + min(k, 0), cols - max(k, 0)),
+                     dtype=upcast(self.dtype))
+        _sparsetools.bsr_diagonal(k, rows // R, cols // C, R, C,
+                                  self.indptr, self.indices,
+                                  np.ravel(self.data), y)
+        return y
+
+    diagonal.__doc__ = _spbase.diagonal.__doc__
+
+    ##########################
+    # NotImplemented methods #
+    ##########################
+
+    def __getitem__(self,key):
+        raise NotImplementedError
+
+    def __setitem__(self,key,val):
+        raise NotImplementedError
+
+    ######################
+    # Arithmetic methods #
+    ######################
+
+    def _add_dense(self, other):
+        return self.tocoo(copy=False)._add_dense(other)
+
+    def _matmul_vector(self, other):
+        M,N = self.shape
+        R,C = self.blocksize
+
+        result = np.zeros(self.shape[0], dtype=upcast(self.dtype, other.dtype))
+
+        bsr_matvec(M//R, N//C, R, C,
+            self.indptr, self.indices, self.data.ravel(),
+            other, result)
+
+        return result
+
+    def _matmul_multivector(self,other):
+        R,C = self.blocksize
+        M,N = self.shape
+        n_vecs = other.shape[1]  # number of column vectors
+
+        result = np.zeros((M,n_vecs), dtype=upcast(self.dtype,other.dtype))
+
+        bsr_matvecs(M//R, N//C, n_vecs, R, C,
+                self.indptr, self.indices, self.data.ravel(),
+                other.ravel(), result.ravel())
+
+        return result
+
+    def _matmul_sparse(self, other):
+        M, K1 = self.shape
+        K2, N = other.shape
+
+        R,n = self.blocksize
+
+        # convert to this format
+        if other.format == "bsr":
+            C = other.blocksize[1]
+        else:
+            C = 1
+
+        if other.format == "csr" and n == 1:
+            other = other.tobsr(blocksize=(n,C), copy=False)  # lightweight conversion
+        else:
+            other = other.tobsr(blocksize=(n,C))
+
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                           other.indptr, other.indices))
+
+        bnnz = csr_matmat_maxnnz(M//R, N//C,
+                                 self.indptr.astype(idx_dtype),
+                                 self.indices.astype(idx_dtype),
+                                 other.indptr.astype(idx_dtype),
+                                 other.indices.astype(idx_dtype))
+
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                           other.indptr, other.indices),
+                                          maxval=bnnz)
+        indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
+        indices = np.empty(bnnz, dtype=idx_dtype)
+        data = np.empty(R*C*bnnz, dtype=upcast(self.dtype,other.dtype))
+
+        bsr_matmat(bnnz, M//R, N//C, R, C, n,
+                   self.indptr.astype(idx_dtype),
+                   self.indices.astype(idx_dtype),
+                   np.ravel(self.data),
+                   other.indptr.astype(idx_dtype),
+                   other.indices.astype(idx_dtype),
+                   np.ravel(other.data),
+                   indptr,
+                   indices,
+                   data)
+
+        data = data.reshape(-1,R,C)
+
+        # TODO eliminate zeros
+
+        return self._bsr_container(
+            (data, indices, indptr), shape=(M, N), blocksize=(R, C)
+        )
+
+    ######################
+    # Conversion methods #
+    ######################
+
+    def tobsr(self, blocksize=None, copy=False):
+        """Convert this array/matrix into Block Sparse Row Format.
+
+        With copy=False, the data/indices may be shared between this
+        array/matrix and the resultant bsr_array/bsr_matrix.
+
+        If blocksize=(R, C) is provided, it will be used for determining
+        block size of the bsr_array/bsr_matrix.
+        """
+        if blocksize not in [None, self.blocksize]:
+            return self.tocsr().tobsr(blocksize=blocksize)
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    def tocsr(self, copy=False):
+        M, N = self.shape
+        R, C = self.blocksize
+        nnz = self.nnz
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+                                          maxval=max(nnz, N))
+        indptr = np.empty(M + 1, dtype=idx_dtype)
+        indices = np.empty(nnz, dtype=idx_dtype)
+        data = np.empty(nnz, dtype=upcast(self.dtype))
+
+        bsr_tocsr(M // R,  # n_brow
+                  N // C,  # n_bcol
+                  R, C,
+                  self.indptr.astype(idx_dtype, copy=False),
+                  self.indices.astype(idx_dtype, copy=False),
+                  self.data,
+                  indptr,
+                  indices,
+                  data)
+        return self._csr_container((data, indices, indptr), shape=self.shape)
+
+    tocsr.__doc__ = _spbase.tocsr.__doc__
+
+    def tocsc(self, copy=False):
+        return self.tocsr(copy=False).tocsc(copy=copy)
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def tocoo(self, copy=True):
+        """Convert this array/matrix to COOrdinate format.
+
+        When copy=False the data array will be shared between
+        this array/matrix and the resultant coo_array/coo_matrix.
+        """
+
+        M,N = self.shape
+        R,C = self.blocksize
+
+        indptr_diff = np.diff(self.indptr)
+        if indptr_diff.dtype.itemsize > np.dtype(np.intp).itemsize:
+            # Check for potential overflow
+            indptr_diff_limited = indptr_diff.astype(np.intp)
+            if np.any(indptr_diff_limited != indptr_diff):
+                raise ValueError("Matrix too big to convert")
+            indptr_diff = indptr_diff_limited
+
+        idx_dtype = self._get_index_dtype(maxval=max(M, N))
+        row = (R * np.arange(M//R, dtype=idx_dtype)).repeat(indptr_diff)
+        row = row.repeat(R*C).reshape(-1,R,C)
+        row += np.tile(np.arange(R, dtype=idx_dtype).reshape(-1,1), (1,C))
+        row = row.reshape(-1)
+
+        col = ((C * self.indices).astype(idx_dtype, copy=False)
+               .repeat(R*C).reshape(-1,R,C))
+        col += np.tile(np.arange(C, dtype=idx_dtype), (R,1))
+        col = col.reshape(-1)
+
+        data = self.data.reshape(-1)
+
+        if copy:
+            data = data.copy()
+
+        return self._coo_container(
+            (data, (row, col)), shape=self.shape
+        )
+
+    def toarray(self, order=None, out=None):
+        return self.tocoo(copy=False).toarray(order=order, out=out)
+
+    toarray.__doc__ = _spbase.toarray.__doc__
+
+    def transpose(self, axes=None, copy=False):
+        if axes is not None and axes != (1, 0):
+            raise ValueError("Sparse matrices do not support "
+                              "an 'axes' parameter because swapping "
+                              "dimensions is the only logical permutation.")
+
+        R, C = self.blocksize
+        M, N = self.shape
+        NBLK = self.nnz//(R*C)
+
+        if self.nnz == 0:
+            return self._bsr_container((N, M), blocksize=(C, R),
+                                       dtype=self.dtype, copy=copy)
+
+        indptr = np.empty(N//C + 1, dtype=self.indptr.dtype)
+        indices = np.empty(NBLK, dtype=self.indices.dtype)
+        data = np.empty((NBLK, C, R), dtype=self.data.dtype)
+
+        bsr_transpose(M//R, N//C, R, C,
+                      self.indptr, self.indices, self.data.ravel(),
+                      indptr, indices, data.ravel())
+
+        return self._bsr_container((data, indices, indptr),
+                                   shape=(N, M), copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    ##############################################################
+    # methods that examine or modify the internal data structure #
+    ##############################################################
+
+    def eliminate_zeros(self):
+        """Remove zero elements in-place."""
+
+        if not self.nnz:
+            return  # nothing to do
+
+        R,C = self.blocksize
+        M,N = self.shape
+
+        mask = (self.data != 0).reshape(-1,R*C).sum(axis=1)  # nonzero blocks
+
+        nonzero_blocks = mask.nonzero()[0]
+
+        self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks]
+
+        # modifies self.indptr and self.indices *in place*
+        _sparsetools.csr_eliminate_zeros(M//R, N//C, self.indptr,
+                                         self.indices, mask)
+        self.prune()
+
+    def sum_duplicates(self):
+        """Eliminate duplicate array/matrix entries by adding them together
+
+        The is an *in place* operation
+        """
+        if self.has_canonical_format:
+            return
+        self.sort_indices()
+        R, C = self.blocksize
+        M, N = self.shape
+
+        # port of _sparsetools.csr_sum_duplicates
+        n_row = M // R
+        nnz = 0
+        row_end = 0
+        for i in range(n_row):
+            jj = row_end
+            row_end = self.indptr[i+1]
+            while jj < row_end:
+                j = self.indices[jj]
+                x = self.data[jj]
+                jj += 1
+                while jj < row_end and self.indices[jj] == j:
+                    x += self.data[jj]
+                    jj += 1
+                self.indices[nnz] = j
+                self.data[nnz] = x
+                nnz += 1
+            self.indptr[i+1] = nnz
+
+        self.prune()  # nnz may have changed
+        self.has_canonical_format = True
+
+    def sort_indices(self):
+        """Sort the indices of this array/matrix *in place*
+        """
+        if self.has_sorted_indices:
+            return
+
+        R,C = self.blocksize
+        M,N = self.shape
+
+        bsr_sort_indices(M//R, N//C, R, C, self.indptr, self.indices, self.data.ravel())
+
+        self.has_sorted_indices = True
+
+    def prune(self):
+        """Remove empty space after all non-zero elements.
+        """
+
+        R,C = self.blocksize
+        M,N = self.shape
+
+        if len(self.indptr) != M//R + 1:
+            raise ValueError("index pointer has invalid length")
+
+        bnnz = self.indptr[-1]
+
+        if len(self.indices) < bnnz:
+            raise ValueError("indices array has too few elements")
+        if len(self.data) < bnnz:
+            raise ValueError("data array has too few elements")
+
+        self.data = self.data[:bnnz]
+        self.indices = self.indices[:bnnz]
+
+    # utility functions
+    def _binopt(self, other, op, in_shape=None, out_shape=None):
+        """Apply the binary operation fn to two sparse matrices."""
+
+        # Ideally we'd take the GCDs of the blocksize dimensions
+        # and explode self and other to match.
+        other = self.__class__(other, blocksize=self.blocksize)
+
+        # e.g. bsr_plus_bsr, etc.
+        fn = getattr(_sparsetools, self.format + op + self.format)
+
+        R,C = self.blocksize
+
+        max_bnnz = len(self.data) + len(other.data)
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                           other.indptr, other.indices),
+                                          maxval=max_bnnz)
+        indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
+        indices = np.empty(max_bnnz, dtype=idx_dtype)
+
+        bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_']
+        if op in bool_ops:
+            data = np.empty(R*C*max_bnnz, dtype=np.bool_)
+        else:
+            data = np.empty(R*C*max_bnnz, dtype=upcast(self.dtype,other.dtype))
+
+        fn(self.shape[0]//R, self.shape[1]//C, R, C,
+           self.indptr.astype(idx_dtype),
+           self.indices.astype(idx_dtype),
+           self.data,
+           other.indptr.astype(idx_dtype),
+           other.indices.astype(idx_dtype),
+           np.ravel(other.data),
+           indptr,
+           indices,
+           data)
+
+        actual_bnnz = indptr[-1]
+        indices = indices[:actual_bnnz]
+        data = data[:R*C*actual_bnnz]
+
+        if actual_bnnz < max_bnnz/2:
+            indices = indices.copy()
+            data = data.copy()
+
+        data = data.reshape(-1,R,C)
+
+        return self.__class__((data, indices, indptr), shape=self.shape)
+
+    # needed by _data_matrix
+    def _with_data(self,data,copy=True):
+        """Returns a matrix with the same sparsity structure as self,
+        but with different data.  By default the structure arrays
+        (i.e. .indptr and .indices) are copied.
+        """
+        if copy:
+            return self.__class__((data,self.indices.copy(),self.indptr.copy()),
+                                   shape=self.shape,dtype=data.dtype)
+        else:
+            return self.__class__((data,self.indices,self.indptr),
+                                   shape=self.shape,dtype=data.dtype)
+
+#    # these functions are used by the parent class
+#    # to remove redundancy between bsc_matrix and bsr_matrix
+#    def _swap(self,x):
+#        """swap the members of x if this is a column-oriented matrix
+#        """
+#        return (x[0],x[1])
+
+    def _broadcast_to(self, shape, copy=False):
+        return _spbase._broadcast_to(self, shape, copy)
+
+
+def isspmatrix_bsr(x):
+    """Is `x` of a bsr_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a bsr matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a bsr matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import bsr_array, bsr_matrix, csr_matrix, isspmatrix_bsr
+    >>> isspmatrix_bsr(bsr_matrix([[5]]))
+    True
+    >>> isspmatrix_bsr(bsr_array([[5]]))
+    False
+    >>> isspmatrix_bsr(csr_matrix([[5]]))
+    False
+    """
+    return isinstance(x, bsr_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class bsr_array(_bsr_base, sparray):
+    """
+    Block Sparse Row format sparse array.
+
+    This can be instantiated in several ways:
+        bsr_array(D, [blocksize=(R,C)])
+            where D is a 2-D ndarray.
+
+        bsr_array(S, [blocksize=(R,C)])
+            with another sparse array or matrix S (equivalent to S.tobsr())
+
+        bsr_array((M, N), [blocksize=(R,C), dtype])
+            to construct an empty sparse array with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        bsr_array((data, ij), [blocksize=(R,C), shape=(M, N)])
+            where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
+
+        bsr_array((data, indices, indptr), [shape=(M, N)])
+            is the standard BSR representation where the block column
+            indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
+            and their corresponding block values are stored in
+            ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
+            supplied, the array dimensions are inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        BSR format data array of the array
+    indices
+        BSR format index array of the array
+    indptr
+        BSR format index pointer array of the array
+    blocksize
+        Block size
+    has_sorted_indices : bool
+        Whether indices are sorted
+    has_canonical_format : bool
+    T
+
+    Notes
+    -----
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    **Summary of BSR format**
+
+    The Block Sparse Row (BSR) format is very similar to the Compressed
+    Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
+    sub matrices like the last example below. Such sparse block matrices often
+    arise in vector-valued finite element discretizations. In such cases, BSR is
+    considerably more efficient than CSR and CSC for many sparse arithmetic
+    operations.
+
+    **Blocksize**
+
+    The blocksize (R,C) must evenly divide the shape of the sparse array (M,N).
+    That is, R and C must satisfy the relationship ``M % R = 0`` and
+    ``N % C = 0``.
+
+    If no blocksize is specified, a simple heuristic is applied to determine
+    an appropriate blocksize.
+
+    **Canonical Format**
+
+    In canonical format, there are no duplicate blocks and indices are sorted
+    per row.
+
+    **Limitations**
+
+    Block Sparse Row format sparse arrays do not support slicing.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import bsr_array
+    >>> bsr_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 0, 1, 2, 2, 2])
+    >>> col = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3 ,4, 5, 6])
+    >>> bsr_array((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
+    >>> bsr_array((data,indices,indptr), shape=(6, 6)).toarray()
+    array([[1, 1, 0, 0, 2, 2],
+           [1, 1, 0, 0, 2, 2],
+           [0, 0, 0, 0, 3, 3],
+           [0, 0, 0, 0, 3, 3],
+           [4, 4, 5, 5, 6, 6],
+           [4, 4, 5, 5, 6, 6]])
+
+    """
+
+
+class bsr_matrix(spmatrix, _bsr_base):
+    """
+    Block Sparse Row format sparse matrix.
+
+    This can be instantiated in several ways:
+        bsr_matrix(D, [blocksize=(R,C)])
+            where D is a 2-D ndarray.
+
+        bsr_matrix(S, [blocksize=(R,C)])
+            with another sparse array or matrix S (equivalent to S.tobsr())
+
+        bsr_matrix((M, N), [blocksize=(R,C), dtype])
+            to construct an empty sparse matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        bsr_matrix((data, ij), [blocksize=(R,C), shape=(M, N)])
+            where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
+
+        bsr_matrix((data, indices, indptr), [shape=(M, N)])
+            is the standard BSR representation where the block column
+            indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
+            and their corresponding block values are stored in
+            ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
+            supplied, the matrix dimensions are inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        BSR format data array of the matrix
+    indices
+        BSR format index array of the matrix
+    indptr
+        BSR format index pointer array of the matrix
+    blocksize
+        Block size
+    has_sorted_indices : bool
+        Whether indices are sorted
+    has_canonical_format : bool
+    T
+
+    Notes
+    -----
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    **Summary of BSR format**
+
+    The Block Sparse Row (BSR) format is very similar to the Compressed
+    Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
+    sub matrices like the last example below. Such sparse block matrices often
+    arise in vector-valued finite element discretizations. In such cases, BSR is
+    considerably more efficient than CSR and CSC for many sparse arithmetic
+    operations.
+
+    **Blocksize**
+
+    The blocksize (R,C) must evenly divide the shape of the sparse matrix (M,N).
+    That is, R and C must satisfy the relationship ``M % R = 0`` and
+    ``N % C = 0``.
+
+    If no blocksize is specified, a simple heuristic is applied to determine
+    an appropriate blocksize.
+
+    **Canonical Format**
+
+    In canonical format, there are no duplicate blocks and indices are sorted
+    per row.
+
+    **Limitations**
+
+    Block Sparse Row format sparse matrices do not support slicing.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import bsr_matrix
+    >>> bsr_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 0, 1, 2, 2, 2])
+    >>> col = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3 ,4, 5, 6])
+    >>> bsr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
+    >>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray()
+    array([[1, 1, 0, 0, 2, 2],
+           [1, 1, 0, 0, 2, 2],
+           [0, 0, 0, 0, 3, 3],
+           [0, 0, 0, 0, 3, 3],
+           [4, 4, 5, 5, 6, 6],
+           [4, 4, 5, 5, 6, 6]])
+
+    """
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_compressed.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_compressed.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5f43c16bd924ac6bd70cfd4634dc3afcd298391
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_compressed.py
@@ -0,0 +1,1500 @@
+"""Base class for sparse matrix formats using compressed storage."""
+__all__ = []
+
+from warnings import warn
+import itertools
+import operator
+
+import numpy as np
+from scipy._lib._util import _prune_array, copy_if_needed
+
+from ._base import _spbase, issparse, sparray, SparseEfficiencyWarning
+from ._data import _data_matrix, _minmax_mixin
+from . import _sparsetools
+from ._sparsetools import (get_csr_submatrix, csr_sample_offsets, csr_todense,
+                           csr_sample_values, csr_row_index, csr_row_slice,
+                           csr_column_index1, csr_column_index2)
+from ._index import IndexMixin
+from ._sputils import (upcast, upcast_char, to_native, isdense, isshape,
+                       getdtype, isscalarlike, isintlike, downcast_intp_index,
+                       get_sum_dtype, check_shape, get_index_dtype, broadcast_shapes,
+                       is_pydata_spmatrix)
+
+
+class _cs_matrix(_data_matrix, _minmax_mixin, IndexMixin):
+    """
+    base array/matrix class for compressed row- and column-oriented arrays/matrices
+    """
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _data_matrix.__init__(self, arg1, maxprint=maxprint)
+
+        if issparse(arg1):
+            if arg1.format == self.format and copy:
+                arg1 = arg1.copy()
+            else:
+                arg1 = arg1.asformat(self.format)
+            self.indptr, self.indices, self.data, self._shape = (
+                arg1.indptr, arg1.indices, arg1.data, arg1._shape
+            )
+
+        elif isinstance(arg1, tuple):
+            if isshape(arg1, allow_nd=self._allow_nd):
+                # It's a tuple of matrix dimensions (M, N)
+                # create empty matrix
+                self._shape = check_shape(arg1, allow_nd=self._allow_nd)
+                M, N = self._swap(self._shape_as_2d)
+                # Select index dtype large enough to pass array and
+                # scalar parameters to sparsetools
+                idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+                self.data = np.zeros(0, getdtype(dtype, default=float))
+                self.indices = np.zeros(0, idx_dtype)
+                self.indptr = np.zeros(M + 1, dtype=idx_dtype)
+            else:
+                if len(arg1) == 2:
+                    # (data, ij) format
+                    coo = self._coo_container(arg1, shape=shape, dtype=dtype)
+                    arrays = coo._coo_to_compressed(self._swap)
+                    self.indptr, self.indices, self.data, self._shape = arrays
+                    self.sum_duplicates()
+                elif len(arg1) == 3:
+                    # (data, indices, indptr) format
+                    (data, indices, indptr) = arg1
+
+                    # Select index dtype large enough to pass array and
+                    # scalar parameters to sparsetools
+                    maxval = None
+                    if shape is not None and 0 not in shape:
+                        maxval = max(shape)
+                    idx_dtype = self._get_index_dtype((indices, indptr),
+                                                maxval=maxval,
+                                                check_contents=True)
+
+                    if not copy:
+                        copy = copy_if_needed
+                    self.indices = np.array(indices, copy=copy, dtype=idx_dtype)
+                    self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype)
+                    self.data = np.array(data, copy=copy, dtype=dtype)
+                else:
+                    raise ValueError(f"unrecognized {self.__class__.__name__} "
+                                     f"constructor input: {arg1}")
+
+        else:
+            # must be dense
+            try:
+                arg1 = np.asarray(arg1)
+            except Exception as e:
+                raise ValueError(f"unrecognized {self.__class__.__name__} "
+                                 f"constructor input: {arg1}") from e
+            if isinstance(self, sparray) and arg1.ndim != 2 and self.format == "csc":
+                raise ValueError(f"CSC arrays don't support {arg1.ndim}D input. Use 2D")
+            if arg1.ndim > 2:
+                raise ValueError(f"CSR arrays don't yet support {arg1.ndim}D.")
+
+            coo = self._coo_container(arg1, dtype=dtype)
+            arrays = coo._coo_to_compressed(self._swap)
+            self.indptr, self.indices, self.data, self._shape = arrays
+
+        # Read matrix dimensions given, if any
+        if shape is not None:
+            self._shape = check_shape(shape, allow_nd=self._allow_nd)
+        elif self.shape is None:
+            # shape not already set, try to infer dimensions
+            try:
+                M = len(self.indptr) - 1
+                N = self.indices.max() + 1
+            except Exception as e:
+                raise ValueError('unable to infer matrix dimensions') from e
+
+            self._shape = check_shape(self._swap((M, N)), allow_nd=self._allow_nd)
+
+        if dtype is not None:
+            newdtype = getdtype(dtype)
+            self.data = self.data.astype(newdtype, copy=False)
+
+        self.check_format(full_check=False)
+
+    def _getnnz(self, axis=None):
+        if axis is None:
+            return int(self.indptr[-1])
+        elif self.ndim == 1:
+            if axis in (0, -1):
+                return int(self.indptr[-1])
+            raise ValueError('axis out of bounds')
+        else:
+            if axis < 0:
+                axis += 2
+            axis, _ = self._swap((axis, 1 - axis))
+            _, N = self._swap(self.shape)
+            if axis == 0:
+                return np.bincount(downcast_intp_index(self.indices), minlength=N)
+            elif axis == 1:
+                return np.diff(self.indptr)
+            raise ValueError('axis out of bounds')
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def count_nonzero(self, axis=None):
+        self.sum_duplicates()
+        if axis is None:
+            return np.count_nonzero(self.data)
+
+        if self.ndim == 1:
+            if axis not in (0, -1):
+                raise ValueError('axis out of bounds')
+            return np.count_nonzero(self.data)
+
+        if axis < 0:
+            axis += 2
+        axis, _ = self._swap((axis, 1 - axis))
+        if axis == 0:
+            _, N = self._swap(self.shape)
+            mask = self.data != 0
+            idx = self.indices if mask.all() else self.indices[mask]
+            return np.bincount(downcast_intp_index(idx), minlength=N)
+        elif axis == 1:
+            if self.data.all():
+                return np.diff(self.indptr)
+            pairs = itertools.pairwise(self.indptr)
+            return np.array([np.count_nonzero(self.data[i:j]) for i, j in pairs])
+        else:
+            raise ValueError('axis out of bounds')
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def check_format(self, full_check=True):
+        """Check whether the array/matrix respects the CSR or CSC format.
+
+        Parameters
+        ----------
+        full_check : bool, optional
+            If `True`, run rigorous check, scanning arrays for valid values.
+            Note that activating those check might copy arrays for casting,
+            modifying indices and index pointers' inplace.
+            If `False`, run basic checks on attributes. O(1) operations.
+            Default is `True`.
+        """
+        # index arrays should have integer data types
+        if self.indptr.dtype.kind != 'i':
+            warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})",
+                 stacklevel=3)
+        if self.indices.dtype.kind != 'i':
+            warn(f"indices array has non-integer dtype ({self.indices.dtype.name})",
+                 stacklevel=3)
+
+        # check array shapes
+        for x in [self.data.ndim, self.indices.ndim, self.indptr.ndim]:
+            if x != 1:
+                raise ValueError('data, indices, and indptr should be 1-D')
+
+        # check index pointer. Use _swap to determine proper bounds
+        M, N = self._swap(self._shape_as_2d)
+
+        if (len(self.indptr) != M + 1):
+            raise ValueError(f"index pointer size {len(self.indptr)} should be {M + 1}")
+        if (self.indptr[0] != 0):
+            raise ValueError("index pointer should start with 0")
+
+        # check index and data arrays
+        if (len(self.indices) != len(self.data)):
+            raise ValueError("indices and data should have the same size")
+        if (self.indptr[-1] > len(self.indices)):
+            raise ValueError("Last value of index pointer should be less than "
+                             "the size of index and data arrays")
+
+        self.prune()
+
+        if full_check:
+            # check format validity (more expensive)
+            if self.nnz > 0:
+                if self.indices.max() >= N:
+                    raise ValueError(f"indices must be < {N}")
+                if self.indices.min() < 0:
+                    raise ValueError("indices must be >= 0")
+                if np.diff(self.indptr).min() < 0:
+                    raise ValueError("indptr must be a non-decreasing sequence")
+
+            idx_dtype = self._get_index_dtype((self.indptr, self.indices))
+            self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
+            self.indices = np.asarray(self.indices, dtype=idx_dtype)
+            self.data = to_native(self.data)
+
+        # if not self.has_sorted_indices():
+        #    warn('Indices were not in sorted order.  Sorting indices.')
+        #    self.sort_indices()
+        #    assert(self.has_sorted_indices())
+        # TODO check for duplicates?
+
+    #######################
+    # Boolean comparisons #
+    #######################
+
+    def _scalar_binopt(self, other, op):
+        """Scalar version of self._binopt, for cases in which no new nonzeros
+        are added. Produces a new sparse array in canonical form.
+        """
+        self.sum_duplicates()
+        res = self._with_data(op(self.data, other), copy=True)
+        res.eliminate_zeros()
+        return res
+
+    def __eq__(self, other):
+        # Scalar other.
+        if isscalarlike(other):
+            if np.isnan(other):
+                return self.__class__(self.shape, dtype=np.bool_)
+
+            if other == 0:
+                warn("Comparing a sparse matrix with 0 using == is inefficient"
+                     ", try using != instead.", SparseEfficiencyWarning,
+                     stacklevel=3)
+                all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
+                inv = self._scalar_binopt(other, operator.ne)
+                return all_true - inv
+            else:
+                return self._scalar_binopt(other, operator.eq)
+        # Dense other.
+        elif isdense(other):
+            return self.todense() == other
+        # Pydata sparse other.
+        elif is_pydata_spmatrix(other):
+            return NotImplemented
+        # Sparse other.
+        elif issparse(other):
+            warn("Comparing sparse matrices using == is inefficient, try using"
+                 " != instead.", SparseEfficiencyWarning, stacklevel=3)
+            # TODO sparse broadcasting
+            if self.shape != other.shape:
+                return False
+            elif self.format != other.format:
+                other = other.asformat(self.format)
+            res = self._binopt(other, '_ne_')
+            all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
+            return all_true - res
+        else:
+            return NotImplemented
+
+    def __ne__(self, other):
+        # Scalar other.
+        if isscalarlike(other):
+            if np.isnan(other):
+                warn("Comparing a sparse matrix with nan using != is"
+                     " inefficient", SparseEfficiencyWarning, stacklevel=3)
+                all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
+                return all_true
+            elif other != 0:
+                warn("Comparing a sparse matrix with a nonzero scalar using !="
+                     " is inefficient, try using == instead.",
+                     SparseEfficiencyWarning, stacklevel=3)
+                all_true = self.__class__(np.ones(self.shape), dtype=np.bool_)
+                inv = self._scalar_binopt(other, operator.eq)
+                return all_true - inv
+            else:
+                return self._scalar_binopt(other, operator.ne)
+        # Dense other.
+        elif isdense(other):
+            return self.todense() != other
+        # Pydata sparse other.
+        elif is_pydata_spmatrix(other):
+            return NotImplemented
+        # Sparse other.
+        elif issparse(other):
+            # TODO sparse broadcasting
+            if self.shape != other.shape:
+                return True
+            elif self.format != other.format:
+                other = other.asformat(self.format)
+            return self._binopt(other, '_ne_')
+        else:
+            return NotImplemented
+
+    def _inequality(self, other, op, op_name, bad_scalar_msg):
+        # Scalar other.
+        if isscalarlike(other):
+            if 0 == other and op_name in ('_le_', '_ge_'):
+                raise NotImplementedError(" >= and <= don't work with 0.")
+            elif op(0, other):
+                warn(bad_scalar_msg, SparseEfficiencyWarning, stacklevel=3)
+                other_arr = np.empty(self.shape, dtype=np.result_type(other))
+                other_arr.fill(other)
+                other_arr = self.__class__(other_arr)
+                return self._binopt(other_arr, op_name)
+            else:
+                return self._scalar_binopt(other, op)
+        # Dense other.
+        elif isdense(other):
+            return op(self.todense(), other)
+        # Sparse other.
+        elif issparse(other):
+            # TODO sparse broadcasting
+            if self.shape != other.shape:
+                raise ValueError("inconsistent shapes")
+            elif self.format != other.format:
+                other = other.asformat(self.format)
+            if op_name not in ('_ge_', '_le_'):
+                return self._binopt(other, op_name)
+
+            warn("Comparing sparse matrices using >= and <= is inefficient, "
+                 "using <, >, or !=, instead.",
+                 SparseEfficiencyWarning, stacklevel=3)
+            all_true = self.__class__(np.ones(self.shape, dtype=np.bool_))
+            res = self._binopt(other, '_gt_' if op_name == '_le_' else '_lt_')
+            return all_true - res
+        else:
+            return NotImplemented
+
+    def __lt__(self, other):
+        return self._inequality(other, operator.lt, '_lt_',
+                                "Comparing a sparse matrix with a scalar "
+                                "greater than zero using < is inefficient, "
+                                "try using >= instead.")
+
+    def __gt__(self, other):
+        return self._inequality(other, operator.gt, '_gt_',
+                                "Comparing a sparse matrix with a scalar "
+                                "less than zero using > is inefficient, "
+                                "try using <= instead.")
+
+    def __le__(self, other):
+        return self._inequality(other, operator.le, '_le_',
+                                "Comparing a sparse matrix with a scalar "
+                                "greater than zero using <= is inefficient, "
+                                "try using > instead.")
+
+    def __ge__(self, other):
+        return self._inequality(other, operator.ge, '_ge_',
+                                "Comparing a sparse matrix with a scalar "
+                                "less than zero using >= is inefficient, "
+                                "try using < instead.")
+
+    #################################
+    # Arithmetic operator overrides #
+    #################################
+
+    def _add_dense(self, other):
+        if other.shape != self.shape:
+            raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
+        dtype = upcast_char(self.dtype.char, other.dtype.char)
+        order = self._swap('CF')[0]
+        result = np.array(other, dtype=dtype, order=order, copy=True)
+        y = result if result.flags.c_contiguous else result.T
+        M, N = self._swap(self._shape_as_2d)
+        csr_todense(M, N, self.indptr, self.indices, self.data, y)
+        return self._container(result, copy=False)
+
+    def _add_sparse(self, other):
+        return self._binopt(other, '_plus_')
+
+    def _sub_sparse(self, other):
+        return self._binopt(other, '_minus_')
+
+    def multiply(self, other):
+        """Point-wise multiplication by array/matrix, vector, or scalar."""
+        # Scalar multiplication.
+        if isscalarlike(other):
+            return self._mul_scalar(other)
+        # Sparse matrix or vector.
+        if issparse(other):
+            if self.shape == other.shape:
+                other = self.__class__(other)
+                return self._binopt(other, '_elmul_')
+            # Single element.
+            if other.shape == (1, 1):
+                result = self._mul_scalar(other.toarray()[0, 0])
+                if self.ndim == 1:
+                    return result.reshape((1, self.shape[0]))
+                return result
+            if other.shape == (1,):
+                return self._mul_scalar(other.toarray()[0])
+            if self.shape in ((1,), (1, 1)):
+                return other._mul_scalar(self.data.sum())
+
+            # broadcast. treat 1d like a row
+            sM, sN = self._shape_as_2d
+            oM, oN = other._shape_as_2d
+            # A row times a column.
+            if sM == 1 and oN == 1:
+                return other._matmul_sparse(self.reshape(sM, sN).tocsc())
+            if sN == 1 and oM == 1:
+                return self._matmul_sparse(other.reshape(oM, oN).tocsc())
+
+            is_array = isinstance(self, sparray)
+            # Other is a row.
+            if oM == 1 and sN == oN:
+                new_other = _make_diagonal_csr(other.toarray().ravel(), is_array)
+                result = self._matmul_sparse(new_other)
+                return result if self.ndim == 2 else result.reshape((1, oN))
+            # self is a row.
+            if sM == 1 and sN == oN:
+                copy = _make_diagonal_csr(self.toarray().ravel(), is_array)
+                return other._matmul_sparse(copy)
+
+            # Other is a column.
+            if oN == 1 and sM == oM:
+                new_other = _make_diagonal_csr(other.toarray().ravel(), is_array)
+                return new_other._matmul_sparse(self)
+            # self is a column.
+            if sN == 1 and sM == oM:
+                new_self = _make_diagonal_csr(self.toarray().ravel(), is_array)
+                return new_self._matmul_sparse(other)
+            raise ValueError("inconsistent shapes")
+
+        # Assume other is a dense matrix/array, which produces a single-item
+        # object array if other isn't convertible to ndarray.
+        other = np.asanyarray(other)
+
+        if other.ndim > 2:
+            return np.multiply(self.toarray(), other)
+        # Single element / wrapped object.
+        if other.size == 1:
+            if other.dtype == np.object_:
+                # 'other' not convertible to ndarray.
+                return NotImplemented
+            bshape = broadcast_shapes(self.shape, other.shape)
+            return self._mul_scalar(other.flat[0]).reshape(bshape)
+        # Fast case for trivial sparse matrix.
+        if self.shape in ((1,), (1, 1)):
+            bshape = broadcast_shapes(self.shape, other.shape)
+            return np.multiply(self.data.sum(), other).reshape(bshape)
+
+        ret = self.tocoo()
+        # Matching shapes.
+        if self.shape == other.shape:
+            data = np.multiply(ret.data, other[ret.coords])
+            ret.data = data.view(np.ndarray).ravel()
+            return ret
+
+        # convert other to 2d
+        other2d = np.atleast_2d(other)
+        # Sparse row vector times...
+        if self.shape[0] == 1 or self.ndim == 1:
+            if other2d.shape[1] == 1:  # Dense column vector.
+                data = np.multiply(ret.data, other2d)
+            elif other2d.shape[1] == self.shape[-1]:  # Dense 2d matrix.
+                data = np.multiply(ret.data, other2d[:, ret.col])
+            else:
+                raise ValueError("inconsistent shapes")
+            idx_dtype = self._get_index_dtype(ret.col,
+                                              maxval=ret.nnz * other2d.shape[0])
+            row = np.repeat(np.arange(other2d.shape[0], dtype=idx_dtype), ret.nnz)
+            col = np.tile(ret.col.astype(idx_dtype, copy=False), other2d.shape[0])
+            return self._coo_container(
+                (data.view(np.ndarray).ravel(), (row, col)),
+                shape=(other2d.shape[0], self.shape[-1]),
+                copy=False
+            )
+        # Sparse column vector times...
+        if self.shape[1] == 1:
+            if other2d.shape[0] == 1:  # Dense row vector.
+                data = np.multiply(ret.data[:, None], other2d)
+            elif other2d.shape[0] == self.shape[0]:  # Dense 2d array.
+                data = np.multiply(ret.data[:, None], other2d[ret.row])
+            else:
+                raise ValueError("inconsistent shapes")
+            idx_dtype = self._get_index_dtype(ret.row,
+                                              maxval=ret.nnz * other2d.shape[1])
+            row = np.repeat(ret.row.astype(idx_dtype, copy=False), other2d.shape[1])
+            col = np.tile(np.arange(other2d.shape[1], dtype=idx_dtype), ret.nnz)
+            return self._coo_container(
+                (data.view(np.ndarray).ravel(), (row, col)),
+                shape=(self.shape[0], other2d.shape[1]),
+                copy=False
+            )
+        # Sparse matrix times dense row vector.
+        if other2d.shape[0] == 1 and self.shape[1] == other2d.shape[1]:
+            data = np.multiply(ret.data, other2d[:, ret.col].ravel())
+        # Sparse matrix times dense column vector.
+        elif other2d.shape[1] == 1 and self.shape[0] == other2d.shape[0]:
+            data = np.multiply(ret.data, other2d[ret.row].ravel())
+        else:
+            raise ValueError("inconsistent shapes")
+        ret.data = data.view(np.ndarray).ravel()
+        return ret
+
+    ###########################
+    # Multiplication handlers #
+    ###########################
+
+    def _matmul_vector(self, other):
+        M, N = self._shape_as_2d
+
+        # output array
+        result = np.zeros(M, dtype=upcast_char(self.dtype.char, other.dtype.char))
+
+        # csr_matvec or csc_matvec
+        fn = getattr(_sparsetools, self.format + '_matvec')
+        fn(M, N, self.indptr, self.indices, self.data, other, result)
+
+        return result[0] if self.ndim == 1 else result
+
+    def _matmul_multivector(self, other):
+        M, N = self._shape_as_2d
+        n_vecs = other.shape[-1]  # number of column vectors
+
+        result = np.zeros((M, n_vecs),
+                          dtype=upcast_char(self.dtype.char, other.dtype.char))
+
+        # csr_matvecs or csc_matvecs
+        fn = getattr(_sparsetools, self.format + '_matvecs')
+        fn(M, N, n_vecs, self.indptr, self.indices, self.data,
+           other.ravel(), result.ravel())
+
+        if self.ndim == 1:
+            return result.reshape((n_vecs,))
+        return result
+
+    def _matmul_sparse(self, other):
+        M, K1 = self._shape_as_2d
+        # if other is 1d, treat as a **column**
+        o_ndim = other.ndim
+        if o_ndim == 1:
+            # convert 1d array to a 2d column when on the right of @
+            other = other.reshape((1, other.shape[0])).T  # Note: converts to CSC
+        K2, N = other._shape if other.ndim == 2 else (other.shape[0], 1)
+
+        # find new_shape: (M, N), (M,), (N,) or ()
+        new_shape = ()
+        if self.ndim == 2:
+            new_shape += (M,)
+        if o_ndim == 2:
+            new_shape += (N,)
+        faux_shape = (M if self.ndim == 2 else 1, N if o_ndim == 2 else 1)
+
+        major_dim = self._swap((M, N))[0]
+        other = self.__class__(other)  # convert to this format
+
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                     other.indptr, other.indices))
+
+        fn = getattr(_sparsetools, self.format + '_matmat_maxnnz')
+        nnz = fn(M, N,
+                 np.asarray(self.indptr, dtype=idx_dtype),
+                 np.asarray(self.indices, dtype=idx_dtype),
+                 np.asarray(other.indptr, dtype=idx_dtype),
+                 np.asarray(other.indices, dtype=idx_dtype))
+        if nnz == 0:
+            if new_shape == ():
+                return np.array(0, dtype=upcast(self.dtype, other.dtype))
+            return self.__class__(new_shape, dtype=upcast(self.dtype, other.dtype))
+
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                     other.indptr, other.indices),
+                                    maxval=nnz)
+
+        indptr = np.empty(major_dim + 1, dtype=idx_dtype)
+        indices = np.empty(nnz, dtype=idx_dtype)
+        data = np.empty(nnz, dtype=upcast(self.dtype, other.dtype))
+
+        fn = getattr(_sparsetools, self.format + '_matmat')
+        fn(M, N, np.asarray(self.indptr, dtype=idx_dtype),
+           np.asarray(self.indices, dtype=idx_dtype),
+           self.data,
+           np.asarray(other.indptr, dtype=idx_dtype),
+           np.asarray(other.indices, dtype=idx_dtype),
+           other.data,
+           indptr, indices, data)
+
+        if new_shape == ():
+            return np.array(data[0])
+        res = self.__class__((data, indices, indptr), shape=faux_shape)
+        if faux_shape != new_shape:
+            if res.format != 'csr':
+                res = res.tocsr()
+            res = res.reshape(new_shape)
+        return res
+
+    def diagonal(self, k=0):
+        rows, cols = self.shape
+        if k <= -rows or k >= cols:
+            return np.empty(0, dtype=self.data.dtype)
+        fn = getattr(_sparsetools, self.format + "_diagonal")
+        y = np.empty(min(rows + min(k, 0), cols - max(k, 0)),
+                     dtype=upcast(self.dtype))
+        fn(k, self.shape[0], self.shape[1], self.indptr, self.indices,
+           self.data, y)
+        return y
+
+    diagonal.__doc__ = _spbase.diagonal.__doc__
+
+    #####################
+    # Other binary ops  #
+    #####################
+
+    def _maximum_minimum(self, other, npop, op_name, dense_check):
+        if isscalarlike(other):
+            if dense_check(other):
+                warn("Taking maximum (minimum) with > 0 (< 0) number results"
+                     " to a dense matrix.", SparseEfficiencyWarning,
+                     stacklevel=3)
+                other_arr = np.empty(self.shape, dtype=np.asarray(other).dtype)
+                other_arr.fill(other)
+                other_arr = self.__class__(other_arr)
+                return self._binopt(other_arr, op_name)
+            else:
+                self.sum_duplicates()
+                new_data = npop(self.data, np.asarray(other))
+                mat = self.__class__((new_data, self.indices, self.indptr),
+                                     dtype=new_data.dtype, shape=self.shape)
+                return mat
+        elif isdense(other):
+            return npop(self.todense(), other)
+        elif issparse(other):
+            return self._binopt(other, op_name)
+        else:
+            raise ValueError("Operands not compatible.")
+
+    def maximum(self, other):
+        return self._maximum_minimum(other, np.maximum,
+                                     '_maximum_', lambda x: np.asarray(x) > 0)
+
+    maximum.__doc__ = _spbase.maximum.__doc__
+
+    def minimum(self, other):
+        return self._maximum_minimum(other, np.minimum,
+                                     '_minimum_', lambda x: np.asarray(x) < 0)
+
+    minimum.__doc__ = _spbase.minimum.__doc__
+
+    #####################
+    # Reduce operations #
+    #####################
+
+    def sum(self, axis=None, dtype=None, out=None):
+        """Sum the array/matrix over the given axis.  If the axis is None, sum
+        over both rows and columns, returning a scalar.
+        """
+        # The _spbase base class already does axis=0 and axis=1 efficiently
+        # so we only do the case axis=None here
+        if (self.ndim == 2 and not hasattr(self, 'blocksize') and
+                axis in self._swap(((1, -1), (0, -2)))[0]):
+            # faster than multiplication for large minor axis in CSC/CSR
+            res_dtype = get_sum_dtype(self.dtype)
+            ret = np.zeros(len(self.indptr) - 1, dtype=res_dtype)
+
+            major_index, value = self._minor_reduce(np.add)
+            ret[major_index] = value
+            ret = self._ascontainer(ret)
+            if axis % 2 == 1:
+                ret = ret.T
+
+            return ret.sum(axis=(), dtype=dtype, out=out)
+        else:
+            # _spbase handles the situations when axis is in {None, -2, -1, 0, 1}
+            return _spbase.sum(self, axis=axis, dtype=dtype, out=out)
+
+    sum.__doc__ = _spbase.sum.__doc__
+
+    def _minor_reduce(self, ufunc, data=None):
+        """Reduce nonzeros with a ufunc over the minor axis when non-empty
+
+        Can be applied to a function of self.data by supplying data parameter.
+
+        Warning: this does not call sum_duplicates()
+
+        Returns
+        -------
+        major_index : array of ints
+            Major indices where nonzero
+
+        value : array of self.dtype
+            Reduce result for nonzeros in each major_index
+        """
+        if data is None:
+            data = self.data
+        major_index = np.flatnonzero(np.diff(self.indptr))
+        value = ufunc.reduceat(data,
+                               downcast_intp_index(self.indptr[major_index]))
+        return major_index, value
+
+    #######################
+    # Getting and Setting #
+    #######################
+
+    def _get_intXint(self, row, col):
+        M, N = self._swap(self.shape)
+        major, minor = self._swap((row, col))
+        indptr, indices, data = get_csr_submatrix(
+            M, N, self.indptr, self.indices, self.data,
+            major, major + 1, minor, minor + 1)
+        return data.sum(dtype=self.dtype)
+
+    def _get_sliceXslice(self, row, col):
+        major, minor = self._swap((row, col))
+        if major.step in (1, None) and minor.step in (1, None):
+            return self._get_submatrix(major, minor, copy=True)
+        return self._major_slice(major)._minor_slice(minor)
+
+    def _get_arrayXarray(self, row, col):
+        # inner indexing
+        idx_dtype = self.indices.dtype
+        M, N = self._swap(self.shape)
+        major, minor = self._swap((row, col))
+        major = np.asarray(major, dtype=idx_dtype)
+        minor = np.asarray(minor, dtype=idx_dtype)
+
+        val = np.empty(major.size, dtype=self.dtype)
+        csr_sample_values(M, N, self.indptr, self.indices, self.data,
+                          major.size, major.ravel(), minor.ravel(), val)
+        if major.ndim == 1:
+            return self._ascontainer(val)
+        return self.__class__(val.reshape(major.shape))
+
+    def _get_columnXarray(self, row, col):
+        # outer indexing
+        major, minor = self._swap((row, col))
+        return self._major_index_fancy(major)._minor_index_fancy(minor)
+
+    def _major_index_fancy(self, idx):
+        """Index along the major axis where idx is an array of ints.
+        """
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices))
+        indices = np.asarray(idx, dtype=idx_dtype).ravel()
+
+        N = self._swap(self._shape_as_2d)[1]
+        M = len(indices)
+        new_shape = self._swap((M, N)) if self.ndim == 2 else (M,)
+        if M == 0:
+            return self.__class__(new_shape, dtype=self.dtype)
+
+        row_nnz = (self.indptr[indices + 1] - self.indptr[indices]).astype(idx_dtype)
+        res_indptr = np.zeros(M + 1, dtype=idx_dtype)
+        np.cumsum(row_nnz, out=res_indptr[1:])
+
+        nnz = res_indptr[-1]
+        res_indices = np.empty(nnz, dtype=idx_dtype)
+        res_data = np.empty(nnz, dtype=self.dtype)
+        csr_row_index(
+            M,
+            indices,
+            self.indptr.astype(idx_dtype, copy=False),
+            self.indices.astype(idx_dtype, copy=False),
+            self.data,
+            res_indices,
+            res_data
+        )
+
+        return self.__class__((res_data, res_indices, res_indptr),
+                              shape=new_shape, copy=False)
+
+    def _major_slice(self, idx, copy=False):
+        """Index along the major axis where idx is a slice object.
+        """
+        if idx == slice(None):
+            return self.copy() if copy else self
+
+        M, N = self._swap(self._shape_as_2d)
+        start, stop, step = idx.indices(M)
+        M = len(range(start, stop, step))
+        new_shape = self._swap((M, N)) if self.ndim == 2 else (M,)
+        if M == 0:
+            return self.__class__(new_shape, dtype=self.dtype)
+
+        # Work out what slices are needed for `row_nnz`
+        # start,stop can be -1, only if step is negative
+        start0, stop0 = start, stop
+        if stop == -1 and start >= 0:
+            stop0 = None
+        start1, stop1 = start + 1, stop + 1
+
+        row_nnz = self.indptr[start1:stop1:step] - \
+            self.indptr[start0:stop0:step]
+        idx_dtype = self.indices.dtype
+        res_indptr = np.zeros(M+1, dtype=idx_dtype)
+        np.cumsum(row_nnz, out=res_indptr[1:])
+
+        if step == 1:
+            all_idx = slice(self.indptr[start], self.indptr[stop])
+            res_indices = np.array(self.indices[all_idx], copy=copy)
+            res_data = np.array(self.data[all_idx], copy=copy)
+        else:
+            nnz = res_indptr[-1]
+            res_indices = np.empty(nnz, dtype=idx_dtype)
+            res_data = np.empty(nnz, dtype=self.dtype)
+            csr_row_slice(start, stop, step, self.indptr, self.indices,
+                          self.data, res_indices, res_data)
+
+        return self.__class__((res_data, res_indices, res_indptr),
+                              shape=new_shape, copy=False)
+
+    def _minor_index_fancy(self, idx):
+        """Index along the minor axis where idx is an array of ints.
+        """
+        idx_dtype = self._get_index_dtype((self.indices, self.indptr))
+        indices = self.indices.astype(idx_dtype, copy=False)
+        indptr = self.indptr.astype(idx_dtype, copy=False)
+
+        idx = np.asarray(idx, dtype=idx_dtype).ravel()
+
+        M, N = self._swap(self._shape_as_2d)
+        k = len(idx)
+        new_shape = self._swap((M, k)) if self.ndim == 2 else (k,)
+        if k == 0:
+            return self.__class__(new_shape, dtype=self.dtype)
+
+        # pass 1: count idx entries and compute new indptr
+        col_offsets = np.zeros(N, dtype=idx_dtype)
+        res_indptr = np.empty_like(self.indptr, dtype=idx_dtype)
+        csr_column_index1(
+            k,
+            idx,
+            M,
+            N,
+            indptr,
+            indices,
+            col_offsets,
+            res_indptr,
+        )
+
+        # pass 2: copy indices/data for selected idxs
+        col_order = np.argsort(idx).astype(idx_dtype, copy=False)
+        nnz = res_indptr[-1]
+        res_indices = np.empty(nnz, dtype=idx_dtype)
+        res_data = np.empty(nnz, dtype=self.dtype)
+        csr_column_index2(col_order, col_offsets, len(self.indices),
+                          indices, self.data, res_indices, res_data)
+        return self.__class__((res_data, res_indices, res_indptr),
+                              shape=new_shape, copy=False)
+
+    def _minor_slice(self, idx, copy=False):
+        """Index along the minor axis where idx is a slice object.
+        """
+        if idx == slice(None):
+            return self.copy() if copy else self
+
+        M, N = self._swap(self._shape_as_2d)
+        start, stop, step = idx.indices(N)
+        N = len(range(start, stop, step))
+        if N == 0:
+            return self.__class__(self._swap((M, N)), dtype=self.dtype)
+        if step == 1:
+            return self._get_submatrix(minor=idx, copy=copy)
+        # TODO: don't fall back to fancy indexing here
+        return self._minor_index_fancy(np.arange(start, stop, step))
+
+    def _get_submatrix(self, major=None, minor=None, copy=False):
+        """Return a submatrix of this matrix.
+
+        major, minor: None, int, or slice with step 1
+        """
+        M, N = self._swap(self._shape_as_2d)
+        i0, i1 = _process_slice(major, M)
+        j0, j1 = _process_slice(minor, N)
+
+        if i0 == 0 and j0 == 0 and i1 == M and j1 == N:
+            return self.copy() if copy else self
+
+        indptr, indices, data = get_csr_submatrix(
+            M, N, self.indptr, self.indices, self.data, i0, i1, j0, j1)
+
+        shape = self._swap((i1 - i0, j1 - j0))
+        if self.ndim == 1:
+            shape = (shape[1],)
+        return self.__class__((data, indices, indptr), shape=shape,
+                              dtype=self.dtype, copy=False)
+
+    def _set_intXint(self, row, col, x):
+        i, j = self._swap((row, col))
+        self._set_many(i, j, x)
+
+    def _set_arrayXarray(self, row, col, x):
+        i, j = self._swap((row, col))
+        self._set_many(i, j, x)
+
+    def _set_arrayXarray_sparse(self, row, col, x):
+        # clear entries that will be overwritten
+        self._zero_many(*self._swap((row, col)))
+
+        M, N = row.shape  # matches col.shape
+        broadcast_row = M != 1 and x.shape[0] == 1
+        broadcast_col = N != 1 and x.shape[1] == 1
+        r, c = x.row, x.col
+
+        x = np.asarray(x.data, dtype=self.dtype)
+        if x.size == 0:
+            return
+
+        if broadcast_row:
+            r = np.repeat(np.arange(M), len(r))
+            c = np.tile(c, M)
+            x = np.tile(x, M)
+        if broadcast_col:
+            r = np.repeat(r, N)
+            c = np.tile(np.arange(N), len(c))
+            x = np.repeat(x, N)
+        # only assign entries in the new sparsity structure
+        i, j = self._swap((row[r, c], col[r, c]))
+        self._set_many(i, j, x)
+
+    def _setdiag(self, values, k):
+        if 0 in self.shape:
+            return
+        if self.ndim == 1:
+            raise NotImplementedError('diagonals cant be set in 1d arrays')
+
+        M, N = self.shape
+        broadcast = (values.ndim == 0)
+
+        if k < 0:
+            if broadcast:
+                max_index = min(M + k, N)
+            else:
+                max_index = min(M + k, N, len(values))
+            i = np.arange(-k, max_index - k, dtype=self.indices.dtype)
+            j = np.arange(max_index, dtype=self.indices.dtype)
+
+        else:
+            if broadcast:
+                max_index = min(M, N - k)
+            else:
+                max_index = min(M, N - k, len(values))
+            i = np.arange(max_index, dtype=self.indices.dtype)
+            j = np.arange(k, k + max_index, dtype=self.indices.dtype)
+
+        if not broadcast:
+            values = values[:len(i)]
+
+        x = np.atleast_1d(np.asarray(values, dtype=self.dtype)).ravel()
+        if x.squeeze().shape != i.squeeze().shape:
+            x = np.broadcast_to(x, i.shape)
+        if x.size == 0:
+            return
+
+        M, N = self._swap((M, N))
+        i, j = self._swap((i, j))
+        n_samples = x.size
+        offsets = np.empty(n_samples, dtype=self.indices.dtype)
+        ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                                 i, j, offsets)
+        if ret == 1:
+            # rinse and repeat
+            self.sum_duplicates()
+            csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                               i, j, offsets)
+        if -1 not in offsets:
+            # only affects existing non-zero cells
+            self.data[offsets] = x
+            return
+
+        mask = (offsets >= 0)
+        # Boundary between csc and convert to coo
+        # The value 0.001 is justified in gh-19962#issuecomment-1920499678
+        if self.nnz - mask.sum() < self.nnz * 0.001:
+            # replace existing entries
+            self.data[offsets[mask]] = x[mask]
+            # create new entries
+            mask = ~mask
+            i = i[mask]
+            j = j[mask]
+            self._insert_many(i, j, x[mask])
+        else:
+            # convert to coo for _set_diag
+            coo = self.tocoo()
+            coo._setdiag(values, k)
+            arrays = coo._coo_to_compressed(self._swap)
+            self.indptr, self.indices, self.data, _ = arrays
+
+    def _prepare_indices(self, i, j):
+        M, N = self._swap(self._shape_as_2d)
+
+        def check_bounds(indices, bound):
+            idx = indices.max()
+            if idx >= bound:
+                raise IndexError(f'index ({idx}) out of range (>= {bound})')
+            idx = indices.min()
+            if idx < -bound:
+                raise IndexError(f'index ({idx}) out of range (< -{bound})')
+
+        i = np.atleast_1d(np.asarray(i, dtype=self.indices.dtype)).ravel()
+        j = np.atleast_1d(np.asarray(j, dtype=self.indices.dtype)).ravel()
+        check_bounds(i, M)
+        check_bounds(j, N)
+        return i, j, M, N
+
+    def _set_many(self, i, j, x):
+        """Sets value at each (i, j) to x
+
+        Here (i,j) index major and minor respectively, and must not contain
+        duplicate entries.
+        """
+        i, j, M, N = self._prepare_indices(i, j)
+        x = np.atleast_1d(np.asarray(x, dtype=self.dtype)).ravel()
+
+        n_samples = x.size
+        offsets = np.empty(n_samples, dtype=self.indices.dtype)
+        ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                                 i, j, offsets)
+        if ret == 1:
+            # rinse and repeat
+            self.sum_duplicates()
+            csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                               i, j, offsets)
+
+        if -1 not in offsets:
+            # only affects existing non-zero cells
+            self.data[offsets] = x
+            return
+
+        else:
+            warn(f"Changing the sparsity structure of a {self.__class__.__name__} is"
+                 " expensive. lil and dok are more efficient.",
+                 SparseEfficiencyWarning, stacklevel=3)
+            # replace where possible
+            mask = offsets > -1
+            self.data[offsets[mask]] = x[mask]
+            # only insertions remain
+            mask = ~mask
+            i = i[mask]
+            i[i < 0] += M
+            j = j[mask]
+            j[j < 0] += N
+            self._insert_many(i, j, x[mask])
+
+    def _zero_many(self, i, j):
+        """Sets value at each (i, j) to zero, preserving sparsity structure.
+
+        Here (i,j) index major and minor respectively.
+        """
+        i, j, M, N = self._prepare_indices(i, j)
+
+        n_samples = len(i)
+        offsets = np.empty(n_samples, dtype=self.indices.dtype)
+        ret = csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                                 i, j, offsets)
+        if ret == 1:
+            # rinse and repeat
+            self.sum_duplicates()
+            csr_sample_offsets(M, N, self.indptr, self.indices, n_samples,
+                               i, j, offsets)
+
+        # only assign zeros to the existing sparsity structure
+        self.data[offsets[offsets > -1]] = 0
+
+    def _insert_many(self, i, j, x):
+        """Inserts new nonzero at each (i, j) with value x
+
+        Here (i,j) index major and minor respectively.
+        i, j and x must be non-empty, 1d arrays.
+        Inserts each major group (e.g. all entries per row) at a time.
+        Maintains has_sorted_indices property.
+        Modifies i, j, x in place.
+        """
+        order = np.argsort(i, kind='mergesort')  # stable for duplicates
+        i = i.take(order, mode='clip')
+        j = j.take(order, mode='clip')
+        x = x.take(order, mode='clip')
+
+        do_sort = self.has_sorted_indices
+
+        # Update index data type
+        idx_dtype = self._get_index_dtype((self.indices, self.indptr),
+                                    maxval=(self.indptr[-1] + x.size))
+        self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
+        self.indices = np.asarray(self.indices, dtype=idx_dtype)
+        i = np.asarray(i, dtype=idx_dtype)
+        j = np.asarray(j, dtype=idx_dtype)
+
+        # Collate old and new in chunks by major index
+        indices_parts = []
+        data_parts = []
+        ui, ui_indptr = np.unique(i, return_index=True)
+        ui_indptr = np.append(ui_indptr, len(j))
+        new_nnzs = np.diff(ui_indptr)
+        prev = 0
+        for c, (ii, js, je) in enumerate(zip(ui, ui_indptr, ui_indptr[1:])):
+            # old entries
+            start = self.indptr[prev]
+            stop = self.indptr[ii]
+            indices_parts.append(self.indices[start:stop])
+            data_parts.append(self.data[start:stop])
+
+            # handle duplicate j: keep last setting
+            uj, uj_indptr = np.unique(j[js:je][::-1], return_index=True)
+            if len(uj) == je - js:
+                indices_parts.append(j[js:je])
+                data_parts.append(x[js:je])
+            else:
+                indices_parts.append(j[js:je][::-1][uj_indptr])
+                data_parts.append(x[js:je][::-1][uj_indptr])
+                new_nnzs[c] = len(uj)
+
+            prev = ii
+
+        # remaining old entries
+        start = self.indptr[ii]
+        indices_parts.append(self.indices[start:])
+        data_parts.append(self.data[start:])
+
+        # update attributes
+        self.indices = np.concatenate(indices_parts)
+        self.data = np.concatenate(data_parts)
+        nnzs = np.empty(self.indptr.shape, dtype=idx_dtype)
+        nnzs[0] = idx_dtype(0)
+        indptr_diff = np.diff(self.indptr)
+        indptr_diff[ui] += new_nnzs
+        nnzs[1:] = indptr_diff
+        self.indptr = np.cumsum(nnzs, out=nnzs)
+
+        if do_sort:
+            # TODO: only sort where necessary
+            self.has_sorted_indices = False
+            self.sort_indices()
+
+        self.check_format(full_check=False)
+
+    ######################
+    # Conversion methods #
+    ######################
+
+    def tocoo(self, copy=True):
+        if self.ndim == 1:
+            csr = self.tocsr()
+            return self._coo_container((csr.data, (csr.indices,)), csr.shape, copy=copy)
+        major_dim, minor_dim = self._swap(self.shape)
+        minor_indices = self.indices
+        major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype)
+        _sparsetools.expandptr(major_dim, self.indptr, major_indices)
+        coords = self._swap((major_indices, minor_indices))
+
+        return self._coo_container(
+            (self.data, coords), self.shape, copy=copy, dtype=self.dtype
+        )
+
+    tocoo.__doc__ = _spbase.tocoo.__doc__
+
+    def toarray(self, order=None, out=None):
+        if out is None and order is None:
+            order = self._swap('cf')[0]
+        out = self._process_toarray_args(order, out)
+        if not (out.flags.c_contiguous or out.flags.f_contiguous):
+            raise ValueError('Output array must be C or F contiguous')
+        # align ideal order with output array order
+        if out.flags.c_contiguous:
+            x = self.tocsr()
+            y = out
+        else:
+            x = self.tocsc()
+            y = out.T
+        M, N = x._swap(x._shape_as_2d)
+        csr_todense(M, N, x.indptr, x.indices, x.data, y)
+        return out
+
+    toarray.__doc__ = _spbase.toarray.__doc__
+
+    ##############################################################
+    # methods that examine or modify the internal data structure #
+    ##############################################################
+
+    def eliminate_zeros(self):
+        """Remove zero entries from the array/matrix
+
+        This is an *in place* operation.
+        """
+        M, N = self._swap(self._shape_as_2d)
+        _sparsetools.csr_eliminate_zeros(M, N, self.indptr, self.indices, self.data)
+        self.prune()  # nnz may have changed
+
+    @property
+    def has_canonical_format(self) -> bool:
+        """Whether the array/matrix has sorted indices and no duplicates
+
+        Returns
+            - True: if the above applies
+            - False: otherwise
+
+        has_canonical_format implies has_sorted_indices, so if the latter flag
+        is False, so will the former be; if the former is found True, the
+        latter flag is also set.
+        """
+        # first check to see if result was cached
+        if not getattr(self, '_has_sorted_indices', True):
+            # not sorted => not canonical
+            self._has_canonical_format = False
+        elif not hasattr(self, '_has_canonical_format'):
+            self.has_canonical_format = bool(
+                _sparsetools.csr_has_canonical_format(
+                    len(self.indptr) - 1, self.indptr, self.indices)
+                )
+        return self._has_canonical_format
+
+    @has_canonical_format.setter
+    def has_canonical_format(self, val: bool):
+        self._has_canonical_format = bool(val)
+        if val:
+            self.has_sorted_indices = True
+
+    def sum_duplicates(self):
+        """Eliminate duplicate entries by adding them together
+
+        This is an *in place* operation.
+        """
+        if self.has_canonical_format:
+            return
+        self.sort_indices()
+
+        M, N = self._swap(self._shape_as_2d)
+        _sparsetools.csr_sum_duplicates(M, N, self.indptr, self.indices, self.data)
+
+        self.prune()  # nnz may have changed
+        self.has_canonical_format = True
+
+    @property
+    def has_sorted_indices(self) -> bool:
+        """Whether the indices are sorted
+
+        Returns
+            - True: if the indices of the array/matrix are in sorted order
+            - False: otherwise
+        """
+        # first check to see if result was cached
+        if not hasattr(self, '_has_sorted_indices'):
+            self._has_sorted_indices = bool(
+                _sparsetools.csr_has_sorted_indices(
+                    len(self.indptr) - 1, self.indptr, self.indices)
+                )
+        return self._has_sorted_indices
+
+    @has_sorted_indices.setter
+    def has_sorted_indices(self, val: bool):
+        self._has_sorted_indices = bool(val)
+
+
+    def sorted_indices(self):
+        """Return a copy of this array/matrix with sorted indices
+        """
+        A = self.copy()
+        A.sort_indices()
+        return A
+
+        # an alternative that has linear complexity is the following
+        # although the previous option is typically faster
+        # return self.toother().toother()
+
+    def sort_indices(self):
+        """Sort the indices of this array/matrix *in place*
+        """
+
+        if not self.has_sorted_indices:
+            _sparsetools.csr_sort_indices(len(self.indptr) - 1, self.indptr,
+                                          self.indices, self.data)
+            self.has_sorted_indices = True
+
+    def prune(self):
+        """Remove empty space after all non-zero elements.
+        """
+        major_dim = self._swap(self._shape_as_2d)[0]
+
+        if len(self.indptr) != major_dim + 1:
+            raise ValueError('index pointer has invalid length')
+        if len(self.indices) < self.nnz:
+            raise ValueError('indices array has fewer than nnz elements')
+        if len(self.data) < self.nnz:
+            raise ValueError('data array has fewer than nnz elements')
+
+        self.indices = _prune_array(self.indices[:self.nnz])
+        self.data = _prune_array(self.data[:self.nnz])
+
+    def resize(self, *shape):
+        shape = check_shape(shape, allow_nd=self._allow_nd)
+
+        if hasattr(self, 'blocksize'):
+            bm, bn = self.blocksize
+            new_M, rm = divmod(shape[0], bm)
+            new_N, rn = divmod(shape[1], bn)
+            if rm or rn:
+                raise ValueError(f"shape must be divisible into {self.blocksize}"
+                                 f" blocks. Got {shape}")
+            M, N = self.shape[0] // bm, self.shape[1] // bn
+        else:
+            new_M, new_N = self._swap(shape if len(shape)>1 else (1, shape[0]))
+            M, N = self._swap(self._shape_as_2d)
+
+        if new_M < M:
+            self.indices = self.indices[:self.indptr[new_M]]
+            self.data = self.data[:self.indptr[new_M]]
+            self.indptr = self.indptr[:new_M + 1]
+        elif new_M > M:
+            self.indptr = np.resize(self.indptr, new_M + 1)
+            self.indptr[M + 1:].fill(self.indptr[M])
+
+        if new_N < N:
+            mask = self.indices < new_N
+            if not np.all(mask):
+                self.indices = self.indices[mask]
+                self.data = self.data[mask]
+                major_index, val = self._minor_reduce(np.add, mask)
+                self.indptr.fill(0)
+                self.indptr[1:][major_index] = val
+                np.cumsum(self.indptr, out=self.indptr)
+
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+    ###################
+    # utility methods #
+    ###################
+
+    # needed by _data_matrix
+    def _with_data(self, data, copy=True):
+        """Returns a matrix with the same sparsity structure as self,
+        but with different data.  By default the structure arrays
+        (i.e. .indptr and .indices) are copied.
+        """
+        if copy:
+            return self.__class__((data, self.indices.copy(),
+                                   self.indptr.copy()),
+                                  shape=self.shape,
+                                  dtype=data.dtype)
+        else:
+            return self.__class__((data, self.indices, self.indptr),
+                                  shape=self.shape, dtype=data.dtype)
+
+    def _binopt(self, other, op):
+        """apply the binary operation fn to two sparse matrices."""
+        other = self.__class__(other)
+
+        # e.g. csr_plus_csr, csr_minus_csr, etc.
+        fn = getattr(_sparsetools, self.format + op + self.format)
+
+        maxnnz = self.nnz + other.nnz
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+                                     other.indptr, other.indices),
+                                    maxval=maxnnz)
+        indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
+        indices = np.empty(maxnnz, dtype=idx_dtype)
+
+        bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_']
+        if op in bool_ops:
+            data = np.empty(maxnnz, dtype=np.bool_)
+        else:
+            data = np.empty(maxnnz, dtype=upcast(self.dtype, other.dtype))
+
+        M, N = self._shape_as_2d
+        fn(M, N,
+           np.asarray(self.indptr, dtype=idx_dtype),
+           np.asarray(self.indices, dtype=idx_dtype),
+           self.data,
+           np.asarray(other.indptr, dtype=idx_dtype),
+           np.asarray(other.indices, dtype=idx_dtype),
+           other.data,
+           indptr, indices, data)
+
+        A = self.__class__((data, indices, indptr), shape=self.shape)
+        A.prune()
+
+        return A
+
+    def _divide_sparse(self, other):
+        """
+        Divide this matrix by a second sparse matrix.
+        """
+        if other.shape != self.shape:
+            raise ValueError('inconsistent shapes')
+
+        r = self._binopt(other, '_eldiv_')
+
+        if np.issubdtype(r.dtype, np.inexact):
+            # Eldiv leaves entries outside the combined sparsity
+            # pattern empty, so they must be filled manually.
+            # Everything outside of other's sparsity is NaN, and everything
+            # inside it is either zero or defined by eldiv.
+            out = np.empty(self.shape, dtype=self.dtype)
+            out.fill(np.nan)
+            coords = other.nonzero()
+            if self.ndim == 1:
+                coords = (coords[-1],)
+            out[coords] = 0
+            r = r.tocoo()
+            out[r.coords] = r.data
+            return self._container(out)
+        else:
+            # integers types go with nan <-> 0
+            out = r
+            return out
+
+    def _broadcast_to(self, shape, copy=False):
+        if self.shape == shape:
+            return self.copy() if copy else self
+
+        shape = check_shape(shape, allow_nd=(self._allow_nd))
+
+        if broadcast_shapes(self.shape, shape) != shape:
+            raise ValueError("cannot be broadcast")
+
+        if len(self.shape) == 1 and len(shape) == 1:
+            self.sum_duplicates()
+            if self.nnz == 0: # array has no non zero elements
+                return self.__class__(shape, dtype=self.dtype, copy=False)
+
+            N = shape[0]
+            data = np.full(N, self.data[0])
+            indices = np.arange(0,N)
+            indptr = np.array([0, N])
+            return self._csr_container((data, indices, indptr), shape=shape, copy=False)
+
+        # treat 1D as a 2D row
+        old_shape = self._shape_as_2d
+
+        if len(shape) != 2:
+            ndim = len(shape)
+            raise ValueError(f'CSR/CSC broadcast_to cannot have shape >2D. Got {ndim}D')
+
+        if self.nnz == 0: # array has no non zero elements
+            return self.__class__(shape, dtype=self.dtype, copy=False)
+
+        self.sum_duplicates()
+        M, N = self._swap(shape)
+        oM, oN = self._swap(old_shape)
+        if all(s == 1 for s in old_shape):
+            # Broadcast a single element to the entire shape
+            data = np.full(M * N, self.data[0])
+            indices = np.tile(np.arange(N), M)
+            indptr = np.arange(0, len(data) + 1, N)
+        elif oM == 1 and oN == N:
+            # Broadcast row-wise (columns for CSC)
+            data = np.tile(self.data, M)
+            indices = np.tile(self.indices, M)
+            indptr = np.arange(0, len(data) + 1, len(self.data))
+        elif oN == 1 and oM == M:
+            # Broadcast column-wise (rows for CSC)
+            data = np.repeat(self.data, N)
+            indices = np.tile(np.arange(N), len(self.data))
+            indptr = self.indptr * N
+        return self.__class__((data, indices, indptr), shape=shape, copy=False)
+
+
+def _make_diagonal_csr(data, is_array=False):
+    """build diagonal csc_array/csr_array => self._csr_container
+
+    Parameter `data` should be a raveled numpy array holding the
+    values on the diagonal of the resulting sparse matrix.
+    """
+    from ._csr import csr_array, csr_matrix
+    csr_array = csr_array if is_array else csr_matrix
+
+    N = len(data)
+    idx_dtype = get_index_dtype(maxval=N)
+    indptr = np.arange(N + 1, dtype=idx_dtype)
+    indices = indptr[:-1]
+
+    return csr_array((data, indices, indptr), shape=(N, N))
+
+
+def _process_slice(sl, num):
+    if sl is None:
+        i0, i1 = 0, num
+    elif isinstance(sl, slice):
+        i0, i1, stride = sl.indices(num)
+        if stride != 1:
+            raise ValueError('slicing with step != 1 not supported')
+        i0 = min(i0, i1)  # give an empty slice when i0 > i1
+    elif isintlike(sl):
+        if sl < 0:
+            sl += num
+        i0, i1 = sl, sl + 1
+        if i0 < 0 or i1 > num:
+            raise IndexError(f'index out of bounds: 0 <= {i0} < {i1} <= {num}')
+    else:
+        raise TypeError('expected slice or scalar')
+
+    return i0, i1
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_construct.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..f483976badb771d777c9dba0eecfbeb94d2e76fd
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_construct.py
@@ -0,0 +1,1402 @@
+"""Functions to construct sparse matrices and arrays
+"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['spdiags', 'eye', 'identity', 'kron', 'kronsum',
+           'hstack', 'vstack', 'bmat', 'rand', 'random', 'diags', 'block_diag',
+           'diags_array', 'block_array', 'eye_array', 'random_array']
+
+import numbers
+import math
+import numpy as np
+
+from scipy._lib._util import check_random_state, rng_integers, _transition_to_rng
+from ._sputils import upcast, get_index_dtype, isscalarlike
+
+from ._sparsetools import csr_hstack
+from ._bsr import bsr_matrix, bsr_array
+from ._coo import coo_matrix, coo_array
+from ._csc import csc_matrix, csc_array
+from ._csr import csr_matrix, csr_array
+from ._dia import dia_matrix, dia_array
+
+from ._base import issparse, sparray
+
+
+def spdiags(data, diags, m=None, n=None, format=None):
+    """
+    Return a sparse matrix from diagonals.
+
+    Parameters
+    ----------
+    data : array_like
+        Matrix diagonals stored row-wise
+    diags : sequence of int or an int
+        Diagonals to set:
+
+        * k = 0  the main diagonal
+        * k > 0  the kth upper diagonal
+        * k < 0  the kth lower diagonal
+    m, n : int, tuple, optional
+        Shape of the result. If `n` is None and `m` is a given tuple,
+        the shape is this tuple. If omitted, the matrix is square and
+        its shape is len(data[0]).
+    format : str, optional
+        Format of the result. By default (format=None) an appropriate sparse
+        matrix format is returned. This choice is subject to change.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``dia_array`` to take advantage
+        of the sparse array functionality.
+
+    Notes
+    -----
+    This function can be replaced by an equivalent call to ``dia_matrix``
+    as::
+
+        dia_matrix((data, diags), shape=(m, n)).asformat(format)
+
+    See Also
+    --------
+    diags_array : more convenient form of this function
+    diags : matrix version of diags_array
+    dia_matrix : the sparse DIAgonal format.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import spdiags
+    >>> data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
+    >>> diags = np.array([0, -1, 2])
+    >>> spdiags(data, diags, 4, 4).toarray()
+    array([[1, 0, 3, 0],
+           [1, 2, 0, 4],
+           [0, 2, 3, 0],
+           [0, 0, 3, 4]])
+
+    """
+    if m is None and n is None:
+        m = n = len(data[0])
+    elif n is None:
+        m, n = m
+    return dia_matrix((data, diags), shape=(m, n)).asformat(format)
+
+
+def diags_array(diagonals, /, *, offsets=0, shape=None, format=None, dtype=None):
+    """
+    Construct a sparse array from diagonals.
+
+    Parameters
+    ----------
+    diagonals : sequence of array_like
+        Sequence of arrays containing the array diagonals,
+        corresponding to `offsets`.
+    offsets : sequence of int or an int, optional
+        Diagonals to set (repeated offsets are not allowed):
+          - k = 0  the main diagonal (default)
+          - k > 0  the kth upper diagonal
+          - k < 0  the kth lower diagonal
+    shape : tuple of int, optional
+        Shape of the result. If omitted, a square array large enough
+        to contain the diagonals is returned.
+    format : {"dia", "csr", "csc", "lil", ...}, optional
+        Matrix format of the result. By default (format=None) an
+        appropriate sparse array format is returned. This choice is
+        subject to change.
+    dtype : dtype, optional
+        Data type of the array.
+
+    Notes
+    -----
+    Repeated diagonal offsets are disallowed.
+
+    The result from `diags_array` is the sparse equivalent of::
+
+        np.diag(diagonals[0], offsets[0])
+        + ...
+        + np.diag(diagonals[k], offsets[k])
+
+    ``diags_array`` differs from `dia_array` in the way it handles off-diagonals.
+    Specifically, `dia_array` assumes the data input includes padding
+    (ignored values) at the start/end of the rows for positive/negative
+    offset, while ``diags_array` assumes the input data has no padding.
+    Each value in the input ``diagonals`` is used.
+
+    .. versionadded:: 1.11
+
+    Examples
+    --------
+    >>> from scipy.sparse import diags_array
+    >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]
+    >>> diags_array(diagonals, offsets=[0, -1, 2]).toarray()
+    array([[1., 0., 1., 0.],
+           [1., 2., 0., 2.],
+           [0., 2., 3., 0.],
+           [0., 0., 3., 4.]])
+
+    Broadcasting of scalars is supported (but shape needs to be
+    specified):
+
+    >>> diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4)).toarray()
+    array([[-2.,  1.,  0.,  0.],
+           [ 1., -2.,  1.,  0.],
+           [ 0.,  1., -2.,  1.],
+           [ 0.,  0.,  1., -2.]])
+
+
+    If only one diagonal is wanted (as in `numpy.diag`), the following
+    works as well:
+
+    >>> diags_array([1, 2, 3], offsets=1).toarray()
+    array([[ 0.,  1.,  0.,  0.],
+           [ 0.,  0.,  2.,  0.],
+           [ 0.,  0.,  0.,  3.],
+           [ 0.,  0.,  0.,  0.]])
+
+    """
+    # if offsets is not a sequence, assume that there's only one diagonal
+    if isscalarlike(offsets):
+        # now check that there's actually only one diagonal
+        if len(diagonals) == 0 or isscalarlike(diagonals[0]):
+            diagonals = [np.atleast_1d(diagonals)]
+        else:
+            raise ValueError("Different number of diagonals and offsets.")
+    else:
+        diagonals = list(map(np.atleast_1d, diagonals))
+
+    offsets = np.atleast_1d(offsets)
+
+    # Basic check
+    if len(diagonals) != len(offsets):
+        raise ValueError("Different number of diagonals and offsets.")
+
+    # Determine shape, if omitted
+    if shape is None:
+        m = len(diagonals[0]) + abs(int(offsets[0]))
+        shape = (m, m)
+
+    # Determine data type, if omitted
+    if dtype is None:
+        dtype = np.common_type(*diagonals)
+
+    # Construct data array
+    m, n = shape
+
+    M = max([min(m + offset, n - offset) + max(0, offset)
+             for offset in offsets])
+    M = max(0, M)
+    data_arr = np.zeros((len(offsets), M), dtype=dtype)
+
+    K = min(m, n)
+
+    for j, diagonal in enumerate(diagonals):
+        offset = offsets[j]
+        k = max(0, offset)
+        length = min(m + offset, n - offset, K)
+        if length < 0:
+            raise ValueError(f"Offset {offset} (index {j}) out of bounds")
+        try:
+            data_arr[j, k:k+length] = diagonal[...,:length]
+        except ValueError as e:
+            if len(diagonal) != length and len(diagonal) != 1:
+                raise ValueError(
+                    f"Diagonal length (index {j}: {len(diagonal)} at"
+                    f" offset {offset}) does not agree with array size ({m}, {n})."
+                ) from e
+            raise
+
+    return dia_array((data_arr, offsets), shape=(m, n)).asformat(format)
+
+
+def diags(diagonals, offsets=0, shape=None, format=None, dtype=None):
+    """
+    Construct a sparse matrix from diagonals.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``diags_array`` to take advantage
+        of the sparse array functionality.
+
+    Parameters
+    ----------
+    diagonals : sequence of array_like
+        Sequence of arrays containing the matrix diagonals,
+        corresponding to `offsets`.
+    offsets : sequence of int or an int, optional
+        Diagonals to set (repeated offsets are not allowed):
+          - k = 0  the main diagonal (default)
+          - k > 0  the kth upper diagonal
+          - k < 0  the kth lower diagonal
+    shape : tuple of int, optional
+        Shape of the result. If omitted, a square matrix large enough
+        to contain the diagonals is returned.
+    format : {"dia", "csr", "csc", "lil", ...}, optional
+        Matrix format of the result. By default (format=None) an
+        appropriate sparse matrix format is returned. This choice is
+        subject to change.
+    dtype : dtype, optional
+        Data type of the matrix.
+
+    See Also
+    --------
+    spdiags : construct matrix from diagonals
+    diags_array : construct sparse array instead of sparse matrix
+
+    Notes
+    -----
+    Repeated diagonal offsets are disallowed.
+
+    The result from `diags` is the sparse equivalent of::
+
+        np.diag(diagonals[0], offsets[0])
+        + ...
+        + np.diag(diagonals[k], offsets[k])
+
+    ``diags`` differs from ``dia_matrix`` in the way it handles off-diagonals.
+    Specifically, `dia_matrix` assumes the data input includes padding
+    (ignored values) at the start/end of the rows for positive/negative
+    offset, while ``diags` assumes the input data has no padding.
+    Each value in the input ``diagonals`` is used.
+
+    .. versionadded:: 0.11
+
+    Examples
+    --------
+    >>> from scipy.sparse import diags
+    >>> diagonals = [[1, 2, 3, 4], [1, 2, 3], [1, 2]]
+    >>> diags(diagonals, [0, -1, 2]).toarray()
+    array([[1., 0., 1., 0.],
+           [1., 2., 0., 2.],
+           [0., 2., 3., 0.],
+           [0., 0., 3., 4.]])
+
+    Broadcasting of scalars is supported (but shape needs to be
+    specified):
+
+    >>> diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)).toarray()
+    array([[-2.,  1.,  0.,  0.],
+           [ 1., -2.,  1.,  0.],
+           [ 0.,  1., -2.,  1.],
+           [ 0.,  0.,  1., -2.]])
+
+
+    If only one diagonal is wanted (as in `numpy.diag`), the following
+    works as well:
+
+    >>> diags([1, 2, 3], 1).toarray()
+    array([[ 0.,  1.,  0.,  0.],
+           [ 0.,  0.,  2.,  0.],
+           [ 0.,  0.,  0.,  3.],
+           [ 0.,  0.,  0.,  0.]])
+
+    """
+    A = diags_array(diagonals, offsets=offsets, shape=shape, dtype=dtype)
+    return dia_matrix(A).asformat(format)
+
+
+def identity(n, dtype='d', format=None):
+    """Identity matrix in sparse format
+
+    Returns an identity matrix with shape (n,n) using a given
+    sparse format and dtype. This differs from `eye_array` in
+    that it has a square shape with ones only on the main diagonal.
+    It is thus the multiplicative identity. `eye_array` allows
+    rectangular shapes and the diagonal can be offset from the main one.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``eye_array`` to take advantage
+        of the sparse array functionality.
+
+    Parameters
+    ----------
+    n : int
+        Shape of the identity matrix.
+    dtype : dtype, optional
+        Data type of the matrix
+    format : str, optional
+        Sparse format of the result, e.g., format="csr", etc.
+
+    Examples
+    --------
+    >>> import scipy as sp
+    >>> sp.sparse.identity(3).toarray()
+    array([[ 1.,  0.,  0.],
+           [ 0.,  1.,  0.],
+           [ 0.,  0.,  1.]])
+    >>> sp.sparse.identity(3, dtype='int8', format='dia')
+    
+    >>> sp.sparse.eye_array(3, dtype='int8', format='dia')
+    
+
+    """
+    return eye(n, n, dtype=dtype, format=format)
+
+
+def eye_array(m, n=None, *, k=0, dtype=float, format=None):
+    """Identity matrix in sparse array format
+
+    Return a sparse array with ones on diagonal.
+    Specifically a sparse array (m x n) where the kth diagonal
+    is all ones and everything else is zeros.
+
+    Parameters
+    ----------
+    m : int
+        Number of rows requested.
+    n : int, optional
+        Number of columns. Default: `m`.
+    k : int, optional
+        Diagonal to place ones on. Default: 0 (main diagonal).
+    dtype : dtype, optional
+        Data type of the array
+    format : str, optional (default: "dia")
+        Sparse format of the result, e.g., format="csr", etc.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> sp.sparse.eye_array(3).toarray()
+    array([[ 1.,  0.,  0.],
+           [ 0.,  1.,  0.],
+           [ 0.,  0.,  1.]])
+    >>> sp.sparse.eye_array(3, dtype=np.int8)
+    
+
+    """
+    # TODO: delete next 15 lines [combine with _eye()] once spmatrix removed
+    return _eye(m, n, k, dtype, format)
+
+
+def _eye(m, n, k, dtype, format, as_sparray=True):
+    if as_sparray:
+        csr_sparse = csr_array
+        csc_sparse = csc_array
+        coo_sparse = coo_array
+        diags_sparse = diags_array
+    else:
+        csr_sparse = csr_matrix
+        csc_sparse = csc_matrix
+        coo_sparse = coo_matrix
+        diags_sparse = diags
+
+    if n is None:
+        n = m
+    m, n = int(m), int(n)
+
+    if m == n and k == 0:
+        # fast branch for special formats
+        if format in ['csr', 'csc']:
+            idx_dtype = get_index_dtype(maxval=n)
+            indptr = np.arange(n+1, dtype=idx_dtype)
+            indices = np.arange(n, dtype=idx_dtype)
+            data = np.ones(n, dtype=dtype)
+            cls = {'csr': csr_sparse, 'csc': csc_sparse}[format]
+            return cls((data, indices, indptr), (n, n))
+
+        elif format == 'coo':
+            idx_dtype = get_index_dtype(maxval=n)
+            row = np.arange(n, dtype=idx_dtype)
+            col = np.arange(n, dtype=idx_dtype)
+            data = np.ones(n, dtype=dtype)
+            return coo_sparse((data, (row, col)), (n, n))
+
+    data = np.ones((1, max(0, min(m + k, n))), dtype=dtype)
+    return diags_sparse(data, offsets=[k], shape=(m, n), dtype=dtype).asformat(format)
+
+
+def eye(m, n=None, k=0, dtype=float, format=None):
+    """Sparse matrix with ones on diagonal
+
+    Returns a sparse matrix (m x n) where the kth diagonal
+    is all ones and everything else is zeros.
+
+    Parameters
+    ----------
+    m : int
+        Number of rows in the matrix.
+    n : int, optional
+        Number of columns. Default: `m`.
+    k : int, optional
+        Diagonal to place ones on. Default: 0 (main diagonal).
+    dtype : dtype, optional
+        Data type of the matrix.
+    format : str, optional
+        Sparse format of the result, e.g., format="csr", etc.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``eye_array`` to take advantage
+        of the sparse array functionality.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> sp.sparse.eye(3).toarray()
+    array([[ 1.,  0.,  0.],
+           [ 0.,  1.,  0.],
+           [ 0.,  0.,  1.]])
+    >>> sp.sparse.eye(3, dtype=np.int8)
+    
+
+    """
+    return _eye(m, n, k, dtype, format, False)
+
+
+def kron(A, B, format=None):
+    """kronecker product of sparse matrices A and B
+
+    Parameters
+    ----------
+    A : sparse or dense matrix
+        first matrix of the product
+    B : sparse or dense matrix
+        second matrix of the product
+    format : str, optional (default: 'bsr' or 'coo')
+        format of the result (e.g. "csr")
+        If None, choose 'bsr' for relatively dense array and 'coo' for others
+
+    Returns
+    -------
+    kronecker product in a sparse format.
+    Returns a sparse matrix unless either A or B is a
+    sparse array in which case returns a sparse array.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> A = sp.sparse.csr_array(np.array([[0, 2], [5, 0]]))
+    >>> B = sp.sparse.csr_array(np.array([[1, 2], [3, 4]]))
+    >>> sp.sparse.kron(A, B).toarray()
+    array([[ 0,  0,  2,  4],
+           [ 0,  0,  6,  8],
+           [ 5, 10,  0,  0],
+           [15, 20,  0,  0]])
+
+    >>> sp.sparse.kron(A, [[1, 2], [3, 4]]).toarray()
+    array([[ 0,  0,  2,  4],
+           [ 0,  0,  6,  8],
+           [ 5, 10,  0,  0],
+           [15, 20,  0,  0]])
+
+    """
+    # TODO: delete next 10 lines and replace _sparse with _array when spmatrix removed
+    if isinstance(A, sparray) or isinstance(B, sparray):
+        # convert to local variables
+        bsr_sparse = bsr_array
+        csr_sparse = csr_array
+        coo_sparse = coo_array
+    else:  # use spmatrix
+        bsr_sparse = bsr_matrix
+        csr_sparse = csr_matrix
+        coo_sparse = coo_matrix
+
+    B = coo_sparse(B)
+    if B.ndim != 2:
+        raise ValueError(f"kron requires 2D input arrays. `B` is {B.ndim}D.")
+
+    # B is fairly dense, use BSR
+    if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]:
+        A = csr_sparse(A,copy=True)
+        if A.ndim != 2:
+            raise ValueError(f"kron requires 2D input arrays. `A` is {A.ndim}D.")
+        output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1])
+
+        if A.nnz == 0 or B.nnz == 0:
+            # kronecker product is the zero matrix
+            return coo_sparse(output_shape).asformat(format)
+
+        B = B.toarray()
+        data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1])
+        data = data * B
+
+        return bsr_sparse((data,A.indices,A.indptr), shape=output_shape)
+    else:
+        # use COO
+        A = coo_sparse(A)
+        if A.ndim != 2:
+            raise ValueError(f"kron requires 2D input arrays. `A` is {A.ndim}D.")
+        output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1])
+
+        if A.nnz == 0 or B.nnz == 0:
+            # kronecker product is the zero matrix
+            return coo_sparse(output_shape).asformat(format)
+
+        # expand entries of a into blocks
+        idx_dtype = get_index_dtype(A.coords, maxval=max(output_shape))
+        row = np.asarray(A.row, dtype=idx_dtype).repeat(B.nnz)
+        col = np.asarray(A.col, dtype=idx_dtype).repeat(B.nnz)
+        data = A.data.repeat(B.nnz)
+
+        row *= B.shape[0]
+        col *= B.shape[1]
+
+        # increment block indices
+        row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz)
+        row += B.row
+        col += B.col
+        row,col = row.reshape(-1),col.reshape(-1)
+
+        # compute block entries
+        data = data.reshape(-1,B.nnz) * B.data
+        data = data.reshape(-1)
+
+        return coo_sparse((data,(row,col)), shape=output_shape).asformat(format)
+
+
+def kronsum(A, B, format=None):
+    """kronecker sum of square sparse matrices A and B
+
+    Kronecker sum of two sparse matrices is a sum of two Kronecker
+    products kron(I_n,A) + kron(B,I_m) where A has shape (m,m)
+    and B has shape (n,n) and I_m and I_n are identity matrices
+    of shape (m,m) and (n,n), respectively.
+
+    Parameters
+    ----------
+    A
+        square matrix
+    B
+        square matrix
+    format : str
+        format of the result (e.g. "csr")
+
+    Returns
+    -------
+    kronecker sum in a sparse matrix format
+
+    """
+    # TODO: delete next 8 lines and replace _sparse with _array when spmatrix removed
+    if isinstance(A, sparray) or isinstance(B, sparray):
+        # convert to local variables
+        coo_sparse = coo_array
+        identity_sparse = eye_array
+    else:
+        coo_sparse = coo_matrix
+        identity_sparse = identity
+
+    A = coo_sparse(A)
+    B = coo_sparse(B)
+
+    if A.ndim != 2:
+        raise ValueError(f"kronsum requires 2D inputs. `A` is {A.ndim}D.")
+    if B.ndim != 2:
+        raise ValueError(f"kronsum requires 2D inputs. `B` is {B.ndim}D.")
+    if A.shape[0] != A.shape[1]:
+        raise ValueError('A is not square')
+    if B.shape[0] != B.shape[1]:
+        raise ValueError('B is not square')
+
+    dtype = upcast(A.dtype, B.dtype)
+
+    I_n = identity_sparse(A.shape[0], dtype=dtype)
+    I_m = identity_sparse(B.shape[0], dtype=dtype)
+    L = kron(I_m, A, format='coo')
+    R = kron(B, I_n, format='coo')
+
+    return (L + R).asformat(format)
+
+
+def _compressed_sparse_stack(blocks, axis, return_spmatrix):
+    """
+    Stacking fast path for CSR/CSC matrices or arrays
+    (i) vstack for CSR, (ii) hstack for CSC.
+    """
+    other_axis = 1 if axis == 0 else 0
+    data = np.concatenate([b.data for b in blocks])
+    constant_dim = blocks[0]._shape_as_2d[other_axis]
+    idx_dtype = get_index_dtype(arrays=[b.indptr for b in blocks],
+                                maxval=max(data.size, constant_dim))
+    indices = np.empty(data.size, dtype=idx_dtype)
+    indptr = np.empty(sum(b._shape_as_2d[axis] for b in blocks) + 1, dtype=idx_dtype)
+    last_indptr = idx_dtype(0)
+    sum_dim = 0
+    sum_indices = 0
+    for b in blocks:
+        if b._shape_as_2d[other_axis] != constant_dim:
+            raise ValueError(f'incompatible dimensions for axis {other_axis}')
+        indices[sum_indices:sum_indices+b.indices.size] = b.indices
+        sum_indices += b.indices.size
+        idxs = slice(sum_dim, sum_dim + b._shape_as_2d[axis])
+        indptr[idxs] = b.indptr[:-1]
+        indptr[idxs] += last_indptr
+        sum_dim += b._shape_as_2d[axis]
+        last_indptr += b.indptr[-1]
+    indptr[-1] = last_indptr
+    # TODO remove this if-structure when sparse matrices removed
+    if return_spmatrix:
+        if axis == 0:
+            return csr_matrix((data, indices, indptr),
+                              shape=(sum_dim, constant_dim))
+        else:
+            return csc_matrix((data, indices, indptr),
+                              shape=(constant_dim, sum_dim))
+
+    if axis == 0:
+        return csr_array((data, indices, indptr),
+                          shape=(sum_dim, constant_dim))
+    else:
+        return csc_array((data, indices, indptr),
+                          shape=(constant_dim, sum_dim))
+
+
+def _stack_along_minor_axis(blocks, axis):
+    """
+    Stacking fast path for CSR/CSC matrices along the minor axis
+    (i) hstack for CSR, (ii) vstack for CSC.
+    """
+    n_blocks = len(blocks)
+    if n_blocks == 0:
+        raise ValueError('Missing block matrices')
+
+    if n_blocks == 1:
+        return blocks[0]
+
+    # check for incompatible dimensions
+    other_axis = 1 if axis == 0 else 0
+    other_axis_dims = {b._shape_as_2d[other_axis] for b in blocks}
+    if len(other_axis_dims) > 1:
+        raise ValueError(f'Mismatching dimensions along axis {other_axis}: '
+                         f'{other_axis_dims}')
+    constant_dim, = other_axis_dims
+
+    # Do the stacking
+    indptr_list = [b.indptr for b in blocks]
+    data_cat = np.concatenate([b.data for b in blocks])
+
+    # Need to check if any indices/indptr, would be too large post-
+    # concatenation for np.int32:
+    # - The max value of indices is the output array's stacking-axis length - 1
+    # - The max value in indptr is the number of non-zero entries. This is
+    #   exceedingly unlikely to require int64, but is checked out of an
+    #   abundance of caution.
+    sum_dim = sum(b._shape_as_2d[axis] for b in blocks)
+    nnz = sum(len(b.indices) for b in blocks)
+    idx_dtype = get_index_dtype(indptr_list, maxval=max(sum_dim - 1, nnz))
+    stack_dim_cat = np.array([b._shape_as_2d[axis] for b in blocks], dtype=idx_dtype)
+    if data_cat.size > 0:
+        indptr_cat = np.concatenate(indptr_list, dtype=idx_dtype)
+        indices_cat = np.concatenate([b.indices for b in blocks], dtype=idx_dtype)
+        indptr = np.empty(constant_dim + 1, dtype=idx_dtype)
+        indices = np.empty_like(indices_cat)
+        data = np.empty_like(data_cat)
+        csr_hstack(n_blocks, constant_dim, stack_dim_cat,
+                   indptr_cat, indices_cat, data_cat,
+                   indptr, indices, data)
+    else:
+        indptr = np.zeros(constant_dim + 1, dtype=idx_dtype)
+        indices = np.empty(0, dtype=idx_dtype)
+        data = np.empty(0, dtype=data_cat.dtype)
+
+    if axis == 0:
+        return blocks[0]._csc_container((data, indices, indptr),
+                          shape=(sum_dim, constant_dim))
+    else:
+        return blocks[0]._csr_container((data, indices, indptr),
+                          shape=(constant_dim, sum_dim))
+
+
+def hstack(blocks, format=None, dtype=None):
+    """
+    Stack sparse matrices horizontally (column wise)
+
+    Parameters
+    ----------
+    blocks
+        sequence of sparse matrices with compatible shapes
+    format : str
+        sparse format of the result (e.g., "csr")
+        by default an appropriate sparse matrix format is returned.
+        This choice is subject to change.
+    dtype : dtype, optional
+        The data-type of the output matrix. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    new_array : sparse matrix or array
+        If any block in blocks is a sparse array, return a sparse array.
+        Otherwise return a sparse matrix.
+
+        If you want a sparse array built from blocks that are not sparse
+        arrays, use ``block(hstack(blocks))`` or convert one block
+        e.g. ``blocks[0] = csr_array(blocks[0])``.
+
+    See Also
+    --------
+    vstack : stack sparse matrices vertically (row wise)
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_matrix, hstack
+    >>> A = coo_matrix([[1, 2], [3, 4]])
+    >>> B = coo_matrix([[5], [6]])
+    >>> hstack([A,B]).toarray()
+    array([[1, 2, 5],
+           [3, 4, 6]])
+
+    """
+    blocks = np.asarray(blocks, dtype='object')
+    if any(isinstance(b, sparray) for b in blocks.flat):
+        return _block([blocks], format, dtype)
+    else:
+        return _block([blocks], format, dtype, return_spmatrix=True)
+
+
+def vstack(blocks, format=None, dtype=None):
+    """
+    Stack sparse arrays vertically (row wise)
+
+    Parameters
+    ----------
+    blocks
+        sequence of sparse arrays with compatible shapes
+    format : str, optional
+        sparse format of the result (e.g., "csr")
+        by default an appropriate sparse array format is returned.
+        This choice is subject to change.
+    dtype : dtype, optional
+        The data-type of the output array. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    new_array : sparse matrix or array
+        If any block in blocks is a sparse array, return a sparse array.
+        Otherwise return a sparse matrix.
+
+        If you want a sparse array built from blocks that are not sparse
+        arrays, use ``block(vstack(blocks))`` or convert one block
+        e.g. `blocks[0] = csr_array(blocks[0])`.
+
+    See Also
+    --------
+    hstack : stack sparse matrices horizontally (column wise)
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, vstack
+    >>> A = coo_array([[1, 2], [3, 4]])
+    >>> B = coo_array([[5, 6]])
+    >>> vstack([A, B]).toarray()
+    array([[1, 2],
+           [3, 4],
+           [5, 6]])
+
+    """
+    blocks = np.asarray(blocks, dtype='object')
+    if any(isinstance(b, sparray) for b in blocks.flat):
+        return _block([[b] for b in blocks], format, dtype)
+    else:
+        return _block([[b] for b in blocks], format, dtype, return_spmatrix=True)
+
+
+def bmat(blocks, format=None, dtype=None):
+    """
+    Build a sparse array or matrix from sparse sub-blocks
+
+    Note: `block_array` is preferred over `bmat`. They are the same function
+    except that `bmat` can return a deprecated sparse matrix.
+    `bmat` returns a coo_matrix if none of the inputs are a sparse array.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``block_array`` to take advantage
+        of the sparse array functionality.
+
+    Parameters
+    ----------
+    blocks : array_like
+        Grid of sparse matrices with compatible shapes.
+        An entry of None implies an all-zero matrix.
+    format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional
+        The sparse format of the result (e.g. "csr"). By default an
+        appropriate sparse matrix format is returned.
+        This choice is subject to change.
+    dtype : dtype, optional
+        The data-type of the output matrix. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    bmat : sparse matrix or array
+        If any block in blocks is a sparse array, return a sparse array.
+        Otherwise return a sparse matrix.
+
+        If you want a sparse array built from blocks that are not sparse
+        arrays, use ``block_array()``.
+
+    See Also
+    --------
+    block_array
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, bmat
+    >>> A = coo_array([[1, 2], [3, 4]])
+    >>> B = coo_array([[5], [6]])
+    >>> C = coo_array([[7]])
+    >>> bmat([[A, B], [None, C]]).toarray()
+    array([[1, 2, 5],
+           [3, 4, 6],
+           [0, 0, 7]])
+
+    >>> bmat([[A, None], [None, C]]).toarray()
+    array([[1, 2, 0],
+           [3, 4, 0],
+           [0, 0, 7]])
+
+    """
+    blocks = np.asarray(blocks, dtype='object')
+    if any(isinstance(b, sparray) for b in blocks.flat):
+        return _block(blocks, format, dtype)
+    else:
+        return _block(blocks, format, dtype, return_spmatrix=True)
+
+
+def block_array(blocks, *, format=None, dtype=None):
+    """
+    Build a sparse array from sparse sub-blocks
+
+    Parameters
+    ----------
+    blocks : array_like
+        Grid of sparse arrays with compatible shapes.
+        An entry of None implies an all-zero array.
+    format : {'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional
+        The sparse format of the result (e.g. "csr"). By default an
+        appropriate sparse array format is returned.
+        This choice is subject to change.
+    dtype : dtype, optional
+        The data-type of the output array. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    block : sparse array
+
+    See Also
+    --------
+    block_diag : specify blocks along the main diagonals
+    diags : specify (possibly offset) diagonals
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, block_array
+    >>> A = coo_array([[1, 2], [3, 4]])
+    >>> B = coo_array([[5], [6]])
+    >>> C = coo_array([[7]])
+    >>> block_array([[A, B], [None, C]]).toarray()
+    array([[1, 2, 5],
+           [3, 4, 6],
+           [0, 0, 7]])
+
+    >>> block_array([[A, None], [None, C]]).toarray()
+    array([[1, 2, 0],
+           [3, 4, 0],
+           [0, 0, 7]])
+
+    """
+    return _block(blocks, format, dtype)
+
+
+def _block(blocks, format, dtype, return_spmatrix=False):
+    blocks = np.asarray(blocks, dtype='object')
+
+    if blocks.ndim != 2:
+        raise ValueError('blocks must be 2-D')
+
+    M,N = blocks.shape
+
+    # check for fast path cases
+    if (format in (None, 'csr') and
+        all(issparse(b) and b.format == 'csr' for b in blocks.flat)
+    ):
+        if N > 1:
+            # stack along columns (axis 1): must have shape (M, 1)
+            blocks = [[_stack_along_minor_axis(blocks[b, :], 1)] for b in range(M)]
+            blocks = np.asarray(blocks, dtype='object')
+
+        # stack along rows (axis 0):
+        A = _compressed_sparse_stack(blocks[:, 0], 0, return_spmatrix)
+        if dtype is not None:
+            A = A.astype(dtype, copy=False)
+        return A
+    elif (format in (None, 'csc') and
+          all(issparse(b) and b.format == 'csc' for b in blocks.flat)
+    ):
+        if M > 1:
+            # stack along rows (axis 0): must have shape (1, N)
+            blocks = [[_stack_along_minor_axis(blocks[:, b], 0) for b in range(N)]]
+            blocks = np.asarray(blocks, dtype='object')
+
+        # stack along columns (axis 1):
+        A = _compressed_sparse_stack(blocks[0, :], 1, return_spmatrix)
+        if dtype is not None:
+            A = A.astype(dtype, copy=False)
+        return A
+
+    block_mask = np.zeros(blocks.shape, dtype=bool)
+    brow_lengths = np.zeros(M, dtype=np.int64)
+    bcol_lengths = np.zeros(N, dtype=np.int64)
+
+    # convert everything to COO format
+    for i in range(M):
+        for j in range(N):
+            if blocks[i,j] is not None:
+                A = coo_array(blocks[i,j])
+                blocks[i,j] = A
+                block_mask[i,j] = True
+
+                if brow_lengths[i] == 0:
+                    brow_lengths[i] = A._shape_as_2d[0]
+                elif brow_lengths[i] != A._shape_as_2d[0]:
+                    msg = (f'blocks[{i},:] has incompatible row dimensions. '
+                           f'Got blocks[{i},{j}].shape[0] == {A._shape_as_2d[0]}, '
+                           f'expected {brow_lengths[i]}.')
+                    raise ValueError(msg)
+
+                if bcol_lengths[j] == 0:
+                    bcol_lengths[j] = A._shape_as_2d[1]
+                elif bcol_lengths[j] != A._shape_as_2d[1]:
+                    msg = (f'blocks[:,{j}] has incompatible column '
+                           f'dimensions. '
+                           f'Got blocks[{i},{j}].shape[1] == {A._shape_as_2d[1]}, '
+                           f'expected {bcol_lengths[j]}.')
+                    raise ValueError(msg)
+
+    nnz = sum(block.nnz for block in blocks[block_mask])
+    if dtype is None:
+        all_dtypes = [blk.dtype for blk in blocks[block_mask]]
+        dtype = upcast(*all_dtypes) if all_dtypes else None
+
+    row_offsets = np.append(0, np.cumsum(brow_lengths))
+    col_offsets = np.append(0, np.cumsum(bcol_lengths))
+
+    shape = (row_offsets[-1], col_offsets[-1])
+
+    data = np.empty(nnz, dtype=dtype)
+    idx_dtype = get_index_dtype([b.coords[0] for b in blocks[block_mask]],
+                                maxval=max(shape))
+    row = np.empty(nnz, dtype=idx_dtype)
+    col = np.empty(nnz, dtype=idx_dtype)
+
+    nnz = 0
+    ii, jj = np.nonzero(block_mask)
+    for i, j in zip(ii, jj):
+        B = blocks[i, j]
+        idx = slice(nnz, nnz + B.nnz)
+        data[idx] = B.data
+        np.add(B.row, row_offsets[i], out=row[idx], dtype=idx_dtype)
+        np.add(B.col, col_offsets[j], out=col[idx], dtype=idx_dtype)
+        nnz += B.nnz
+
+    if return_spmatrix:
+        return coo_matrix((data, (row, col)), shape=shape).asformat(format)
+    return coo_array((data, (row, col)), shape=shape).asformat(format)
+
+
+def block_diag(mats, format=None, dtype=None):
+    """
+    Build a block diagonal sparse matrix or array from provided matrices.
+
+    Parameters
+    ----------
+    mats : sequence of matrices or arrays
+        Input matrices or arrays.
+    format : str, optional
+        The sparse format of the result (e.g., "csr"). If not given, the result
+        is returned in "coo" format.
+    dtype : dtype specifier, optional
+        The data-type of the output. If not given, the dtype is
+        determined from that of `blocks`.
+
+    Returns
+    -------
+    res : sparse matrix or array
+        If at least one input is a sparse array, the output is a sparse array.
+        Otherwise the output is a sparse matrix.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.11.0
+
+    See Also
+    --------
+    block_array
+    diags_array
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, block_diag
+    >>> A = coo_array([[1, 2], [3, 4]])
+    >>> B = coo_array([[5], [6]])
+    >>> C = coo_array([[7]])
+    >>> block_diag((A, B, C)).toarray()
+    array([[1, 2, 0, 0],
+           [3, 4, 0, 0],
+           [0, 0, 5, 0],
+           [0, 0, 6, 0],
+           [0, 0, 0, 7]])
+
+    """
+    if any(isinstance(a, sparray) for a in mats):
+        container = coo_array
+    else:
+        container = coo_matrix
+
+    row = []
+    col = []
+    data = []
+    idx_arrays = []  # track idx_dtype of incoming sparse arrays
+    r_idx = 0
+    c_idx = 0
+    for a in mats:
+        if isinstance(a, (list | numbers.Number)):
+            a = coo_array(np.atleast_2d(a))
+        if issparse(a):
+            a = a.tocoo()
+            if not idx_arrays and a.coords[0].dtype == np.int64:
+                idx_arrays.append(a.coords[0])
+            nrows, ncols = a._shape_as_2d
+            row.append(a.row + r_idx)
+            col.append(a.col + c_idx)
+            data.append(a.data)
+        else:
+            nrows, ncols = a.shape
+            a_row, a_col = np.divmod(np.arange(nrows*ncols), ncols)
+            row.append(a_row + r_idx)
+            col.append(a_col + c_idx)
+            data.append(a.ravel())
+        r_idx += nrows
+        c_idx += ncols
+    idx_dtype = get_index_dtype(idx_arrays, maxval=max(r_idx, c_idx))
+    row = np.concatenate(row, dtype=idx_dtype)
+    col = np.concatenate(col, dtype=idx_dtype)
+    data = np.concatenate(data)
+    new_shape = (r_idx, c_idx)
+
+    return container((data, (row, col)), shape=new_shape, dtype=dtype).asformat(format)
+
+
+@_transition_to_rng("random_state")
+def random_array(shape, *, density=0.01, format='coo', dtype=None,
+                 rng=None, data_sampler=None):
+    """Return a sparse array of uniformly random numbers in [0, 1)
+
+    Returns a sparse array with the given shape and density
+    where values are generated uniformly randomly in the range [0, 1).
+
+    Parameters
+    ----------
+    shape : int or tuple of ints
+        shape of the array
+    density : real, optional (default: 0.01)
+        density of the generated matrix: density equal to one means a full
+        matrix, density of 0 means a matrix with no non-zero items.
+    format : str, optional (default: 'coo')
+        sparse matrix format.
+    dtype : dtype, optional (default: np.float64)
+        type of the returned matrix values.
+    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``.
+
+        This random state will be used for sampling `indices` (the sparsity
+        structure), and by default for the data values too (see `data_sampler`).
+    data_sampler : callable, optional (default depends on dtype)
+        Sampler of random data values with keyword arg `size`.
+        This function should take a single keyword argument `size` specifying
+        the length of its returned ndarray. It is used to generate the nonzero
+        values in the matrix after the locations of those values are chosen.
+        By default, uniform [0, 1) random values are used unless `dtype` is
+        an integer (default uniform integers from that dtype) or
+        complex (default uniform over the unit square in the complex plane).
+        For these, the `rng` is used e.g. ``rng.uniform(size=size)``.
+
+    Returns
+    -------
+    res : sparse array
+
+    Examples
+    --------
+
+    Passing a ``np.random.Generator`` instance for better performance:
+
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> rng = np.random.default_rng()
+
+    Default sampling uniformly from [0, 1):
+
+    >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng)
+
+    Providing a sampler for the values:
+
+    >>> rvs = sp.stats.poisson(25, loc=10).rvs
+    >>> S = sp.sparse.random_array((3, 4), density=0.25,
+    ...                            rng=rng, data_sampler=rvs)
+    >>> S.toarray()
+    array([[ 36.,   0.,  33.,   0.],   # random
+           [  0.,   0.,   0.,   0.],
+           [  0.,   0.,  36.,   0.]])
+
+    Building a custom distribution.
+    This example builds a squared normal from np.random:
+
+    >>> def np_normal_squared(size=None, rng=rng):
+    ...     return rng.standard_normal(size) ** 2
+    >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng,
+    ...                            data_sampler=np_normal_squared)
+
+    Or we can build it from sp.stats style rvs functions:
+
+    >>> def sp_stats_normal_squared(size=None, rng=rng):
+    ...     std_normal = sp.stats.distributions.norm_gen().rvs
+    ...     return std_normal(size=size, random_state=rng) ** 2
+    >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng,
+    ...                            data_sampler=sp_stats_normal_squared)
+
+    Or we can subclass sp.stats rv_continuous or rv_discrete:
+
+    >>> class NormalSquared(sp.stats.rv_continuous):
+    ...     def _rvs(self,  size=None, random_state=rng):
+    ...         return rng.standard_normal(size) ** 2
+    >>> X = NormalSquared()
+    >>> Y = X().rvs
+    >>> S = sp.sparse.random_array((3, 4), density=0.25,
+    ...                            rng=rng, data_sampler=Y)
+    """
+    data, ind = _random(shape, density, format, dtype, rng, data_sampler)
+
+    # downcast, if safe, before calling coo_constructor
+    idx_dtype = get_index_dtype(maxval=max(shape))
+    ind = tuple(np.asarray(co, dtype=idx_dtype) for co in ind)
+    return coo_array((data, ind), shape=shape).asformat(format)
+
+
+def _random(shape, density=0.01, format=None, dtype=None,
+            rng=None, data_sampler=None):
+    if density < 0 or density > 1:
+        raise ValueError("density expected to be 0 <= density <= 1")
+
+    tot_prod = math.prod(shape)  # use `math` for when prod is >= 2**64
+
+    # Number of non zero values
+    size = int(round(density * tot_prod))
+
+    rng = check_random_state(rng)
+
+    if data_sampler is None:
+        if np.issubdtype(dtype, np.integer):
+            def data_sampler(size):
+                return rng_integers(rng,
+                                    np.iinfo(dtype).min,
+                                    np.iinfo(dtype).max,
+                                    size,
+                                    dtype=dtype)
+        elif np.issubdtype(dtype, np.complexfloating):
+            def data_sampler(size):
+                return (rng.uniform(size=size) +
+                        rng.uniform(size=size) * 1j)
+        else:
+            data_sampler = rng.uniform
+
+    idx_dtype = get_index_dtype(maxval=max(shape))
+    # rng.choice uses int64 if first arg is an int
+    if tot_prod <= np.iinfo(np.int64).max:
+        raveled_ind = rng.choice(tot_prod, size=size, replace=False)
+        ind = np.unravel_index(raveled_ind, shape=shape, order='F')
+        ind = tuple(np.asarray(co, idx_dtype) for co in ind)
+    else:
+        # for ravel indices bigger than dtype max, use sets to remove duplicates
+        ndim = len(shape)
+        seen = set()
+        while len(seen) < size:
+            dsize = size - len(seen)
+            seen.update(map(tuple, rng_integers(rng, shape, size=(dsize, ndim))))
+        ind = tuple(np.array(list(seen), dtype=idx_dtype).T)
+
+    # size kwarg allows eg data_sampler=partial(np.random.poisson, lam=5)
+    vals = data_sampler(size=size).astype(dtype, copy=False)
+    return vals, ind
+
+
+@_transition_to_rng("random_state", position_num=5)
+def random(m, n, density=0.01, format='coo', dtype=None,
+           rng=None, data_rvs=None):
+    """Generate a sparse matrix of the given shape and density with randomly
+    distributed values.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``random_array`` to take advantage of the
+        sparse array functionality.
+
+    Parameters
+    ----------
+    m, n : int
+        shape of the matrix
+    density : real, optional
+        density of the generated matrix: density equal to one means a full
+        matrix, density of 0 means a matrix with no non-zero items.
+    format : str, optional
+        sparse matrix format.
+    dtype : dtype, optional
+        type of the returned matrix values.
+    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``.
+
+        This random state will be used for sampling the sparsity structure, but
+        not necessarily for sampling the values of the structurally nonzero
+        entries of the matrix.
+    data_rvs : callable, optional
+        Samples a requested number of random values.
+        This function should take a single argument specifying the length
+        of the ndarray that it will return. The structurally nonzero entries
+        of the sparse random matrix will be taken from the array sampled
+        by this function. By default, uniform [0, 1) random values will be
+        sampled using the same random state as is used for sampling
+        the sparsity structure.
+
+    Returns
+    -------
+    res : sparse matrix
+
+    See Also
+    --------
+    random_array : constructs sparse arrays instead of sparse matrices
+
+    Examples
+    --------
+
+    Passing a ``np.random.Generator`` instance for better performance:
+
+    >>> import scipy as sp
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng)
+
+    Providing a sampler for the values:
+
+    >>> rvs = sp.stats.poisson(25, loc=10).rvs
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=rvs)
+    >>> S.toarray()
+    array([[ 36.,   0.,  33.,   0.],   # random
+           [  0.,   0.,   0.,   0.],
+           [  0.,   0.,  36.,   0.]])
+
+    Building a custom distribution.
+    This example builds a squared normal from np.random:
+
+    >>> def np_normal_squared(size=None, rng=rng):
+    ...     return rng.standard_normal(size) ** 2
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng,
+    ...                      data_rvs=np_normal_squared)
+
+    Or we can build it from sp.stats style rvs functions:
+
+    >>> def sp_stats_normal_squared(size=None, rng=rng):
+    ...     std_normal = sp.stats.distributions.norm_gen().rvs
+    ...     return std_normal(size=size, random_state=rng) ** 2
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng,
+    ...                      data_rvs=sp_stats_normal_squared)
+
+    Or we can subclass sp.stats rv_continuous or rv_discrete:
+
+    >>> class NormalSquared(sp.stats.rv_continuous):
+    ...     def _rvs(self,  size=None, random_state=rng):
+    ...         return rng.standard_normal(size) ** 2
+    >>> X = NormalSquared()
+    >>> Y = X()  # get a frozen version of the distribution
+    >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=Y.rvs)
+    """
+    if n is None:
+        n = m
+    m, n = int(m), int(n)
+    # make keyword syntax work for data_rvs e.g. data_rvs(size=7)
+    if data_rvs is not None:
+        def data_rvs_kw(size):
+            return data_rvs(size)
+    else:
+        data_rvs_kw = None
+    vals, ind = _random((m, n), density, format, dtype, rng, data_rvs_kw)
+    return coo_matrix((vals, ind), shape=(m, n)).asformat(format)
+
+
+@_transition_to_rng("random_state", position_num=5)
+def rand(m, n, density=0.01, format="coo", dtype=None, rng=None):
+    """Generate a sparse matrix of the given shape and density with uniformly
+    distributed values.
+
+    .. warning::
+
+        This function returns a sparse matrix -- not a sparse array.
+        You are encouraged to use ``random_array`` to take advantage
+        of the sparse array functionality.
+
+    Parameters
+    ----------
+    m, n : int
+        shape of the matrix
+    density : real, optional
+        density of the generated matrix: density equal to one means a full
+        matrix, density of 0 means a matrix with no non-zero items.
+    format : str, optional
+        sparse matrix format.
+    dtype : dtype, optional
+        type of the returned matrix values.
+    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
+    -------
+    res : sparse matrix
+
+    Notes
+    -----
+    Only float types are supported for now.
+
+    See Also
+    --------
+    random : Similar function allowing a custom random data sampler
+    random_array : Similar to random() but returns a sparse array
+
+    Examples
+    --------
+    >>> from scipy.sparse import rand
+    >>> matrix = rand(3, 4, density=0.25, format="csr", rng=42)
+    >>> matrix
+    
+    >>> matrix.toarray()
+    array([[0.05641158, 0.        , 0.        , 0.65088847],  # random
+           [0.        , 0.        , 0.        , 0.14286682],
+           [0.        , 0.        , 0.        , 0.        ]])
+
+    """
+    return random(m, n, density, format, dtype, rng)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_coo.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b1d577f90e5cf4d585aede3f30c6caf5b8ae059
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_coo.py
@@ -0,0 +1,1647 @@
+""" A sparse matrix in COOrdinate or 'triplet' format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['coo_array', 'coo_matrix', 'isspmatrix_coo']
+
+import math
+from warnings import warn
+
+import numpy as np
+
+from .._lib._util import copy_if_needed
+from ._matrix import spmatrix
+from ._sparsetools import (coo_tocsr, coo_todense, coo_todense_nd,
+                           coo_matvec, coo_matvec_nd, coo_matmat_dense,
+                           coo_matmat_dense_nd)
+from ._base import issparse, SparseEfficiencyWarning, _spbase, sparray
+from ._data import _data_matrix, _minmax_mixin
+from ._sputils import (upcast_char, to_native, isshape, getdtype,
+                       getdata, downcast_intp_index, get_index_dtype,
+                       check_shape, check_reshape_kwargs, isscalarlike, isdense)
+
+import operator
+
+
+class _coo_base(_data_matrix, _minmax_mixin):
+    _format = 'coo'
+    _allow_nd = range(1, 65)
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _data_matrix.__init__(self, arg1, maxprint=maxprint)
+        if not copy:
+            copy = copy_if_needed
+
+        if isinstance(arg1, tuple):
+            if isshape(arg1, allow_nd=self._allow_nd):
+                self._shape = check_shape(arg1, allow_nd=self._allow_nd)
+                idx_dtype = self._get_index_dtype(maxval=max(self._shape))
+                data_dtype = getdtype(dtype, default=float)
+                self.coords = tuple(np.array([], dtype=idx_dtype)
+                                     for _ in range(len(self._shape)))
+                self.data = np.array([], dtype=data_dtype)
+                self.has_canonical_format = True
+            else:
+                try:
+                    obj, coords = arg1
+                except (TypeError, ValueError) as e:
+                    raise TypeError('invalid input format') from e
+
+                if shape is None:
+                    if any(len(idx) == 0 for idx in coords):
+                        raise ValueError('cannot infer dimensions from zero '
+                                         'sized index arrays')
+                    shape = tuple(operator.index(np.max(idx)) + 1
+                                  for idx in coords)
+                self._shape = check_shape(shape, allow_nd=self._allow_nd)
+                idx_dtype = self._get_index_dtype(coords,
+                                                  maxval=max(self.shape),
+                                                  check_contents=True)
+                self.coords = tuple(np.array(idx, copy=copy, dtype=idx_dtype)
+                                     for idx in coords)
+                self.data = getdata(obj, copy=copy, dtype=dtype)
+                self.has_canonical_format = False
+        else:
+            if issparse(arg1):
+                if arg1.format == self.format and copy:
+                    self.coords = tuple(idx.copy() for idx in arg1.coords)
+                    self.data = arg1.data.astype(getdtype(dtype, arg1))  # copy=True
+                    self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd)
+                    self.has_canonical_format = arg1.has_canonical_format
+                else:
+                    coo = arg1.tocoo()
+                    self.coords = tuple(coo.coords)
+                    self.data = coo.data.astype(getdtype(dtype, coo), copy=False)
+                    self._shape = check_shape(coo.shape, allow_nd=self._allow_nd)
+                    self.has_canonical_format = False
+            else:
+                # dense argument
+                M = np.asarray(arg1)
+                if not isinstance(self, sparray):
+                    M = np.atleast_2d(M)
+                    if M.ndim != 2:
+                        raise TypeError(f'expected 2D array or matrix, not {M.ndim}D')
+
+                self._shape = check_shape(M.shape, allow_nd=self._allow_nd)
+                if shape is not None:
+                    if check_shape(shape, allow_nd=self._allow_nd) != self._shape:
+                        message = f'inconsistent shapes: {shape} != {self._shape}'
+                        raise ValueError(message)
+
+                index_dtype = self._get_index_dtype(maxval=max(self._shape))
+                coords = M.nonzero()
+                self.coords = tuple(idx.astype(index_dtype, copy=False)
+                                     for idx in coords)
+                self.data = getdata(M[coords], copy=copy, dtype=dtype)
+                self.has_canonical_format = True
+
+        if len(self._shape) > 2:
+            self.coords = tuple(idx.astype(np.int64, copy=False) for idx in self.coords)
+
+        self._check()
+
+    @property
+    def row(self):
+        if self.ndim > 1:
+            return self.coords[-2]
+        result = np.zeros_like(self.col)
+        result.setflags(write=False)
+        return result
+
+
+    @row.setter
+    def row(self, new_row):
+        if self.ndim < 2:
+            raise ValueError('cannot set row attribute of a 1-dimensional sparse array')
+        new_row = np.asarray(new_row, dtype=self.coords[-2].dtype)
+        self.coords = self.coords[:-2] + (new_row,) + self.coords[-1:]
+
+    @property
+    def col(self):
+        return self.coords[-1]
+
+    @col.setter
+    def col(self, new_col):
+        new_col = np.asarray(new_col, dtype=self.coords[-1].dtype)
+        self.coords = self.coords[:-1] + (new_col,)
+
+    def reshape(self, *args, **kwargs):
+        shape = check_shape(args, self.shape, allow_nd=self._allow_nd)
+        order, copy = check_reshape_kwargs(kwargs)
+
+        # Return early if reshape is not required
+        if shape == self.shape:
+            if copy:
+                return self.copy()
+            else:
+                return self
+
+        # When reducing the number of dimensions, we need to be careful about
+        # index overflow. This is why we can't simply call
+        # `np.ravel_multi_index()` followed by `np.unravel_index()` here.
+        flat_coords = _ravel_coords(self.coords, self.shape, order=order)
+        if len(shape) == 2:
+            if order == 'C':
+                new_coords = divmod(flat_coords, shape[1])
+            else:
+                new_coords = divmod(flat_coords, shape[0])[::-1]
+        else:
+            new_coords = np.unravel_index(flat_coords, shape, order=order)
+
+        idx_dtype = self._get_index_dtype(self.coords, maxval=max(shape))
+        new_coords = tuple(np.asarray(co, dtype=idx_dtype) for co in new_coords)
+
+        # Handle copy here rather than passing on to the constructor so that no
+        # copy will be made of `new_coords` regardless.
+        if copy:
+            new_data = self.data.copy()
+        else:
+            new_data = self.data
+
+        return self.__class__((new_data, new_coords), shape=shape, copy=False)
+
+    reshape.__doc__ = _spbase.reshape.__doc__
+
+    def _getnnz(self, axis=None):
+        if axis is None or (axis == 0 and self.ndim == 1):
+            nnz = len(self.data)
+            if any(len(idx) != nnz for idx in self.coords):
+                raise ValueError('all index and data arrays must have the '
+                                 'same length')
+
+            if self.data.ndim != 1 or any(idx.ndim != 1 for idx in self.coords):
+                raise ValueError('coordinates and data arrays must be 1-D')
+
+            return int(nnz)
+
+        if axis < 0:
+            axis += self.ndim
+        if axis >= self.ndim:
+            raise ValueError('axis out of bounds')
+
+        return np.bincount(downcast_intp_index(self.coords[1 - axis]),
+                           minlength=self.shape[1 - axis])
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def count_nonzero(self, axis=None):
+        self.sum_duplicates()
+        if axis is None:
+            return np.count_nonzero(self.data)
+
+        if axis < 0:
+            axis += self.ndim
+        if axis < 0 or axis >= self.ndim:
+            raise ValueError('axis out of bounds')
+        mask = self.data != 0
+        coord = self.coords[1 - axis][mask]
+        return np.bincount(downcast_intp_index(coord), minlength=self.shape[1 - axis])
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def _check(self):
+        """ Checks data structure for consistency """
+        if self.ndim != len(self.coords):
+            raise ValueError('mismatching number of index arrays for shape; '
+                             f'got {len(self.coords)}, expected {self.ndim}')
+
+        # index arrays should have integer data types
+        for i, idx in enumerate(self.coords):
+            if idx.dtype.kind != 'i':
+                warn(f'index array {i} has non-integer dtype ({idx.dtype.name})',
+                     stacklevel=3)
+
+        idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.shape))
+        self.coords = tuple(np.asarray(idx, dtype=idx_dtype)
+                             for idx in self.coords)
+        self.data = to_native(self.data)
+
+        if self.nnz > 0:
+            for i, idx in enumerate(self.coords):
+                if idx.max() >= self.shape[i]:
+                    raise ValueError(f'axis {i} index {idx.max()} exceeds '
+                                     f'matrix dimension {self.shape[i]}')
+                if idx.min() < 0:
+                    raise ValueError(f'negative axis {i} index: {idx.min()}')
+
+    def transpose(self, axes=None, copy=False):
+        if axes is None:
+            axes = range(self.ndim)[::-1]
+        elif isinstance(self, sparray):
+            if not hasattr(axes, "__len__") or len(axes) != self.ndim:
+                raise ValueError("axes don't match matrix dimensions")
+            if len(set(axes)) != self.ndim:
+                raise ValueError("repeated axis in transpose")
+        elif axes != (1, 0):
+            raise ValueError("Sparse matrices do not support an 'axes' "
+                             "parameter because swapping dimensions is the "
+                             "only logical permutation.")
+
+        permuted_shape = tuple(self._shape[i] for i in axes)
+        permuted_coords = tuple(self.coords[i] for i in axes)
+        return self.__class__((self.data, permuted_coords),
+                              shape=permuted_shape, copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def resize(self, *shape) -> None:
+        shape = check_shape(shape, allow_nd=self._allow_nd)
+        if self.ndim > 2:
+            raise ValueError("only 1-D or 2-D input accepted")
+        if len(shape) > 2:
+            raise ValueError("shape argument must be 1-D or 2-D")
+        # Check for added dimensions.
+        if len(shape) > self.ndim:
+            flat_coords = _ravel_coords(self.coords, self.shape)
+            max_size = math.prod(shape)
+            self.coords = np.unravel_index(flat_coords[:max_size], shape)
+            self.data = self.data[:max_size]
+            self._shape = shape
+            return
+
+        # Check for removed dimensions.
+        if len(shape) < self.ndim:
+            tmp_shape = (
+                self._shape[:len(shape) - 1]  # Original shape without last axis
+                + (-1,)  # Last axis is used to flatten the array
+                + (1,) * (self.ndim - len(shape))  # Pad with ones
+            )
+            tmp = self.reshape(tmp_shape)
+            self.coords = tmp.coords[:len(shape)]
+            self._shape = tmp.shape[:len(shape)]
+
+        # Handle truncation of existing dimensions.
+        is_truncating = any(old > new for old, new in zip(self.shape, shape))
+        if is_truncating:
+            mask = np.logical_and.reduce([
+                idx < size for idx, size in zip(self.coords, shape)
+            ])
+            if not mask.all():
+                self.coords = tuple(idx[mask] for idx in self.coords)
+                self.data = self.data[mask]
+
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+    def toarray(self, order=None, out=None):
+        B = self._process_toarray_args(order, out)
+        fortran = int(B.flags.f_contiguous)
+        if not fortran and not B.flags.c_contiguous:
+            raise ValueError("Output array must be C or F contiguous")
+        # This handles both 0D and 1D cases correctly regardless of the
+        # original shape.
+        if self.ndim == 1:
+            coo_todense_nd(np.array([1]), self.nnz, self.ndim,
+                           self.coords[0], self.data, B.ravel('A'), fortran)
+        elif self.ndim == 2:
+            M, N = self.shape
+            coo_todense(M, N, self.nnz, self.row, self.col, self.data,
+                        B.ravel('A'), fortran)
+        else:
+            if fortran:
+                strides = np.append(1, np.cumprod(self.shape[:-1]))
+            else:
+                strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1)
+            coords = np.concatenate(self.coords)
+            coo_todense_nd(strides, self.nnz, self.ndim,
+                           coords, self.data, B.ravel('A'), fortran)
+        # Note: reshape() doesn't copy here, but does return a new array (view).
+        return B.reshape(self.shape)
+
+    toarray.__doc__ = _spbase.toarray.__doc__
+
+    def tocsc(self, copy=False):
+        """Convert this array/matrix to Compressed Sparse Column format
+
+        Duplicate entries will be summed together.
+
+        Examples
+        --------
+        >>> from numpy import array
+        >>> from scipy.sparse import coo_array
+        >>> row  = array([0, 0, 1, 3, 1, 0, 0])
+        >>> col  = array([0, 2, 1, 3, 1, 0, 0])
+        >>> data = array([1, 1, 1, 1, 1, 1, 1])
+        >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsc()
+        >>> A.toarray()
+        array([[3, 0, 1, 0],
+               [0, 2, 0, 0],
+               [0, 0, 0, 0],
+               [0, 0, 0, 1]])
+
+        """
+        if self.ndim != 2:
+            raise ValueError(f'Cannot convert. CSC format must be 2D. Got {self.ndim}D')
+        if self.nnz == 0:
+            return self._csc_container(self.shape, dtype=self.dtype)
+        else:
+            from ._csc import csc_array
+            indptr, indices, data, shape = self._coo_to_compressed(csc_array._swap)
+
+            x = self._csc_container((data, indices, indptr), shape=shape)
+            if not self.has_canonical_format:
+                x.sum_duplicates()
+            return x
+
+    def tocsr(self, copy=False):
+        """Convert this array/matrix to Compressed Sparse Row format
+
+        Duplicate entries will be summed together.
+
+        Examples
+        --------
+        >>> from numpy import array
+        >>> from scipy.sparse import coo_array
+        >>> row  = array([0, 0, 1, 3, 1, 0, 0])
+        >>> col  = array([0, 2, 1, 3, 1, 0, 0])
+        >>> data = array([1, 1, 1, 1, 1, 1, 1])
+        >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsr()
+        >>> A.toarray()
+        array([[3, 0, 1, 0],
+               [0, 2, 0, 0],
+               [0, 0, 0, 0],
+               [0, 0, 0, 1]])
+
+        """
+        if self.ndim > 2:
+            raise ValueError(f'Cannot convert. CSR must be 1D or 2D. Got {self.ndim}D')
+        if self.nnz == 0:
+            return self._csr_container(self.shape, dtype=self.dtype)
+        else:
+            from ._csr import csr_array
+            arrays = self._coo_to_compressed(csr_array._swap, copy=copy)
+            indptr, indices, data, shape = arrays
+
+            x = self._csr_container((data, indices, indptr), shape=self.shape)
+            if not self.has_canonical_format:
+                x.sum_duplicates()
+            return x
+
+    def _coo_to_compressed(self, swap, copy=False):
+        """convert (shape, coords, data) to (indptr, indices, data, shape)"""
+        M, N = swap(self._shape_as_2d)
+        # convert idx_dtype intc to int32 for pythran.
+        # tested in scipy/optimize/tests/test__numdiff.py::test_group_columns
+        idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.nnz, N))
+
+        if self.ndim == 1:
+            indices = self.coords[0].copy() if copy else self.coords[0]
+            nnz = len(indices)
+            indptr = np.array([0, nnz], dtype=idx_dtype)
+            data = self.data.copy() if copy else self.data
+            return indptr, indices, data, self.shape
+
+        # ndim == 2
+        major, minor = swap(self.coords)
+        nnz = len(major)
+        major = major.astype(idx_dtype, copy=False)
+        minor = minor.astype(idx_dtype, copy=False)
+
+        indptr = np.empty(M + 1, dtype=idx_dtype)
+        indices = np.empty_like(minor, dtype=idx_dtype)
+        data = np.empty_like(self.data, dtype=self.dtype)
+
+        coo_tocsr(M, N, nnz, major, minor, self.data, indptr, indices, data)
+        return indptr, indices, data, self.shape
+
+    def tocoo(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    tocoo.__doc__ = _spbase.tocoo.__doc__
+
+    def todia(self, copy=False):
+        if self.ndim != 2:
+            raise ValueError(f'Cannot convert. DIA format must be 2D. Got {self.ndim}D')
+        self.sum_duplicates()
+        ks = self.col - self.row  # the diagonal for each nonzero
+        diags, diag_idx = np.unique(ks, return_inverse=True)
+
+        if len(diags) > 100:
+            # probably undesired, should todia() have a maxdiags parameter?
+            warn(f"Constructing a DIA matrix with {len(diags)} diagonals "
+                 "is inefficient",
+                 SparseEfficiencyWarning, stacklevel=2)
+
+        #initialize and fill in data array
+        if self.data.size == 0:
+            data = np.zeros((0, 0), dtype=self.dtype)
+        else:
+            data = np.zeros((len(diags), self.col.max()+1), dtype=self.dtype)
+            data[diag_idx, self.col] = self.data
+
+        return self._dia_container((data, diags), shape=self.shape)
+
+    todia.__doc__ = _spbase.todia.__doc__
+
+    def todok(self, copy=False):
+        if self.ndim > 2:
+            raise ValueError(f'Cannot convert. DOK must be 1D or 2D. Got {self.ndim}D')
+        self.sum_duplicates()
+        dok = self._dok_container(self.shape, dtype=self.dtype)
+        # ensure that 1d coordinates are not tuples
+        if self.ndim == 1:
+            coords = self.coords[0]
+        else:
+            coords = zip(*self.coords)
+
+        dok._dict = dict(zip(coords, self.data))
+        return dok
+
+    todok.__doc__ = _spbase.todok.__doc__
+
+    def diagonal(self, k=0):
+        if self.ndim != 2:
+            raise ValueError("diagonal requires two dimensions")
+        rows, cols = self.shape
+        if k <= -rows or k >= cols:
+            return np.empty(0, dtype=self.data.dtype)
+        diag = np.zeros(min(rows + min(k, 0), cols - max(k, 0)),
+                        dtype=self.dtype)
+        diag_mask = (self.row + k) == self.col
+
+        if self.has_canonical_format:
+            row = self.row[diag_mask]
+            data = self.data[diag_mask]
+        else:
+            inds = tuple(idx[diag_mask] for idx in self.coords)
+            (row, _), data = self._sum_duplicates(inds, self.data[diag_mask])
+        diag[row + min(k, 0)] = data
+
+        return diag
+
+    diagonal.__doc__ = _data_matrix.diagonal.__doc__
+
+    def _setdiag(self, values, k):
+        if self.ndim != 2:
+            raise ValueError("setting a diagonal requires two dimensions")
+        M, N = self.shape
+        if values.ndim and not len(values):
+            return
+        idx_dtype = self.row.dtype
+
+        # Determine which triples to keep and where to put the new ones.
+        full_keep = self.col - self.row != k
+        if k < 0:
+            max_index = min(M+k, N)
+            if values.ndim:
+                max_index = min(max_index, len(values))
+            keep = np.logical_or(full_keep, self.col >= max_index)
+            new_row = np.arange(-k, -k + max_index, dtype=idx_dtype)
+            new_col = np.arange(max_index, dtype=idx_dtype)
+        else:
+            max_index = min(M, N-k)
+            if values.ndim:
+                max_index = min(max_index, len(values))
+            keep = np.logical_or(full_keep, self.row >= max_index)
+            new_row = np.arange(max_index, dtype=idx_dtype)
+            new_col = np.arange(k, k + max_index, dtype=idx_dtype)
+
+        # Define the array of data consisting of the entries to be added.
+        if values.ndim:
+            new_data = values[:max_index]
+        else:
+            new_data = np.empty(max_index, dtype=self.dtype)
+            new_data[:] = values
+
+        # Update the internal structure.
+        self.coords = (np.concatenate((self.row[keep], new_row)),
+                       np.concatenate((self.col[keep], new_col)))
+        self.data = np.concatenate((self.data[keep], new_data))
+        self.has_canonical_format = False
+
+    # needed by _data_matrix
+    def _with_data(self, data, copy=True):
+        """Returns a matrix with the same sparsity structure as self,
+        but with different data. By default the index arrays are copied.
+        """
+        if copy:
+            coords = tuple(idx.copy() for idx in self.coords)
+        else:
+            coords = self.coords
+        return self.__class__((data, coords), shape=self.shape, dtype=data.dtype)
+
+    def sum_duplicates(self) -> None:
+        """Eliminate duplicate entries by adding them together
+
+        This is an *in place* operation
+        """
+        if self.has_canonical_format:
+            return
+        summed = self._sum_duplicates(self.coords, self.data)
+        self.coords, self.data = summed
+        self.has_canonical_format = True
+
+    def _sum_duplicates(self, coords, data):
+        # Assumes coords not in canonical format.
+        if len(data) == 0:
+            return coords, data
+        # Sort coords w.r.t. rows, then cols. This corresponds to C-order,
+        # which we rely on for argmin/argmax to return the first index in the
+        # same way that numpy does (in the case of ties).
+        order = np.lexsort(coords[::-1])
+        coords = tuple(idx[order] for idx in coords)
+        data = data[order]
+        unique_mask = np.logical_or.reduce([
+            idx[1:] != idx[:-1] for idx in coords
+        ])
+        unique_mask = np.append(True, unique_mask)
+        coords = tuple(idx[unique_mask] for idx in coords)
+        unique_inds, = np.nonzero(unique_mask)
+        data = np.add.reduceat(data, downcast_intp_index(unique_inds), dtype=self.dtype)
+        return coords, data
+
+    def eliminate_zeros(self):
+        """Remove zero entries from the array/matrix
+
+        This is an *in place* operation
+        """
+        mask = self.data != 0
+        self.data = self.data[mask]
+        self.coords = tuple(idx[mask] for idx in self.coords)
+
+    #######################
+    # Arithmetic handlers #
+    #######################
+
+    def _add_dense(self, other):
+        if other.shape != self.shape:
+            raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
+        dtype = upcast_char(self.dtype.char, other.dtype.char)
+        result = np.array(other, dtype=dtype, copy=True)
+        fortran = int(result.flags.f_contiguous)
+        if self.ndim == 1:
+            coo_todense_nd(np.array([1]), self.nnz, self.ndim,
+                           self.coords[0], self.data, result.ravel('A'), fortran)
+        elif self.ndim == 2:
+            M, N = self._shape_as_2d
+            coo_todense(M, N, self.nnz, self.row, self.col, self.data,
+                        result.ravel('A'), fortran)
+        else:
+            if fortran:
+                strides = np.append(1, np.cumprod(self.shape[:-1]))
+            else:
+                strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1)
+            coords = np.concatenate(self.coords)
+            coo_todense_nd(strides, self.nnz, self.ndim,
+                           coords, self.data, result.ravel('A'), fortran)
+        return self._container(result, copy=False)
+
+
+    def _add_sparse(self, other):
+        if self.ndim < 3:
+            return self.tocsr()._add_sparse(other)
+
+        if other.shape != self.shape:
+            raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
+        other = self.__class__(other)
+        new_data = np.concatenate((self.data, other.data))
+        new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1))
+        A = self.__class__((new_data, new_coords), shape=self.shape)
+        return A
+
+
+    def _sub_sparse(self, other):
+        if self.ndim < 3:
+            return self.tocsr()._sub_sparse(other)
+
+        if other.shape != self.shape:
+            raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})')
+        other = self.__class__(other)
+        new_data = np.concatenate((self.data, -other.data))
+        new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1))
+        A = coo_array((new_data, new_coords), shape=self.shape)
+        return A
+
+
+    def _matmul_vector(self, other):
+        if self.ndim > 2:
+            result = np.zeros(math.prod(self.shape[:-1]),
+                              dtype=upcast_char(self.dtype.char, other.dtype.char))
+            shape = np.array(self.shape)
+            strides = np.append(np.cumprod(shape[:-1][::-1])[::-1][1:], 1)
+            coords = np.concatenate(self.coords)
+            coo_matvec_nd(self.nnz, len(self.shape), strides, coords, self.data,
+                          other, result)
+
+            result = result.reshape(self.shape[:-1])
+            return result
+
+        # self.ndim <= 2
+        result_shape = self.shape[0] if self.ndim > 1 else 1
+        result = np.zeros(result_shape,
+                          dtype=upcast_char(self.dtype.char, other.dtype.char))
+        if self.ndim == 2:
+            col = self.col
+            row = self.row
+        elif self.ndim == 1:
+            col = self.coords[0]
+            row = np.zeros_like(col)
+        else:
+            raise NotImplementedError(
+                f"coo_matvec not implemented for ndim={self.ndim}")
+
+        coo_matvec(self.nnz, row, col, self.data, other, result)
+        # Array semantics return a scalar here, not a single-element array.
+        if isinstance(self, sparray) and result_shape == 1:
+            return result[0]
+        return result
+
+
+    def _rmatmul_dispatch(self, other):
+        if isscalarlike(other):
+            return self._mul_scalar(other)
+        else:
+            # Don't use asarray unless we have to
+            try:
+                o_ndim = other.ndim
+            except AttributeError:
+                other = np.asarray(other)
+                o_ndim = other.ndim
+            perm = tuple(range(o_ndim)[:-2]) + tuple(range(o_ndim)[-2:][::-1])
+            tr = other.transpose(perm)
+
+            s_ndim = self.ndim
+            perm = tuple(range(s_ndim)[:-2]) + tuple(range(s_ndim)[-2:][::-1])
+            ret = self.transpose(perm)._matmul_dispatch(tr)
+            if ret is NotImplemented:
+                return NotImplemented
+
+            if s_ndim == 1 or o_ndim == 1:
+                perm = range(ret.ndim)
+            else:
+                perm = tuple(range(ret.ndim)[:-2]) + tuple(range(ret.ndim)[-2:][::-1])
+            return ret.transpose(perm)
+
+
+    def _matmul_dispatch(self, other):
+        if isscalarlike(other):
+            return self.multiply(other)
+
+        if not (issparse(other) or isdense(other)):
+            # If it's a list or whatever, treat it like an array
+            other_a = np.asanyarray(other)
+
+            if other_a.ndim == 0 and other_a.dtype == np.object_:
+                # Not interpretable as an array; return NotImplemented so that
+                # other's __rmatmul__ can kick in if that's implemented.
+                return NotImplemented
+
+            try:
+                other.shape
+            except AttributeError:
+                other = other_a
+
+        if self.ndim < 3 and other.ndim < 3:
+            return _spbase._matmul_dispatch(self, other)
+
+        N = self.shape[-1]
+        err_prefix = "matmul: dimension mismatch with signature"
+        if other.__class__ is np.ndarray:
+            if other.shape == (N,):
+                return self._matmul_vector(other)
+            if other.shape == (N, 1):
+                result = self._matmul_vector(other.ravel())
+                return result.reshape(*self.shape[:-1], 1)
+            if other.ndim == 1:
+                msg = f"{err_prefix} (n,k={N}),(k={other.shape[0]},)->(n,)"
+                raise ValueError(msg)
+            if other.shape[-2] == N:
+                # check for batch dimensions compatibility
+                batch_shape_A = self.shape[:-2]
+                batch_shape_B = other.shape[:-2]
+                if batch_shape_A != batch_shape_B:
+                    try:
+                        # This will raise an error if the shapes are not broadcastable
+                        np.broadcast_shapes(batch_shape_A, batch_shape_B)
+                    except ValueError:
+                        raise ValueError("Batch dimensions are not broadcastable")
+
+                return self._matmul_multivector(other)
+            else:
+                raise ValueError(
+                    f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)"
+                )
+
+
+        if isscalarlike(other):
+            # scalar value
+            return self._mul_scalar(other)
+
+        if issparse(other):
+            self_is_1d = self.ndim == 1
+            other_is_1d = other.ndim == 1
+
+            # reshape to 2-D if self or other is 1-D
+            if self_is_1d:
+                self = self.reshape(self._shape_as_2d) # prepend 1 to shape
+
+            if other_is_1d:
+                other = other.reshape((other.shape[0], 1)) # append 1 to shape
+
+            # Check if the inner dimensions match for matrix multiplication
+            if N != other.shape[-2]:
+                raise ValueError(
+                    f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)"
+                )
+
+            # If A or B has more than 2 dimensions, check for
+            # batch dimensions compatibility
+            if self.ndim > 2 or other.ndim > 2:
+                batch_shape_A = self.shape[:-2]
+                batch_shape_B = other.shape[:-2]
+                if batch_shape_A != batch_shape_B:
+                    try:
+                        # This will raise an error if the shapes are not broadcastable
+                        np.broadcast_shapes(batch_shape_A, batch_shape_B)
+                    except ValueError:
+                        raise ValueError("Batch dimensions are not broadcastable")
+
+            result = self._matmul_sparse(other)
+
+            # reshape back if a or b were originally 1-D
+            if self_is_1d:
+                # if self was originally 1-D, reshape result accordingly
+                result = result.reshape(tuple(result.shape[:-2]) +
+                                        tuple(result.shape[-1:]))
+            if other_is_1d:
+                result = result.reshape(result.shape[:-1])
+            return result
+
+
+    def _matmul_multivector(self, other):
+        result_dtype = upcast_char(self.dtype.char, other.dtype.char)
+        if self.ndim >= 3 or other.ndim >= 3:
+            # if self has shape (N,), reshape to (1,N)
+            if self.ndim == 1:
+                result = self.reshape(1, self.shape[0])._matmul_multivector(other)
+                return result.reshape(tuple(other.shape[:-2]) + tuple(other.shape[-1:]))
+
+            broadcast_shape = np.broadcast_shapes(self.shape[:-2], other.shape[:-2])
+            self_shape = broadcast_shape + self.shape[-2:]
+            other_shape = broadcast_shape + other.shape[-2:]
+
+            self = self._broadcast_to(self_shape)
+            other = np.broadcast_to(other, other_shape)
+            result_shape = broadcast_shape + self.shape[-2:-1] + other.shape[-1:]
+            result = np.zeros(result_shape, dtype=result_dtype)
+            coo_matmat_dense_nd(self.nnz, len(self.shape), other.shape[-1],
+                                np.array(other_shape), np.array(result_shape),
+                                np.concatenate(self.coords),
+                                self.data, other.ravel('C'), result)
+            return result
+
+        if self.ndim == 2:
+            result_shape = (self.shape[0], other.shape[1])
+            col = self.col
+            row = self.row
+        elif self.ndim == 1:
+            result_shape = (other.shape[1],)
+            col = self.coords[0]
+            row = np.zeros_like(col)
+        result = np.zeros(result_shape, dtype=result_dtype)
+        coo_matmat_dense(self.nnz, other.shape[-1], row, col,
+                         self.data, other.ravel('C'), result)
+        return result.view(type=type(other))
+
+
+    def dot(self, other):
+        """Return the dot product of two arrays.
+
+        Strictly speaking a dot product involves two vectors.
+        But in the sense that an array with ndim >= 1 is a collection
+        of vectors, the function computes the collection of dot products
+        between each vector in the first array with each vector in the
+        second array. The axis upon which the sum of products is performed
+        is the last axis of the first array and the second to last axis of
+        the second array. If the second array is 1-D, the last axis is used.
+
+        Thus, if both arrays are 1-D, the inner product is returned.
+        If both are 2-D, we have matrix multiplication. If `other` is 1-D,
+        the sum product is taken along the last axis of each array. If
+        `other` is N-D for N>=2, the sum product is over the last axis of
+        the first array and the second-to-last axis of the second array.
+
+        Parameters
+        ----------
+        other : array_like (dense or sparse)
+            Second array
+
+        Returns
+        -------
+        output : array (sparse or dense)
+            The dot product of this array with `other`.
+            It will be dense/sparse if `other` is dense/sparse.
+
+        Examples
+        --------
+
+        >>> import numpy as np
+        >>> from scipy.sparse import coo_array
+        >>> A = coo_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+        >>> v = np.array([1, 0, -1])
+        >>> A.dot(v)
+        array([ 1, -3, -1], dtype=int64)
+
+        For 2-D arrays it is the matrix product:
+
+        >>> A = coo_array([[1, 0], [0, 1]])
+        >>> B = coo_array([[4, 1], [2, 2]])
+        >>> A.dot(B).toarray()
+        array([[4, 1],
+               [2, 2]])
+
+        For 3-D arrays the shape extends unused axes by other unused axes.
+
+        >>> A = coo_array(np.arange(3*4*5*6)).reshape((3,4,5,6))
+        >>> B = coo_array(np.arange(3*4*5*6)).reshape((5,4,6,3))
+        >>> A.dot(B).shape
+        (3, 4, 5, 5, 4, 3)
+        """
+        if not (issparse(other) or isdense(other) or isscalarlike(other)):
+            # If it's a list or whatever, treat it like an array
+            o_array = np.asanyarray(other)
+
+            if o_array.ndim == 0 and o_array.dtype == np.object_:
+                raise TypeError(f"dot argument not supported type: '{type(other)}'")
+            try:
+                other.shape
+            except AttributeError:
+                other = o_array
+
+        if self.ndim < 3 and (np.isscalar(other) or other.ndim<3):
+            return _spbase.dot(self, other)
+        # Handle scalar multiplication
+        if np.isscalar(other):
+            return self * other
+        if isdense(other):
+            return self._dense_dot(other)
+        elif other.format != "coo":
+            raise TypeError("input must be a COO matrix/array")
+        elif self.ndim == 1 and other.ndim == 1:
+            # Handle inner product of vectors (1-D arrays)
+            if self.shape[0] != other.shape[0]:
+                raise ValueError(f"shapes {self.shape} and {other.shape}"
+                                 " are not aligned for inner product")
+            return self @ other
+        elif self.ndim == 2 and other.ndim == 2:
+            # Handle matrix multiplication (2-D arrays)
+            if self.shape[1] != other.shape[0]:
+                raise ValueError(f"shapes {self.shape} and {other.shape}"
+                                 " are not aligned for matmul")
+            return self @ other
+        else:
+            return self._sparse_dot(other)
+
+
+    def _sparse_dot(self, other):
+        self_is_1d = self.ndim == 1
+        other_is_1d = other.ndim == 1
+
+        # reshape to 2-D if self or other is 1-D
+        if self_is_1d:
+            self = self.reshape(self._shape_as_2d)  # prepend 1 to shape
+        if other_is_1d:
+            other = other.reshape((other.shape[0], 1))  # append 1 to shape
+
+        if self.shape[-1] != other.shape[-2]:
+                raise ValueError(f"shapes {self.shape} and {other.shape}"
+                                 " are not aligned for n-D dot")
+
+        # Prepare the tensors for dot operation
+        # Ravel non-reduced axes coordinates
+        self_raveled_coords = _ravel_non_reduced_axes(self.coords,
+                                                      self.shape, [self.ndim-1])
+        other_raveled_coords = _ravel_non_reduced_axes(other.coords,
+                                                       other.shape, [other.ndim-2])
+
+        # Get the shape of the non-reduced axes
+        self_nonreduced_shape = self.shape[:-1]
+        other_nonreduced_shape = other.shape[:-2] + other.shape[-1:]
+
+        # Create 2D coords arrays
+        ravel_coords_shape_self = (math.prod(self_nonreduced_shape), self.shape[-1])
+        ravel_coords_shape_other = (other.shape[-2], math.prod(other_nonreduced_shape))
+
+        self_2d_coords = (self_raveled_coords, self.coords[-1])
+        other_2d_coords = (other.coords[-2], other_raveled_coords)
+
+        self_2d = coo_array((self.data, self_2d_coords), ravel_coords_shape_self)
+        other_2d = coo_array((other.data, other_2d_coords), ravel_coords_shape_other)
+
+        prod = (self_2d @ other_2d).tocoo() # routes via 2-D CSR
+
+        # Combine the shapes of the non-reduced axes
+        combined_shape = self_nonreduced_shape + other_nonreduced_shape
+
+        # Unravel the 2D coordinates to get multi-dimensional coordinates
+        shapes = (self_nonreduced_shape, other_nonreduced_shape)
+        prod_coords = []
+        for c, s in zip(prod.coords, shapes):
+            prod_coords.extend(np.unravel_index(c, s))
+
+        prod_arr = coo_array((prod.data, prod_coords), combined_shape)
+
+        # reshape back if a or b were originally 1-D
+        # TODO: Move this logic before computation of prod_coords for efficiency
+        if self_is_1d:
+            prod_arr = prod_arr.reshape(combined_shape[1:])
+        if other_is_1d:
+            prod_arr = prod_arr.reshape(combined_shape[:-1])
+
+        return prod_arr
+
+    def _dense_dot(self, other):
+        self_is_1d = self.ndim == 1
+        other_is_1d = other.ndim == 1
+
+        # reshape to 2-D if self or other is 1-D
+        if self_is_1d:
+            self = self.reshape(self._shape_as_2d)  # prepend 1 to shape
+        if other_is_1d:
+            other = other.reshape((other.shape[0], 1))  # append 1 to shape
+
+        if self.shape[-1] != other.shape[-2]:
+                raise ValueError(f"shapes {self.shape} and {other.shape}"
+                                 " are not aligned for n-D dot")
+
+        new_shape_self = (
+            self.shape[:-1] + (1,) * (len(other.shape) - 1) + self.shape[-1:]
+        )
+        new_shape_other = (1,) * (len(self.shape) - 1) + other.shape
+
+        result_shape = self.shape[:-1] + other.shape[:-2] + other.shape[-1:]
+        result = self.reshape(new_shape_self) @ other.reshape(new_shape_other)
+        prod_arr = result.reshape(result_shape)
+
+        # reshape back if a or b were originally 1-D
+        if self_is_1d:
+            prod_arr = prod_arr.reshape(result_shape[1:])
+        if other_is_1d:
+            prod_arr = prod_arr.reshape(result_shape[:-1])
+
+        return prod_arr
+
+    def tensordot(self, other, axes=2):
+        """Return the tensordot product with another array along the given axes.
+
+        The tensordot differs from dot and matmul in that any axis can be
+        chosen for each of the first and second array and the sum of the
+        products is computed just like for matrix multiplication, only not
+        just for the rows of the first times the columns of the second. It
+        takes the dot product of the collection of vectors along the specified
+        axes.  Here we can even take the sum of the products along two or even
+        more axes if desired. So, tensordot is a dot product computation
+        applied to arrays of any dimension >= 1. It is like matmul but over
+        arbitrary axes for each matrix.
+
+        Given two tensors, `a` and `b`, and the desired axes specified as a
+        2-tuple/list/array containing two sequences of axis numbers,
+        ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements
+        (components) over the axes specified by ``a_axes`` and ``b_axes``.
+        The `axes` input can be a single non-negative integer, ``N``;
+        if it is, then the last ``N`` dimensions of `a` and the first
+        ``N`` dimensions of `b` are summed over.
+
+        Parameters
+        ----------
+        a, b : array_like
+            Tensors to "dot".
+
+        axes : int or (2,) array_like
+            * integer_like
+              If an int N, sum over the last N axes of `a` and the first N axes
+              of `b` in order. The sizes of the corresponding axes must match.
+            * (2,) array_like
+              A 2-tuple of sequences of axes to be summed over, the first applying
+              to `a`, the second to `b`. The sequences must be the same length.
+              The shape of the corresponding axes must match between `a` and `b`.
+
+        Returns
+        -------
+        output : coo_array
+            The tensor dot product of this array with `other`.
+            It will be dense/sparse if `other` is dense/sparse.
+
+        See Also
+        --------
+        dot
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> import scipy.sparse
+        >>> A = scipy.sparse.coo_array([[[2, 3], [0, 0]], [[0, 1], [0, 5]]])
+        >>> A.shape
+        (2, 2, 2)
+
+        Integer axes N are shorthand for (range(-N, 0), range(0, N)):
+
+        >>> A.tensordot(A, axes=1).toarray()
+        array([[[[ 4,  9],
+                 [ 0, 15]],
+        
+                [[ 0,  0],
+                 [ 0,  0]]],
+        
+        
+               [[[ 0,  1],
+                 [ 0,  5]],
+        
+                [[ 0,  5],
+                 [ 0, 25]]]])
+        >>> A.tensordot(A, axes=2).toarray()
+        array([[ 4,  6],
+               [ 0, 25]])
+        >>> A.tensordot(A, axes=3)
+        array(39)
+
+        Using tuple for axes:
+
+        >>> a = scipy.sparse.coo_array(np.arange(60).reshape(3,4,5))
+        >>> b = np.arange(24).reshape(4,3,2)
+        >>> c = a.tensordot(b, axes=([1,0],[0,1]))
+        >>> c.shape
+        (5, 2)
+        >>> c
+        array([[4400, 4730],
+               [4532, 4874],
+               [4664, 5018],
+               [4796, 5162],
+               [4928, 5306]])
+
+        """
+        if not isdense(other) and not issparse(other):
+            # If it's a list or whatever, treat it like an array
+            other_array = np.asanyarray(other)
+
+            if other_array.ndim == 0 and other_array.dtype == np.object_:
+                raise TypeError(f"tensordot arg not supported type: '{type(other)}'")
+            try:
+                other.shape
+            except AttributeError:
+                other = other_array
+
+        axes_self, axes_other = _process_axes(self.ndim, other.ndim, axes)
+
+        # Check for shape compatibility along specified axes
+        if any(self.shape[ax] != other.shape[bx]
+               for ax, bx in zip(axes_self, axes_other)):
+            raise ValueError("sizes of the corresponding axes must match")
+
+        if isdense(other):
+            return self._dense_tensordot(other, axes_self, axes_other)
+        else:
+            return self._sparse_tensordot(other, axes_self, axes_other)
+
+
+    def _sparse_tensordot(self, other, axes_self, axes_other):
+        ndim_self = len(self.shape)
+        ndim_other = len(other.shape)
+
+        # Prepare the tensors for tensordot operation
+        # Ravel non-reduced axes coordinates
+        self_non_red_coords = _ravel_non_reduced_axes(self.coords, self.shape,
+                                                      axes_self)
+        self_reduced_coords = np.ravel_multi_index(
+            [self.coords[ax] for ax in axes_self], [self.shape[ax] for ax in axes_self])
+        other_non_red_coords = _ravel_non_reduced_axes(other.coords, other.shape,
+                                                       axes_other)
+        other_reduced_coords = np.ravel_multi_index(
+            [other.coords[a] for a in axes_other], [other.shape[a] for a in axes_other]
+        )
+        # Get the shape of the non-reduced axes
+        self_nonreduced_shape = tuple(self.shape[ax] for ax in range(ndim_self)
+                              if ax not in axes_self)
+        other_nonreduced_shape = tuple(other.shape[ax] for ax in range(ndim_other)
+                               if ax not in axes_other)
+
+        # Create 2D coords arrays
+        ravel_coords_shape_self = (math.prod(self_nonreduced_shape),
+                                math.prod([self.shape[ax] for ax in axes_self]))
+        ravel_coords_shape_other = (math.prod([other.shape[ax] for ax in axes_other]),
+                                    math.prod(other_nonreduced_shape))
+
+        self_2d_coords = (self_non_red_coords, self_reduced_coords)
+        other_2d_coords = (other_reduced_coords, other_non_red_coords)
+
+        self_2d = coo_array((self.data, self_2d_coords), ravel_coords_shape_self)
+        other_2d = coo_array((other.data, other_2d_coords), ravel_coords_shape_other)
+
+        # Perform matrix multiplication (routed via 2-D CSR)
+        prod = (self_2d @ other_2d).tocoo()
+
+        # Combine the shapes of the non-contracted axes
+        combined_shape = self_nonreduced_shape + other_nonreduced_shape
+
+        # Unravel the 2D coordinates to get multi-dimensional coordinates
+        coords = []
+        for c, s in zip(prod.coords, (self_nonreduced_shape, other_nonreduced_shape)):
+            if s:
+                coords.extend(np.unravel_index(c, s))
+
+        if coords == []:  # if result is scalar
+            return sum(prod.data)
+
+        # Construct the resulting COO array with combined coordinates and shape
+        return coo_array((prod.data, coords), shape=combined_shape)
+
+
+    def _dense_tensordot(self, other, axes_self, axes_other):
+        ndim_self = len(self.shape)
+        ndim_other = len(other.shape)
+
+        non_reduced_axes_self = [ax for ax in range(ndim_self) if ax not in axes_self]
+        reduced_shape_self = [self.shape[s] for s in axes_self]
+        non_reduced_shape_self = [self.shape[s] for s in non_reduced_axes_self]
+
+        non_reduced_axes_other = [ax for ax in range(ndim_other)
+                                  if ax not in axes_other]
+        reduced_shape_other = [other.shape[s] for s in axes_other]
+        non_reduced_shape_other = [other.shape[s] for s in non_reduced_axes_other]
+
+        permute_self = non_reduced_axes_self + axes_self
+        permute_other = (
+            non_reduced_axes_other[:-1] + axes_other + non_reduced_axes_other[-1:]
+        )
+        self = self.transpose(permute_self)
+        other = np.transpose(other, permute_other)
+
+        reshape_self = (*non_reduced_shape_self, math.prod(reduced_shape_self))
+        reshape_other = (*non_reduced_shape_other[:-1], math.prod(reduced_shape_other),
+                        *non_reduced_shape_other[-1:])
+
+        return self.reshape(reshape_self).dot(other.reshape(reshape_other))
+
+
+    def _matmul_sparse(self, other):
+        """
+        Perform sparse-sparse matrix multiplication for two n-D COO arrays.
+        The method converts input n-D arrays to 2-D block array format,
+        uses csr_matmat to multiply them, and then converts the
+        result back to n-D COO array.
+
+        Parameters:
+        self (COO): The first n-D sparse array in COO format.
+        other (COO): The second n-D sparse array in COO format.
+
+        Returns:
+        prod (COO): The resulting n-D sparse array after multiplication.
+        """
+        if self.ndim < 3 and other.ndim < 3:
+            return _spbase._matmul_sparse(self, other)
+
+        # Get the shapes of self and other
+        self_shape = self.shape
+        other_shape = other.shape
+
+        # Determine the new shape to broadcast self and other
+        broadcast_shape = np.broadcast_shapes(self_shape[:-2], other_shape[:-2])
+        self_new_shape = tuple(broadcast_shape) + self_shape[-2:]
+        other_new_shape = tuple(broadcast_shape) + other_shape[-2:]
+
+        self_broadcasted = self._broadcast_to(self_new_shape)
+        other_broadcasted = other._broadcast_to(other_new_shape)
+
+        # Convert n-D COO arrays to 2-D block diagonal arrays
+        self_block_diag = _block_diag(self_broadcasted)
+        other_block_diag = _block_diag(other_broadcasted)
+
+        # Use csr_matmat to perform sparse matrix multiplication
+        prod_block_diag = (self_block_diag @ other_block_diag).tocoo()
+
+        # Convert the 2-D block diagonal array back to n-D
+        return _extract_block_diag(
+            prod_block_diag,
+            shape=(*broadcast_shape, self.shape[-2], other.shape[-1]),
+        )
+
+
+    def _broadcast_to(self, new_shape, copy=False):
+        if self.shape == new_shape:
+            return self.copy() if copy else self
+
+        old_shape = self.shape
+
+        # Check if the new shape is compatible for broadcasting
+        if len(new_shape) < len(old_shape):
+            raise ValueError("New shape must have at least as many dimensions"
+                             " as the current shape")
+
+        # Add leading ones to shape to ensure same length as `new_shape`
+        shape = (1,) * (len(new_shape) - len(old_shape)) + tuple(old_shape)
+
+        # Ensure the old shape can be broadcast to the new shape
+        if any((o != 1 and o != n) for o, n in zip(shape, new_shape)):
+            raise ValueError(f"current shape {old_shape} cannot be "
+                             "broadcast to new shape {new_shape}")
+
+        # Reshape the COO array to match the new dimensions
+        self = self.reshape(shape)
+
+        idx_dtype = get_index_dtype(self.coords, maxval=max(new_shape))
+        coords = self.coords
+        new_data = self.data
+        new_coords = coords[-1:]  # Copy last coordinate to start
+        cum_repeat = 1 # Cumulative repeat factor for broadcasting
+
+        if shape[-1] != new_shape[-1]: # broadcasting the n-th (col) dimension
+            repeat_count = new_shape[-1]
+            cum_repeat *= repeat_count
+            new_data = np.tile(new_data, repeat_count)
+            new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), self.nnz)
+            new_coords = (new_dim,)
+
+        for i in range(-2, -(len(shape)+1), -1):
+            if shape[i] != new_shape[i]:
+                repeat_count = new_shape[i] # number of times to repeat data, coords
+                cum_repeat *= repeat_count # update cumulative repeat factor
+                nnz = len(new_data) # Number of non-zero elements so far
+
+                # Tile data and coordinates to match the new repeat count
+                new_data = np.tile(new_data, repeat_count)
+                new_coords = tuple(np.tile(new_coords[i+1:], repeat_count))
+
+                # Create new dimensions and stack them
+                new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), nnz)
+                new_coords = (new_dim,) + new_coords
+            else:
+                # If no broadcasting needed, tile the coordinates
+                new_dim = np.tile(coords[i], cum_repeat)
+                new_coords = (new_dim,) + new_coords
+
+        return coo_array((new_data, new_coords), new_shape)
+
+
+def _block_diag(self):
+    """
+    Converts an N-D COO array into a 2-D COO array in block diagonal form.
+
+    Parameters:
+    self (coo_array): An N-Dimensional COO sparse array.
+
+    Returns:
+    coo_array: A 2-Dimensional COO sparse array in block diagonal form.
+    """
+    if self.ndim<2:
+        raise ValueError("array must have atleast dim=2")
+    num_blocks = math.prod(self.shape[:-2])
+    n_col = self.shape[-1]
+    n_row = self.shape[-2]
+    res_arr = self.reshape((num_blocks, n_row, n_col))
+    new_coords = (
+        res_arr.coords[1] + res_arr.coords[0] * res_arr.shape[1],
+        res_arr.coords[2] + res_arr.coords[0] * res_arr.shape[2],
+    )
+
+    new_shape = (num_blocks * n_row, num_blocks * n_col)
+    return coo_array((self.data, tuple(new_coords)), shape=new_shape)
+
+
+def _extract_block_diag(self, shape):
+    n_row, n_col = shape[-2], shape[-1]
+
+    # Extract data and coordinates from the block diagonal COO array
+    data = self.data
+    row, col = self.row, self.col
+
+    # Initialize new coordinates array
+    new_coords = np.empty((len(shape), self.nnz), dtype=int)
+
+    # Calculate within-block indices
+    new_coords[-2] = row % n_row
+    new_coords[-1] = col % n_col
+
+    # Calculate coordinates for higher dimensions
+    temp_block_idx = row // n_row
+    for i in range(len(shape) - 3, -1, -1):
+        size = shape[i]
+        new_coords[i] = temp_block_idx % size
+        temp_block_idx = temp_block_idx // size
+
+    # Create the new COO array with the original n-D shape
+    return coo_array((data, tuple(new_coords)), shape=shape)
+
+
+def _process_axes(ndim_a, ndim_b, axes):
+    if isinstance(axes, int):
+        if axes < 1 or axes > min(ndim_a, ndim_b):
+            raise ValueError("axes integer is out of bounds for input arrays")
+        axes_a = list(range(ndim_a - axes, ndim_a))
+        axes_b = list(range(axes))
+    elif isinstance(axes, (tuple, list)):
+        if len(axes) != 2:
+            raise ValueError("axes must be a tuple/list of length 2")
+        axes_a, axes_b = axes
+        if len(axes_a) != len(axes_b):
+            raise ValueError("axes lists/tuples must be of the same length")
+        if any(ax >= ndim_a or ax < -ndim_a for ax in axes_a) or \
+           any(bx >= ndim_b or bx < -ndim_b for bx in axes_b):
+            raise ValueError("axes indices are out of bounds for input arrays")
+    else:
+        raise TypeError("axes must be an integer or a tuple/list of integers")
+
+    axes_a = [axis + ndim_a if axis < 0 else axis for axis in axes_a]
+    axes_b = [axis + ndim_b if axis < 0 else axis for axis in axes_b]
+    return axes_a, axes_b
+
+
+def _ravel_non_reduced_axes(coords, shape, axes):
+    ndim = len(shape)
+    non_reduced_axes = [ax for ax in range(ndim) if ax not in axes]
+
+    if not non_reduced_axes:
+        # Return an array with one row
+        return np.zeros_like(coords[0])
+
+    # Extract the shape of the non-reduced axes
+    non_reduced_shape = [shape[ax] for ax in non_reduced_axes]
+
+    # Extract the coordinates of the non-reduced axes
+    non_reduced_coords = tuple(coords[idx] for idx in non_reduced_axes)
+
+    # Ravel the coordinates into 1D
+    return np.ravel_multi_index(non_reduced_coords, non_reduced_shape)
+
+
+def _ravel_coords(coords, shape, order='C'):
+    """Like np.ravel_multi_index, but avoids some overflow issues."""
+    if len(coords) == 1:
+        return coords[0]
+    # Handle overflow as in https://github.com/scipy/scipy/pull/9132
+    if len(coords) == 2:
+        nrows, ncols = shape
+        row, col = coords
+        if order == 'C':
+            maxval = (ncols * max(0, nrows - 1) + max(0, ncols - 1))
+            idx_dtype = get_index_dtype(maxval=maxval)
+            return np.multiply(ncols, row, dtype=idx_dtype) + col
+        elif order == 'F':
+            maxval = (nrows * max(0, ncols - 1) + max(0, nrows - 1))
+            idx_dtype = get_index_dtype(maxval=maxval)
+            return np.multiply(nrows, col, dtype=idx_dtype) + row
+        else:
+            raise ValueError("'order' must be 'C' or 'F'")
+    return np.ravel_multi_index(coords, shape, order=order)
+
+
+def isspmatrix_coo(x):
+    """Is `x` of coo_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a coo matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a coo matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import coo_array, coo_matrix, csr_matrix, isspmatrix_coo
+    >>> isspmatrix_coo(coo_matrix([[5]]))
+    True
+    >>> isspmatrix_coo(coo_array([[5]]))
+    False
+    >>> isspmatrix_coo(csr_matrix([[5]]))
+    False
+    """
+    return isinstance(x, coo_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class coo_array(_coo_base, sparray):
+    """
+    A sparse array in COOrdinate format.
+
+    Also known as the 'ijv' or 'triplet' format.
+
+    This can be instantiated in several ways:
+        coo_array(D)
+            where D is an ndarray
+
+        coo_array(S)
+            with another sparse array or matrix S (equivalent to S.tocoo())
+
+        coo_array(shape, [dtype])
+            to construct an empty sparse array with shape `shape`
+            dtype is optional, defaulting to dtype='d'.
+
+        coo_array((data, coords), [shape])
+            to construct from existing data and index arrays:
+                1. data[:]       the entries of the sparse array, in any order
+                2. coords[i][:]  the axis-i coordinates of the data entries
+
+            Where ``A[coords] = data``, and coords is a tuple of index arrays.
+            When shape is not specified, it is inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the sparse array
+    shape : tuple of integers
+        Shape of the sparse array
+    ndim : int
+        Number of dimensions of the sparse array
+    nnz
+    size
+    data
+        COO format data array of the sparse array
+    coords
+        COO format tuple of index arrays
+    has_canonical_format : bool
+        Whether the matrix has sorted coordinates and no duplicates
+    format
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the COO format
+        - facilitates fast conversion among sparse formats
+        - permits duplicate entries (see example)
+        - very fast conversion to and from CSR/CSC formats
+
+    Disadvantages of the COO format
+        - does not directly support:
+            + arithmetic operations
+            + slicing
+
+    Intended Usage
+        - COO is a fast format for constructing sparse arrays
+        - Once a COO array has been constructed, convert to CSR or
+          CSC format for fast arithmetic and matrix vector operations
+        - By default when converting to CSR or CSC format, duplicate (i,j)
+          entries will be summed together.  This facilitates efficient
+          construction of finite element matrices and the like. (see example)
+
+    Canonical format
+        - Entries and coordinates sorted by row, then column.
+        - There are no duplicate entries (i.e. duplicate (i,j) locations)
+        - Data arrays MAY have explicit zeros.
+
+    Examples
+    --------
+
+    >>> # Constructing an empty sparse array
+    >>> import numpy as np
+    >>> from scipy.sparse import coo_array
+    >>> coo_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> # Constructing a sparse array using ijv format
+    >>> row  = np.array([0, 3, 1, 0])
+    >>> col  = np.array([0, 3, 1, 2])
+    >>> data = np.array([4, 5, 7, 9])
+    >>> coo_array((data, (row, col)), shape=(4, 4)).toarray()
+    array([[4, 0, 9, 0],
+           [0, 7, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 5]])
+
+    >>> # Constructing a sparse array with duplicate coordinates
+    >>> row  = np.array([0, 0, 1, 3, 1, 0, 0])
+    >>> col  = np.array([0, 2, 1, 3, 1, 0, 0])
+    >>> data = np.array([1, 1, 1, 1, 1, 1, 1])
+    >>> coo = coo_array((data, (row, col)), shape=(4, 4))
+    >>> # Duplicate coordinates are maintained until implicitly or explicitly summed
+    >>> np.max(coo.data)
+    1
+    >>> coo.toarray()
+    array([[3, 0, 1, 0],
+           [0, 2, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 1]])
+
+    """
+
+
+class coo_matrix(spmatrix, _coo_base):
+    """
+    A sparse matrix in COOrdinate format.
+
+    Also known as the 'ijv' or 'triplet' format.
+
+    This can be instantiated in several ways:
+        coo_matrix(D)
+            where D is a 2-D ndarray
+
+        coo_matrix(S)
+            with another sparse array or matrix S (equivalent to S.tocoo())
+
+        coo_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        coo_matrix((data, (i, j)), [shape=(M, N)])
+            to construct from three arrays:
+                1. data[:]   the entries of the matrix, in any order
+                2. i[:]      the row indices of the matrix entries
+                3. j[:]      the column indices of the matrix entries
+
+            Where ``A[i[k], j[k]] = data[k]``.  When shape is not
+            specified, it is inferred from the index arrays
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        COO format data array of the matrix
+    row
+        COO format row index array of the matrix
+    col
+        COO format column index array of the matrix
+    has_canonical_format : bool
+        Whether the matrix has sorted indices and no duplicates
+    format
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the COO format
+        - facilitates fast conversion among sparse formats
+        - permits duplicate entries (see example)
+        - very fast conversion to and from CSR/CSC formats
+
+    Disadvantages of the COO format
+        - does not directly support:
+            + arithmetic operations
+            + slicing
+
+    Intended Usage
+        - COO is a fast format for constructing sparse matrices
+        - Once a COO matrix has been constructed, convert to CSR or
+          CSC format for fast arithmetic and matrix vector operations
+        - By default when converting to CSR or CSC format, duplicate (i,j)
+          entries will be summed together.  This facilitates efficient
+          construction of finite element matrices and the like. (see example)
+
+    Canonical format
+        - Entries and coordinates sorted by row, then column.
+        - There are no duplicate entries (i.e. duplicate (i,j) locations)
+        - Data arrays MAY have explicit zeros.
+
+    Examples
+    --------
+
+    >>> # Constructing an empty matrix
+    >>> import numpy as np
+    >>> from scipy.sparse import coo_matrix
+    >>> coo_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> # Constructing a matrix using ijv format
+    >>> row  = np.array([0, 3, 1, 0])
+    >>> col  = np.array([0, 3, 1, 2])
+    >>> data = np.array([4, 5, 7, 9])
+    >>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
+    array([[4, 0, 9, 0],
+           [0, 7, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 5]])
+
+    >>> # Constructing a matrix with duplicate coordinates
+    >>> row  = np.array([0, 0, 1, 3, 1, 0, 0])
+    >>> col  = np.array([0, 2, 1, 3, 1, 0, 0])
+    >>> data = np.array([1, 1, 1, 1, 1, 1, 1])
+    >>> coo = coo_matrix((data, (row, col)), shape=(4, 4))
+    >>> # Duplicate coordinates are maintained until implicitly or explicitly summed
+    >>> np.max(coo.data)
+    1
+    >>> coo.toarray()
+    array([[3, 0, 1, 0],
+           [0, 2, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 1]])
+
+    """
+
+    def __setstate__(self, state):
+        if 'coords' not in state:
+            # For retro-compatibility with the previous attributes
+            # storing nnz coordinates for 2D COO matrix.
+            state['coords'] = (state.pop('row'), state.pop('col'))
+        self.__dict__.update(state)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_csc.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a03f50f6a29c71a838e6a9c93d61c20114bb432
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_csc.py
@@ -0,0 +1,367 @@
+"""Compressed Sparse Column matrix format"""
+__docformat__ = "restructuredtext en"
+
+__all__ = ['csc_array', 'csc_matrix', 'isspmatrix_csc']
+
+
+import numpy as np
+
+from ._matrix import spmatrix
+from ._base import _spbase, sparray
+from ._sparsetools import csc_tocsr, expandptr
+from ._sputils import upcast
+
+from ._compressed import _cs_matrix
+
+
+class _csc_base(_cs_matrix):
+    _format = 'csc'
+
+    def transpose(self, axes=None, copy=False):
+        if axes is not None and axes != (1, 0):
+            raise ValueError("Sparse arrays/matrices do not support "
+                              "an 'axes' parameter because swapping "
+                              "dimensions is the only logical permutation.")
+
+        M, N = self.shape
+
+        return self._csr_container((self.data, self.indices,
+                                    self.indptr), (N, M), copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def __iter__(self):
+        yield from self.tocsr()
+
+    def tocsc(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def tocsr(self, copy=False):
+        M,N = self.shape
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+                                    maxval=max(self.nnz, N))
+        indptr = np.empty(M + 1, dtype=idx_dtype)
+        indices = np.empty(self.nnz, dtype=idx_dtype)
+        data = np.empty(self.nnz, dtype=upcast(self.dtype))
+
+        csc_tocsr(M, N,
+                  self.indptr.astype(idx_dtype),
+                  self.indices.astype(idx_dtype),
+                  self.data,
+                  indptr,
+                  indices,
+                  data)
+
+        A = self._csr_container(
+            (data, indices, indptr),
+            shape=self.shape, copy=False
+        )
+        A.has_sorted_indices = True
+        return A
+
+    tocsr.__doc__ = _spbase.tocsr.__doc__
+
+    def nonzero(self):
+        # CSC can't use _cs_matrix's .nonzero method because it
+        # returns the indices sorted for self transposed.
+
+        # Get row and col indices, from _cs_matrix.tocoo
+        major_dim, minor_dim = self._swap(self.shape)
+        minor_indices = self.indices
+        major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype)
+        expandptr(major_dim, self.indptr, major_indices)
+        row, col = self._swap((major_indices, minor_indices))
+
+        # Remove explicit zeros
+        nz_mask = self.data != 0
+        row = row[nz_mask]
+        col = col[nz_mask]
+
+        # Sort them to be in C-style order
+        ind = np.argsort(row, kind='mergesort')
+        row = row[ind]
+        col = col[ind]
+
+        return row, col
+
+    nonzero.__doc__ = _cs_matrix.nonzero.__doc__
+
+    def _getrow(self, i):
+        """Returns a copy of row i of the matrix, as a (1 x n)
+        CSR matrix (row vector).
+        """
+        M, N = self.shape
+        i = int(i)
+        if i < 0:
+            i += M
+        if i < 0 or i >= M:
+            raise IndexError('index (%d) out of range' % i)
+        return self._get_submatrix(minor=i).tocsr()
+
+    def _getcol(self, i):
+        """Returns a copy of column i of the matrix, as a (m x 1)
+        CSC matrix (column vector).
+        """
+        M, N = self.shape
+        i = int(i)
+        if i < 0:
+            i += N
+        if i < 0 or i >= N:
+            raise IndexError('index (%d) out of range' % i)
+        return self._get_submatrix(major=i, copy=True)
+
+    def _get_intXarray(self, row, col):
+        return self._major_index_fancy(col)._get_submatrix(minor=row)
+
+    def _get_intXslice(self, row, col):
+        if col.step in (1, None):
+            return self._get_submatrix(major=col, minor=row, copy=True)
+        return self._major_slice(col)._get_submatrix(minor=row)
+
+    def _get_sliceXint(self, row, col):
+        if row.step in (1, None):
+            return self._get_submatrix(major=col, minor=row, copy=True)
+        return self._get_submatrix(major=col)._minor_slice(row)
+
+    def _get_sliceXarray(self, row, col):
+        return self._major_index_fancy(col)._minor_slice(row)
+
+    def _get_arrayXint(self, row, col):
+        res = self._get_submatrix(major=col)._minor_index_fancy(row)
+        if row.ndim > 1:
+            return res.reshape(row.shape)
+        return res
+
+    def _get_arrayXslice(self, row, col):
+        return self._major_slice(col)._minor_index_fancy(row)
+
+    # these functions are used by the parent class (_cs_matrix)
+    # to remove redundancy between csc_array and csr_matrix
+    @staticmethod
+    def _swap(x):
+        """swap the members of x if this is a column-oriented matrix
+        """
+        return x[1], x[0]
+
+
+def isspmatrix_csc(x):
+    """Is `x` of csc_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a csc matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a csc matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import csc_array, csc_matrix, coo_matrix, isspmatrix_csc
+    >>> isspmatrix_csc(csc_matrix([[5]]))
+    True
+    >>> isspmatrix_csc(csc_array([[5]]))
+    False
+    >>> isspmatrix_csc(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, csc_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class csc_array(_csc_base, sparray):
+    """
+    Compressed Sparse Column array.
+
+    This can be instantiated in several ways:
+        csc_array(D)
+            where D is a 2-D ndarray
+
+        csc_array(S)
+            with another sparse array or matrix S (equivalent to S.tocsc())
+
+        csc_array((M, N), [dtype])
+            to construct an empty array with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        csc_array((data, (row_ind, col_ind)), [shape=(M, N)])
+            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+        csc_array((data, indices, indptr), [shape=(M, N)])
+            is the standard CSC representation where the row indices for
+            column i are stored in ``indices[indptr[i]:indptr[i+1]]``
+            and their corresponding values are stored in
+            ``data[indptr[i]:indptr[i+1]]``.  If the shape parameter is
+            not supplied, the array dimensions are inferred from
+            the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        CSC format data array of the array
+    indices
+        CSC format index array of the array
+    indptr
+        CSC format index pointer array of the array
+    has_sorted_indices
+    has_canonical_format
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the CSC format
+        - efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
+        - efficient column slicing
+        - fast matrix vector products (CSR, BSR may be faster)
+
+    Disadvantages of the CSC format
+      - slow row slicing operations (consider CSR)
+      - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+    Canonical format
+      - Within each column, indices are sorted by row.
+      - There are no duplicate entries.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> csc_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 2, 2, 0, 1, 2])
+    >>> col = np.array([0, 0, 1, 2, 2, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csc_array((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 4],
+           [0, 0, 5],
+           [2, 3, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csc_array((data, indices, indptr), shape=(3, 3)).toarray()
+    array([[1, 0, 4],
+           [0, 0, 5],
+           [2, 3, 6]])
+
+    """
+
+
+class csc_matrix(spmatrix, _csc_base):
+    """
+    Compressed Sparse Column matrix.
+
+    This can be instantiated in several ways:
+        csc_matrix(D)
+            where D is a 2-D ndarray
+
+        csc_matrix(S)
+            with another sparse array or matrix S (equivalent to S.tocsc())
+
+        csc_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
+            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+        csc_matrix((data, indices, indptr), [shape=(M, N)])
+            is the standard CSC representation where the row indices for
+            column i are stored in ``indices[indptr[i]:indptr[i+1]]``
+            and their corresponding values are stored in
+            ``data[indptr[i]:indptr[i+1]]``.  If the shape parameter is
+            not supplied, the matrix dimensions are inferred from
+            the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        CSC format data array of the matrix
+    indices
+        CSC format index array of the matrix
+    indptr
+        CSC format index pointer array of the matrix
+    has_sorted_indices
+    has_canonical_format
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the CSC format
+        - efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
+        - efficient column slicing
+        - fast matrix vector products (CSR, BSR may be faster)
+
+    Disadvantages of the CSC format
+      - slow row slicing operations (consider CSR)
+      - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+    Canonical format
+      - Within each column, indices are sorted by row.
+      - There are no duplicate entries.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_matrix
+    >>> csc_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 2, 2, 0, 1, 2])
+    >>> col = np.array([0, 0, 1, 2, 2, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 4],
+           [0, 0, 5],
+           [2, 3, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
+    array([[1, 0, 4],
+           [0, 0, 5],
+           [2, 3, 6]])
+
+    """
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_csr.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..52ce35cdb1fbf75c26a08b4e13b93d236566ab0b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_csr.py
@@ -0,0 +1,558 @@
+"""Compressed Sparse Row matrix format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['csr_array', 'csr_matrix', 'isspmatrix_csr']
+
+import numpy as np
+
+from ._matrix import spmatrix
+from ._base import _spbase, sparray
+from ._sparsetools import (csr_tocsc, csr_tobsr, csr_count_blocks,
+                           get_csr_submatrix, csr_sample_values)
+from ._sputils import upcast
+
+from ._compressed import _cs_matrix
+
+
+class _csr_base(_cs_matrix):
+    _format = 'csr'
+    _allow_nd = (1, 2)
+
+    def transpose(self, axes=None, copy=False):
+        if axes is not None and axes != (1, 0):
+            raise ValueError("Sparse arrays/matrices do not support "
+                              "an 'axes' parameter because swapping "
+                              "dimensions is the only logical permutation.")
+
+        if self.ndim == 1:
+            return self.copy() if copy else self
+        M, N = self.shape
+        return self._csc_container((self.data, self.indices,
+                                    self.indptr), shape=(N, M), copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def tolil(self, copy=False):
+        if self.ndim != 2:
+            raise ValueError("Cannot convert a 1d sparse array to lil format")
+        lil = self._lil_container(self.shape, dtype=self.dtype)
+
+        self.sum_duplicates()
+        ptr,ind,dat = self.indptr,self.indices,self.data
+        rows, data = lil.rows, lil.data
+
+        for n in range(self.shape[0]):
+            start = ptr[n]
+            end = ptr[n+1]
+            rows[n] = ind[start:end].tolist()
+            data[n] = dat[start:end].tolist()
+
+        return lil
+
+    tolil.__doc__ = _spbase.tolil.__doc__
+
+    def tocsr(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    tocsr.__doc__ = _spbase.tocsr.__doc__
+
+    def tocsc(self, copy=False):
+        if self.ndim != 2:
+            raise ValueError("Cannot convert a 1d sparse array to csc format")
+        M, N = self.shape
+        idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+                                    maxval=max(self.nnz, M))
+        indptr = np.empty(N + 1, dtype=idx_dtype)
+        indices = np.empty(self.nnz, dtype=idx_dtype)
+        data = np.empty(self.nnz, dtype=upcast(self.dtype))
+
+        csr_tocsc(M, N,
+                  self.indptr.astype(idx_dtype),
+                  self.indices.astype(idx_dtype),
+                  self.data,
+                  indptr,
+                  indices,
+                  data)
+
+        A = self._csc_container((data, indices, indptr), shape=self.shape)
+        A.has_sorted_indices = True
+        return A
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def tobsr(self, blocksize=None, copy=True):
+        if self.ndim != 2:
+            raise ValueError("Cannot convert a 1d sparse array to bsr format")
+        if blocksize is None:
+            from ._spfuncs import estimate_blocksize
+            return self.tobsr(blocksize=estimate_blocksize(self))
+
+        elif blocksize == (1,1):
+            arg1 = (self.data.reshape(-1,1,1),self.indices,self.indptr)
+            return self._bsr_container(arg1, shape=self.shape, copy=copy)
+
+        else:
+            R,C = blocksize
+            M,N = self.shape
+
+            if R < 1 or C < 1 or M % R != 0 or N % C != 0:
+                raise ValueError(f'invalid blocksize {blocksize}')
+
+            blks = csr_count_blocks(M,N,R,C,self.indptr,self.indices)
+
+            idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+                                        maxval=max(N//C, blks))
+            indptr = np.empty(M//R+1, dtype=idx_dtype)
+            indices = np.empty(blks, dtype=idx_dtype)
+            data = np.zeros((blks,R,C), dtype=self.dtype)
+
+            csr_tobsr(M, N, R, C,
+                      self.indptr.astype(idx_dtype),
+                      self.indices.astype(idx_dtype),
+                      self.data,
+                      indptr, indices, data.ravel())
+
+            return self._bsr_container(
+                (data, indices, indptr), shape=self.shape
+            )
+
+    tobsr.__doc__ = _spbase.tobsr.__doc__
+
+    # these functions are used by the parent class (_cs_matrix)
+    # to remove redundancy between csc_matrix and csr_array
+    @staticmethod
+    def _swap(x):
+        """swap the members of x if this is a column-oriented matrix
+        """
+        return x
+
+    def __iter__(self):
+        if self.ndim == 1:
+            zero = self.dtype.type(0)
+            u = 0
+            for v, d in zip(self.indices, self.data):
+                for _ in range(v - u):
+                    yield zero
+                yield d
+                u = v + 1
+            for _ in range(self.shape[0] - u):
+                yield zero
+            return
+
+        indptr = np.zeros(2, dtype=self.indptr.dtype)
+        # return 1d (sparray) or 2drow (spmatrix)
+        shape = self.shape[1:] if isinstance(self, sparray) else (1, self.shape[1])
+        i0 = 0
+        for i1 in self.indptr[1:]:
+            indptr[1] = i1 - i0
+            indices = self.indices[i0:i1]
+            data = self.data[i0:i1]
+            yield self.__class__((data, indices, indptr), shape=shape, copy=True)
+            i0 = i1
+
+    def _getrow(self, i):
+        """Returns a copy of row i of the matrix, as a (1 x n)
+        CSR matrix (row vector).
+        """
+        if self.ndim == 1:
+            if i not in (0, -1):
+                raise IndexError(f'index ({i}) out of range')
+            return self.reshape((1, self.shape[0]), copy=True)
+
+        M, N = self.shape
+        i = int(i)
+        if i < 0:
+            i += M
+        if i < 0 or i >= M:
+            raise IndexError('index (%d) out of range' % i)
+        indptr, indices, data = get_csr_submatrix(
+            M, N, self.indptr, self.indices, self.data, i, i + 1, 0, N)
+        return self.__class__((data, indices, indptr), shape=(1, N),
+                              dtype=self.dtype, copy=False)
+
+    def _getcol(self, i):
+        """Returns a copy of column i. A (m x 1) sparse array (column vector).
+        """
+        if self.ndim == 1:
+            raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]")
+        M, N = self.shape
+        i = int(i)
+        if i < 0:
+            i += N
+        if i < 0 or i >= N:
+            raise IndexError('index (%d) out of range' % i)
+        indptr, indices, data = get_csr_submatrix(
+            M, N, self.indptr, self.indices, self.data, 0, M, i, i + 1)
+        return self.__class__((data, indices, indptr), shape=(M, 1),
+                              dtype=self.dtype, copy=False)
+
+    def _get_int(self, idx):
+        spot = np.flatnonzero(self.indices == idx)
+        if spot.size:
+            return self.data[spot[0]]
+        return self.data.dtype.type(0)
+
+    def _get_slice(self, idx):
+        if idx == slice(None):
+            return self.copy()
+        if idx.step in (1, None):
+            ret = self._get_submatrix(0, idx, copy=True)
+            return ret.reshape(ret.shape[-1])
+        return self._minor_slice(idx)
+
+    def _get_array(self, idx):
+        idx_dtype = self._get_index_dtype(self.indices)
+        idx = np.asarray(idx, dtype=idx_dtype)
+        if idx.size == 0:
+            return self.__class__([], dtype=self.dtype)
+
+        M, N = 1, self.shape[0]
+        row = np.zeros_like(idx, dtype=idx_dtype)
+        col = np.asarray(idx, dtype=idx_dtype)
+        val = np.empty(row.size, dtype=self.dtype)
+        csr_sample_values(M, N, self.indptr, self.indices, self.data,
+                          row.size, row, col, val)
+
+        new_shape = col.shape if col.shape[0] > 1 else (col.shape[0],)
+        return self.__class__(val.reshape(new_shape))
+
+    def _get_intXarray(self, row, col):
+        return self._getrow(row)._minor_index_fancy(col)
+
+    def _get_intXslice(self, row, col):
+        if col.step in (1, None):
+            return self._get_submatrix(row, col, copy=True)
+        # TODO: uncomment this once it's faster:
+        # return self._getrow(row)._minor_slice(col)
+
+        M, N = self.shape
+        start, stop, stride = col.indices(N)
+
+        ii, jj = self.indptr[row:row+2]
+        row_indices = self.indices[ii:jj]
+        row_data = self.data[ii:jj]
+
+        if stride > 0:
+            ind = (row_indices >= start) & (row_indices < stop)
+        else:
+            ind = (row_indices <= start) & (row_indices > stop)
+
+        if abs(stride) > 1:
+            ind &= (row_indices - start) % stride == 0
+
+        row_indices = (row_indices[ind] - start) // stride
+        row_data = row_data[ind]
+        row_indptr = np.array([0, len(row_indices)])
+
+        if stride < 0:
+            row_data = row_data[::-1]
+            row_indices = abs(row_indices[::-1])
+
+        shape = (1, max(0, int(np.ceil(float(stop - start) / stride))))
+        return self.__class__((row_data, row_indices, row_indptr), shape=shape,
+                              dtype=self.dtype, copy=False)
+
+    def _get_sliceXint(self, row, col):
+        if row.step in (1, None):
+            return self._get_submatrix(row, col, copy=True)
+        return self._major_slice(row)._get_submatrix(minor=col)
+
+    def _get_sliceXarray(self, row, col):
+        return self._major_slice(row)._minor_index_fancy(col)
+
+    def _get_arrayXint(self, row, col):
+        res = self._major_index_fancy(row)._get_submatrix(minor=col)
+        if row.ndim > 1:
+            return res.reshape(row.shape)
+        return res
+
+    def _get_arrayXslice(self, row, col):
+        if col.step not in (1, None):
+            col = np.arange(*col.indices(self.shape[1]))
+            return self._get_arrayXarray(row, col)
+        return self._major_index_fancy(row)._get_submatrix(minor=col)
+
+    def _set_int(self, idx, x):
+        self._set_many(0, idx, x)
+
+    def _set_array(self, idx, x):
+        x = np.broadcast_to(x, idx.shape)
+        self._set_many(np.zeros_like(idx), idx, x)
+
+
+def isspmatrix_csr(x):
+    """Is `x` of csr_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a csr matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a csr matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, csr_matrix, coo_matrix, isspmatrix_csr
+    >>> isspmatrix_csr(csr_matrix([[5]]))
+    True
+    >>> isspmatrix_csr(csr_array([[5]]))
+    False
+    >>> isspmatrix_csr(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, csr_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class csr_array(_csr_base, sparray):
+    """
+    Compressed Sparse Row array.
+
+    This can be instantiated in several ways:
+        csr_array(D)
+            where D is a 2-D ndarray
+
+        csr_array(S)
+            with another sparse array or matrix S (equivalent to S.tocsr())
+
+        csr_array((M, N), [dtype])
+            to construct an empty array with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        csr_array((data, (row_ind, col_ind)), [shape=(M, N)])
+            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+        csr_array((data, indices, indptr), [shape=(M, N)])
+            is the standard CSR representation where the column indices for
+            row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
+            corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
+            If the shape parameter is not supplied, the array dimensions
+            are inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        CSR format data array of the array
+    indices
+        CSR format index array of the array
+    indptr
+        CSR format index pointer array of the array
+    has_sorted_indices
+    has_canonical_format
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the CSR format
+      - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
+      - efficient row slicing
+      - fast matrix vector products
+
+    Disadvantages of the CSR format
+      - slow column slicing operations (consider CSC)
+      - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+    Canonical Format
+        - Within each row, indices are sorted by column.
+        - There are no duplicate entries.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_array
+    >>> csr_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 0, 1, 2, 2, 2])
+    >>> col = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csr_array((data, indices, indptr), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    Duplicate entries are summed together:
+
+    >>> row = np.array([0, 1, 2, 0])
+    >>> col = np.array([0, 1, 1, 0])
+    >>> data = np.array([1, 2, 4, 8])
+    >>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
+    array([[9, 0, 0],
+           [0, 2, 0],
+           [0, 4, 0]])
+
+    As an example of how to construct a CSR array incrementally,
+    the following snippet builds a term-document array from texts:
+
+    >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
+    >>> indptr = [0]
+    >>> indices = []
+    >>> data = []
+    >>> vocabulary = {}
+    >>> for d in docs:
+    ...     for term in d:
+    ...         index = vocabulary.setdefault(term, len(vocabulary))
+    ...         indices.append(index)
+    ...         data.append(1)
+    ...     indptr.append(len(indices))
+    ...
+    >>> csr_array((data, indices, indptr), dtype=int).toarray()
+    array([[2, 1, 0, 0],
+           [0, 1, 1, 1]])
+
+    """
+
+
+class csr_matrix(spmatrix, _csr_base):
+    """
+    Compressed Sparse Row matrix.
+
+    This can be instantiated in several ways:
+        csr_matrix(D)
+            where D is a 2-D ndarray
+
+        csr_matrix(S)
+            with another sparse array or matrix S (equivalent to S.tocsr())
+
+        csr_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+        csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
+            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+        csr_matrix((data, indices, indptr), [shape=(M, N)])
+            is the standard CSR representation where the column indices for
+            row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
+            corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
+            If the shape parameter is not supplied, the matrix dimensions
+            are inferred from the index arrays.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        CSR format data array of the matrix
+    indices
+        CSR format index array of the matrix
+    indptr
+        CSR format index pointer array of the matrix
+    has_sorted_indices
+    has_canonical_format
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the CSR format
+      - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
+      - efficient row slicing
+      - fast matrix vector products
+
+    Disadvantages of the CSR format
+      - slow column slicing operations (consider CSC)
+      - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+    Canonical Format
+        - Within each row, indices are sorted by column.
+        - There are no duplicate entries.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_matrix
+    >>> csr_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> row = np.array([0, 0, 1, 2, 2, 2])
+    >>> col = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    >>> indptr = np.array([0, 2, 3, 6])
+    >>> indices = np.array([0, 2, 2, 0, 1, 2])
+    >>> data = np.array([1, 2, 3, 4, 5, 6])
+    >>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
+    array([[1, 0, 2],
+           [0, 0, 3],
+           [4, 5, 6]])
+
+    Duplicate entries are summed together:
+
+    >>> row = np.array([0, 1, 2, 0])
+    >>> col = np.array([0, 1, 1, 0])
+    >>> data = np.array([1, 2, 4, 8])
+    >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+    array([[9, 0, 0],
+           [0, 2, 0],
+           [0, 4, 0]])
+
+    As an example of how to construct a CSR matrix incrementally,
+    the following snippet builds a term-document matrix from texts:
+
+    >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
+    >>> indptr = [0]
+    >>> indices = []
+    >>> data = []
+    >>> vocabulary = {}
+    >>> for d in docs:
+    ...     for term in d:
+    ...         index = vocabulary.setdefault(term, len(vocabulary))
+    ...         indices.append(index)
+    ...         data.append(1)
+    ...     indptr.append(len(indices))
+    ...
+    >>> csr_matrix((data, indices, indptr), dtype=int).toarray()
+    array([[2, 1, 0, 0],
+           [0, 1, 1, 1]])
+
+    """
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_data.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..585820b10a65271b52b81d140e82130eb4177979
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_data.py
@@ -0,0 +1,569 @@
+"""Base class for sparse matrice with a .data attribute
+
+    subclasses must provide a _with_data() method that
+    creates a new matrix with the same sparsity pattern
+    as self but with a different data array
+
+"""
+
+import math
+import numpy as np
+
+from ._base import _spbase, sparray, _ufuncs_with_fixed_point_at_zero
+from ._sputils import isscalarlike, validateaxis
+
+__all__ = []
+
+
+# TODO implement all relevant operations
+# use .data.__methods__() instead of /=, *=, etc.
+class _data_matrix(_spbase):
+    def __init__(self, arg1, *, maxprint=None):
+        _spbase.__init__(self, arg1, maxprint=maxprint)
+
+    @property
+    def dtype(self):
+        return self.data.dtype
+
+    @dtype.setter
+    def dtype(self, newtype):
+        self.data.dtype = newtype
+
+    def _deduped_data(self):
+        if hasattr(self, 'sum_duplicates'):
+            self.sum_duplicates()
+        return self.data
+
+    def __abs__(self):
+        return self._with_data(abs(self._deduped_data()))
+
+    def __round__(self, ndigits=0):
+        return self._with_data(np.around(self._deduped_data(), decimals=ndigits))
+
+    def _real(self):
+        return self._with_data(self.data.real)
+
+    def _imag(self):
+        return self._with_data(self.data.imag)
+
+    def __neg__(self):
+        if self.dtype.kind == 'b':
+            raise NotImplementedError('negating a boolean sparse array is not '
+                                      'supported')
+        return self._with_data(-self.data)
+
+    def __imul__(self, other):  # self *= other
+        if isscalarlike(other):
+            self.data *= other
+            return self
+        return NotImplemented
+
+    def __itruediv__(self, other):  # self /= other
+        if isscalarlike(other):
+            recip = 1.0 / other
+            self.data *= recip
+            return self
+        else:
+            return NotImplemented
+
+    def astype(self, dtype, casting='unsafe', copy=True):
+        dtype = np.dtype(dtype)
+        if self.dtype != dtype:
+            matrix = self._with_data(
+                self.data.astype(dtype, casting=casting, copy=True),
+                copy=True
+            )
+            return matrix._with_data(matrix._deduped_data(), copy=False)
+        elif copy:
+            return self.copy()
+        else:
+            return self
+
+    astype.__doc__ = _spbase.astype.__doc__
+
+    def conjugate(self, copy=True):
+        if np.issubdtype(self.dtype, np.complexfloating):
+            return self._with_data(self.data.conjugate(), copy=copy)
+        elif copy:
+            return self.copy()
+        else:
+            return self
+
+    conjugate.__doc__ = _spbase.conjugate.__doc__
+
+    def copy(self):
+        return self._with_data(self.data.copy(), copy=True)
+
+    copy.__doc__ = _spbase.copy.__doc__
+
+    def power(self, n, dtype=None):
+        """
+        This function performs element-wise power.
+
+        Parameters
+        ----------
+        n : scalar
+            n is a non-zero scalar (nonzero avoids dense ones creation)
+            If zero power is desired, special case it to use `np.ones`
+
+        dtype : If dtype is not specified, the current dtype will be preserved.
+
+        Raises
+        ------
+        NotImplementedError : if n is a zero scalar
+            If zero power is desired, special case it to use
+            ``np.ones(A.shape, dtype=A.dtype)``
+        """
+        if not isscalarlike(n):
+            raise NotImplementedError("input is not scalar")
+        if not n:
+            raise NotImplementedError(
+                "zero power is not supported as it would densify the matrix.\n"
+                "Use `np.ones(A.shape, dtype=A.dtype)` for this case."
+            )
+
+        data = self._deduped_data()
+        if dtype is not None:
+            data = data.astype(dtype)
+        return self._with_data(data ** n)
+
+    ###########################
+    # Multiplication handlers #
+    ###########################
+
+    def _mul_scalar(self, other):
+        return self._with_data(self.data * other)
+
+
+# Add the numpy unary ufuncs for which func(0) = 0 to _data_matrix.
+for npfunc in _ufuncs_with_fixed_point_at_zero:
+    name = npfunc.__name__
+
+    def _create_method(op):
+        def method(self):
+            result = op(self._deduped_data())
+            return self._with_data(result, copy=True)
+
+        method.__doc__ = (f"Element-wise {name}.\n\n"
+                          f"See `numpy.{name}` for more information.")
+        method.__name__ = name
+
+        return method
+
+    setattr(_data_matrix, name, _create_method(npfunc))
+
+
+def _find_missing_index(ind, n):
+    for k, a in enumerate(ind):
+        if k != a:
+            return k
+
+    k += 1
+    if k < n:
+        return k
+    else:
+        return -1
+
+
+class _minmax_mixin:
+    """Mixin for min and max methods.
+
+    These are not implemented for dia_matrix, hence the separate class.
+    """
+
+    def _min_or_max_axis(self, axis, min_or_max, explicit):
+        N = self.shape[axis]
+        if N == 0:
+            raise ValueError("zero-size array to reduction operation")
+        M = self.shape[1 - axis]
+        idx_dtype = self._get_index_dtype(maxval=M)
+
+        mat = self.tocsc() if axis == 0 else self.tocsr()
+        mat.sum_duplicates()
+
+        major_index, value = mat._minor_reduce(min_or_max)
+        if not explicit:
+            not_full = np.diff(mat.indptr)[major_index] < N
+            value[not_full] = min_or_max(value[not_full], 0)
+
+        mask = value != 0
+        major_index = np.compress(mask, major_index).astype(idx_dtype, copy=False)
+        value = np.compress(mask, value)
+
+        if isinstance(self, sparray):
+            coords = (major_index,)
+            shape = (M,)
+            return self._coo_container((value, coords), shape=shape, dtype=self.dtype)
+
+        if axis == 0:
+            return self._coo_container(
+                (value, (np.zeros(len(value), dtype=idx_dtype), major_index)),
+                dtype=self.dtype, shape=(1, M)
+            )
+        else:
+            return self._coo_container(
+                (value, (major_index, np.zeros(len(value), dtype=idx_dtype))),
+                dtype=self.dtype, shape=(M, 1)
+            )
+
+    def _min_or_max(self, axis, out, min_or_max, explicit):
+        if out is not None:
+            raise ValueError("Sparse arrays do not support an 'out' parameter.")
+
+        validateaxis(axis)
+        if self.ndim == 1:
+            if axis not in (None, 0, -1):
+                raise ValueError("axis out of range")
+            axis = None  # avoid calling special axis case. no impact on 1d
+
+        if axis is None:
+            if 0 in self.shape:
+                raise ValueError("zero-size array to reduction operation")
+
+            zero = self.dtype.type(0)
+            if self.nnz == 0:
+                return zero
+            m = min_or_max.reduce(self._deduped_data().ravel())
+            if self.nnz != math.prod(self.shape) and not explicit:
+                m = min_or_max(zero, m)
+            return m
+
+        if axis < 0:
+            axis += 2
+
+        if (axis == 0) or (axis == 1):
+            return self._min_or_max_axis(axis, min_or_max, explicit)
+        else:
+            raise ValueError("axis out of range")
+
+    def _arg_min_or_max_axis(self, axis, argmin_or_argmax, compare, explicit):
+        if self.shape[axis] == 0:
+            raise ValueError("Cannot apply the operation along a zero-sized dimension.")
+
+        if axis < 0:
+            axis += 2
+
+        zero = self.dtype.type(0)
+
+        mat = self.tocsc() if axis == 0 else self.tocsr()
+        mat.sum_duplicates()
+
+        ret_size, line_size = mat._swap(mat.shape)
+        ret = np.zeros(ret_size, dtype=int)
+
+        nz_lines, = np.nonzero(np.diff(mat.indptr))
+        for i in nz_lines:
+            p, q = mat.indptr[i:i + 2]
+            data = mat.data[p:q]
+            indices = mat.indices[p:q]
+            extreme_index = argmin_or_argmax(data)
+            extreme_value = data[extreme_index]
+            if explicit:
+                if q - p > 0:
+                    ret[i] = indices[extreme_index]
+            else:
+                if compare(extreme_value, zero) or q - p == line_size:
+                    ret[i] = indices[extreme_index]
+                else:
+                    zero_ind = _find_missing_index(indices, line_size)
+                    if extreme_value == zero:
+                        ret[i] = min(extreme_index, zero_ind)
+                    else:
+                        ret[i] = zero_ind
+
+        if isinstance(self, sparray):
+            return ret
+
+        if axis == 1:
+            ret = ret.reshape(-1, 1)
+
+        return self._ascontainer(ret)
+
+    def _arg_min_or_max(self, axis, out, argmin_or_argmax, compare, explicit):
+        if out is not None:
+            raise ValueError("Sparse types do not support an 'out' parameter.")
+
+        validateaxis(axis)
+
+        if self.ndim == 1:
+            if axis not in (None, 0, -1):
+                raise ValueError("axis out of range")
+            axis = None  # avoid calling special axis case. no impact on 1d
+
+        if axis is not None:
+            return self._arg_min_or_max_axis(axis, argmin_or_argmax, compare, explicit)
+
+        if 0 in self.shape:
+            raise ValueError("Cannot apply the operation to an empty matrix.")
+
+        if self.nnz == 0:
+            if explicit:
+                raise ValueError("Cannot apply the operation to zero matrix "
+                                 "when explicit=True.")
+            return 0
+
+        zero = self.dtype.type(0)
+        mat = self.tocoo()
+        # Convert to canonical form: no duplicates, sorted indices.
+        mat.sum_duplicates()
+        extreme_index = argmin_or_argmax(mat.data)
+        if explicit:
+            return extreme_index
+        extreme_value = mat.data[extreme_index]
+        num_col = mat.shape[-1]
+
+        # If the min value is less than zero, or max is greater than zero,
+        # then we do not need to worry about implicit zeros.
+        if compare(extreme_value, zero):
+            # cast to Python int to avoid overflow and RuntimeError
+            return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index])
+
+        # Cheap test for the rare case where we have no implicit zeros.
+        size = math.prod(self.shape)
+        if size == mat.nnz:
+            return int(mat.row[extreme_index]) * num_col + int(mat.col[extreme_index])
+
+        # At this stage, any implicit zero could be the min or max value.
+        # After sum_duplicates(), the `row` and `col` arrays are guaranteed to
+        # be sorted in C-order, which means the linearized indices are sorted.
+        linear_indices = mat.row * num_col + mat.col
+        first_implicit_zero_index = _find_missing_index(linear_indices, size)
+        if extreme_value == zero:
+            return min(first_implicit_zero_index, extreme_index)
+        return first_implicit_zero_index
+
+    def max(self, axis=None, out=None, *, explicit=False):
+        """Return the maximum of the array/matrix or maximum along an axis.
+
+        By default, all elements are taken into account, not just the non-zero ones.
+        But with `explicit` set, only the stored elements are considered.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the sum is computed. The default is to
+            compute the maximum over all elements, returning
+            a scalar (i.e., `axis` = `None`).
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except
+            for the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only the stored elements will be considered.
+            If a row/column is empty, the sparse.coo_array returned
+            has no stored element (i.e. an implicit zero) for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        amax : coo_array or scalar
+            Maximum of `a`. If `axis` is None, the result is a scalar value.
+            If `axis` is given, the result is a sparse.coo_array of dimension
+            ``a.ndim - 1``.
+
+        See Also
+        --------
+        min : The minimum value of a sparse array/matrix along a given axis.
+        numpy.max : NumPy's implementation of 'max'
+
+        """
+        return self._min_or_max(axis, out, np.maximum, explicit)
+
+    def min(self, axis=None, out=None, *, explicit=False):
+        """Return the minimum of the array/matrix or maximum along an axis.
+
+        By default, all elements are taken into account, not just the non-zero ones.
+        But with `explicit` set, only the stored elements are considered.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the sum is computed. The default is to
+            compute the minimum over all elements, returning
+            a scalar (i.e., `axis` = `None`).
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except for
+            the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only the stored elements will be considered.
+            If a row/column is empty, the sparse.coo_array returned
+            has no stored element (i.e. an implicit zero) for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        amin : coo_matrix or scalar
+            Minimum of `a`. If `axis` is None, the result is a scalar value.
+            If `axis` is given, the result is a sparse.coo_array of dimension
+            ``a.ndim - 1``.
+
+        See Also
+        --------
+        max : The maximum value of a sparse array/matrix along a given axis.
+        numpy.min : NumPy's implementation of 'min'
+
+        """
+        return self._min_or_max(axis, out, np.minimum, explicit)
+
+    def nanmax(self, axis=None, out=None, *, explicit=False):
+        """Return the maximum, ignoring any Nans, along an axis.
+
+        Return the maximum, ignoring any Nans, of the array/matrix along an axis.
+        By default this takes all elements into account, but with `explicit` set,
+        only stored elements are considered.
+
+        .. versionadded:: 1.11.0
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the maximum is computed. The default is to
+            compute the maximum over all elements, returning
+            a scalar (i.e., `axis` = `None`).
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except
+            for the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only the stored elements will be considered.
+            If a row/column is empty, the sparse.coo_array returned
+            has no stored element (i.e. an implicit zero) for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        amax : coo_array or scalar
+            Maximum of `a`. If `axis` is None, the result is a scalar value.
+            If `axis` is given, the result is a sparse.coo_array of dimension
+            ``a.ndim - 1``.
+
+        See Also
+        --------
+        nanmin : The minimum value of a sparse array/matrix along a given axis,
+                 ignoring NaNs.
+        max : The maximum value of a sparse array/matrix along a given axis,
+              propagating NaNs.
+        numpy.nanmax : NumPy's implementation of 'nanmax'.
+
+        """
+        return self._min_or_max(axis, out, np.fmax, explicit)
+
+    def nanmin(self, axis=None, out=None, *, explicit=False):
+        """Return the minimum, ignoring any Nans, along an axis.
+
+        Return the minimum, ignoring any Nans, of the array/matrix along an axis.
+        By default this takes all elements into account, but with `explicit` set,
+        only stored elements are considered.
+
+        .. versionadded:: 1.11.0
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None} optional
+            Axis along which the minimum is computed. The default is to
+            compute the minimum over all elements, returning
+            a scalar (i.e., `axis` = `None`).
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except for
+            the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only the stored elements will be considered.
+            If a row/column is empty, the sparse.coo_array returned
+            has no stored element (i.e. an implicit zero) for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        amin : coo_array or scalar
+            Minimum of `a`. If `axis` is None, the result is a scalar value.
+            If `axis` is given, the result is a sparse.coo_array of dimension
+            ``a.ndim - 1``.
+
+        See Also
+        --------
+        nanmax : The maximum value of a sparse array/matrix along a given axis,
+                 ignoring NaNs.
+        min : The minimum value of a sparse array/matrix along a given axis,
+              propagating NaNs.
+        numpy.nanmin : NumPy's implementation of 'nanmin'.
+
+        """
+        return self._min_or_max(axis, out, np.fmin, explicit)
+
+    def argmax(self, axis=None, out=None, *, explicit=False):
+        """Return indices of maximum elements along an axis.
+
+        By default, implicit zero elements are taken into account. If there are
+        several minimum values, the index of the first occurrence is returned.
+        If `explicit` is set, only explicitly stored elements will be considered.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None}, optional
+            Axis along which the argmax is computed. If None (default), index
+            of the maximum element in the flatten data is returned.
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except for
+            the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only explicitly stored elements will be considered.
+            If axis is not None and a row/column has no stored elements, argmax
+            is undefined, so the index ``0`` is returned for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+        ind : numpy.matrix or int
+            Indices of maximum elements. If matrix, its size along `axis` is 1.
+        """
+        return self._arg_min_or_max(axis, out, np.argmax, np.greater, explicit)
+
+    def argmin(self, axis=None, out=None, *, explicit=False):
+        """Return indices of minimum elements along an axis.
+
+        By default, implicit zero elements are taken into account. If there are
+        several minimum values, the index of the first occurrence is returned.
+        If `explicit` is set, only explicitly stored elements will be considered.
+
+        Parameters
+        ----------
+        axis : {-2, -1, 0, 1, None}, optional
+            Axis along which the argmin is computed. If None (default), index
+            of the minimum element in the flatten data is returned.
+
+        out : None, optional
+            This argument is in the signature *solely* for NumPy
+            compatibility reasons. Do not pass in anything except for
+            the default value, as this argument is not used.
+
+        explicit : {False, True} optional (default: False)
+            When set to True, only explicitly stored elements will be considered.
+            If axis is not None and a row/column has no stored elements, argmin
+            is undefined, so the index ``0`` is returned for that row/column.
+
+            .. versionadded:: 1.15.0
+
+        Returns
+        -------
+         ind : numpy.matrix or int
+            Indices of minimum elements. If matrix, its size along `axis` is 1.
+        """
+        return self._arg_min_or_max(axis, out, np.argmin, np.less, explicit)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_dia.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_dia.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2944e080b6abc1705d3f597dda7478335b2bcf3
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_dia.py
@@ -0,0 +1,590 @@
+"""Sparse DIAgonal format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['dia_array', 'dia_matrix', 'isspmatrix_dia']
+
+import numpy as np
+
+from .._lib._util import copy_if_needed
+from ._matrix import spmatrix
+from ._base import issparse, _formats, _spbase, sparray
+from ._data import _data_matrix
+from ._sputils import (
+    isshape, upcast_char, getdtype, get_sum_dtype, validateaxis, check_shape
+)
+from ._sparsetools import dia_matvec
+
+
+class _dia_base(_data_matrix):
+    _format = 'dia'
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _data_matrix.__init__(self, arg1, maxprint=maxprint)
+
+        if issparse(arg1):
+            if arg1.format == "dia":
+                if copy:
+                    arg1 = arg1.copy()
+                self.data = arg1.data
+                self.offsets = arg1.offsets
+                self._shape = check_shape(arg1.shape)
+            else:
+                if arg1.format == self.format and copy:
+                    A = arg1.copy()
+                else:
+                    A = arg1.todia()
+                self.data = A.data
+                self.offsets = A.offsets
+                self._shape = check_shape(A.shape)
+        elif isinstance(arg1, tuple):
+            if isshape(arg1):
+                # It's a tuple of matrix dimensions (M, N)
+                # create empty matrix
+                self._shape = check_shape(arg1)
+                self.data = np.zeros((0,0), getdtype(dtype, default=float))
+                idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+                self.offsets = np.zeros((0), dtype=idx_dtype)
+            else:
+                try:
+                    # Try interpreting it as (data, offsets)
+                    data, offsets = arg1
+                except Exception as e:
+                    message = 'unrecognized form for dia_array constructor'
+                    raise ValueError(message) from e
+                else:
+                    if shape is None:
+                        raise ValueError('expected a shape argument')
+                    if not copy:
+                        copy = copy_if_needed
+                    self.data = np.atleast_2d(np.array(arg1[0], dtype=dtype, copy=copy))
+                    offsets = np.array(arg1[1],
+                                       dtype=self._get_index_dtype(maxval=max(shape)),
+                                       copy=copy)
+                    self.offsets = np.atleast_1d(offsets)
+                    self._shape = check_shape(shape)
+        else:
+            # must be dense, convert to COO first, then to DIA
+            try:
+                arg1 = np.asarray(arg1)
+            except Exception as e:
+                raise ValueError("unrecognized form for "
+                                 f"{self.format}_matrix constructor") from e
+            if isinstance(self, sparray) and arg1.ndim != 2:
+                raise ValueError(f"DIA arrays don't support {arg1.ndim}D input. Use 2D")
+            A = self._coo_container(arg1, dtype=dtype, shape=shape).todia()
+            self.data = A.data
+            self.offsets = A.offsets
+            self._shape = check_shape(A.shape)
+
+        if dtype is not None:
+            newdtype = getdtype(dtype)
+            self.data = self.data.astype(newdtype)
+
+        # check format
+        if self.offsets.ndim != 1:
+            raise ValueError('offsets array must have rank 1')
+
+        if self.data.ndim != 2:
+            raise ValueError('data array must have rank 2')
+
+        if self.data.shape[0] != len(self.offsets):
+            raise ValueError('number of diagonals (%d) '
+                    'does not match the number of offsets (%d)'
+                    % (self.data.shape[0], len(self.offsets)))
+
+        if len(np.unique(self.offsets)) != len(self.offsets):
+            raise ValueError('offset array contains duplicate values')
+
+    def __repr__(self):
+        _, fmt = _formats[self.format]
+        sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
+        d = self.data.shape[0]
+        return (
+            f"<{fmt} sparse {sparse_cls} of dtype '{self.dtype}'\n"
+            f"\twith {self.nnz} stored elements ({d} diagonals) and shape {self.shape}>"
+        )
+
+    def _data_mask(self):
+        """Returns a mask of the same shape as self.data, where
+        mask[i,j] is True when data[i,j] corresponds to a stored element."""
+        num_rows, num_cols = self.shape
+        offset_inds = np.arange(self.data.shape[1])
+        row = offset_inds - self.offsets[:,None]
+        mask = (row >= 0)
+        mask &= (row < num_rows)
+        mask &= (offset_inds < num_cols)
+        return mask
+
+    def count_nonzero(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError(
+                "count_nonzero over an axis is not implemented for DIA format"
+            )
+        mask = self._data_mask()
+        return np.count_nonzero(self.data[mask])
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def _getnnz(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError("_getnnz over an axis is not implemented "
+                                      "for DIA format")
+        M,N = self.shape
+        nnz = 0
+        for k in self.offsets:
+            if k > 0:
+                nnz += min(M,N-k)
+            else:
+                nnz += min(M+k,N)
+        return int(nnz)
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def sum(self, axis=None, dtype=None, out=None):
+        validateaxis(axis)
+
+        if axis is not None and axis < 0:
+            axis += 2
+
+        res_dtype = get_sum_dtype(self.dtype)
+        num_rows, num_cols = self.shape
+        ret = None
+
+        if axis == 0:
+            mask = self._data_mask()
+            x = (self.data * mask).sum(axis=0)
+            if x.shape[0] == num_cols:
+                res = x
+            else:
+                res = np.zeros(num_cols, dtype=x.dtype)
+                res[:x.shape[0]] = x
+            ret = self._ascontainer(res, dtype=res_dtype)
+
+        else:
+            row_sums = np.zeros((num_rows, 1), dtype=res_dtype)
+            one = np.ones(num_cols, dtype=res_dtype)
+            dia_matvec(num_rows, num_cols, len(self.offsets),
+                       self.data.shape[1], self.offsets, self.data, one, row_sums)
+
+            row_sums = self._ascontainer(row_sums)
+
+            if axis is None:
+                return row_sums.sum(dtype=dtype, out=out)
+
+            ret = self._ascontainer(row_sums.sum(axis=axis))
+
+        return ret.sum(axis=(), dtype=dtype, out=out)
+
+    sum.__doc__ = _spbase.sum.__doc__
+
+    def _add_sparse(self, other):
+        # If other is not DIA format, let them handle us instead.
+        if not isinstance(other, _dia_base):
+            return other._add_sparse(self)
+
+        # Fast path for exact equality of the sparsity structure.
+        if np.array_equal(self.offsets, other.offsets):
+            return self._with_data(self.data + other.data)
+
+        # Find the union of the offsets (which will be sorted and unique).
+        new_offsets = np.union1d(self.offsets, other.offsets)
+        self_idx = np.searchsorted(new_offsets, self.offsets)
+        other_idx = np.searchsorted(new_offsets, other.offsets)
+
+        self_d = self.data.shape[1]
+        other_d = other.data.shape[1]
+        # Fast path for a sparsity structure where the final offsets are a
+        # permutation of the existing offsets and the diagonal lengths match.
+        if self_d == other_d and len(new_offsets) == len(self.offsets):
+            new_data = self.data[_invert_index(self_idx)]
+            new_data[other_idx, :] += other.data
+        elif self_d == other_d and len(new_offsets) == len(other.offsets):
+            new_data = other.data[_invert_index(other_idx)]
+            new_data[self_idx, :] += self.data
+        else:
+            # Maximum diagonal length of the result.
+            d = min(self.shape[0] + new_offsets[-1], self.shape[1])
+
+            # Add all diagonals to a freshly-allocated data array.
+            new_data = np.zeros(
+                (len(new_offsets), d),
+                dtype=np.result_type(self.data, other.data),
+            )
+            new_data[self_idx, :self_d] += self.data[:, :d]
+            new_data[other_idx, :other_d] += other.data[:, :d]
+        return self._dia_container((new_data, new_offsets), shape=self.shape)
+
+    def _mul_scalar(self, other):
+        return self._with_data(self.data * other)
+
+    def _matmul_vector(self, other):
+        x = other
+
+        y = np.zeros(self.shape[0], dtype=upcast_char(self.dtype.char,
+                                                       x.dtype.char))
+
+        L = self.data.shape[1]
+
+        M,N = self.shape
+
+        dia_matvec(M,N, len(self.offsets), L, self.offsets, self.data,
+                   x.ravel(), y.ravel())
+
+        return y
+
+    def _setdiag(self, values, k=0):
+        M, N = self.shape
+
+        if values.ndim == 0:
+            # broadcast
+            values_n = np.inf
+        else:
+            values_n = len(values)
+
+        if k < 0:
+            n = min(M + k, N, values_n)
+            min_index = 0
+            max_index = n
+        else:
+            n = min(M, N - k, values_n)
+            min_index = k
+            max_index = k + n
+
+        if values.ndim != 0:
+            # allow also longer sequences
+            values = values[:n]
+
+        data_rows, data_cols = self.data.shape
+        if k in self.offsets:
+            if max_index > data_cols:
+                data = np.zeros((data_rows, max_index), dtype=self.data.dtype)
+                data[:, :data_cols] = self.data
+                self.data = data
+            self.data[self.offsets == k, min_index:max_index] = values
+        else:
+            self.offsets = np.append(self.offsets, self.offsets.dtype.type(k))
+            m = max(max_index, data_cols)
+            data = np.zeros((data_rows + 1, m), dtype=self.data.dtype)
+            data[:-1, :data_cols] = self.data
+            data[-1, min_index:max_index] = values
+            self.data = data
+
+    def todia(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    todia.__doc__ = _spbase.todia.__doc__
+
+    def transpose(self, axes=None, copy=False):
+        if axes is not None and axes != (1, 0):
+            raise ValueError("Sparse arrays/matrices do not support "
+                              "an 'axes' parameter because swapping "
+                              "dimensions is the only logical permutation.")
+
+        num_rows, num_cols = self.shape
+        max_dim = max(self.shape)
+
+        # flip diagonal offsets
+        offsets = -self.offsets
+
+        # re-align the data matrix
+        r = np.arange(len(offsets), dtype=np.intc)[:, None]
+        c = np.arange(num_rows, dtype=np.intc) - (offsets % max_dim)[:, None]
+        pad_amount = max(0, max_dim-self.data.shape[1])
+        data = np.hstack((self.data, np.zeros((self.data.shape[0], pad_amount),
+                                              dtype=self.data.dtype)))
+        data = data[r, c]
+        return self._dia_container((data, offsets), shape=(
+            num_cols, num_rows), copy=copy)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def diagonal(self, k=0):
+        rows, cols = self.shape
+        if k <= -rows or k >= cols:
+            return np.empty(0, dtype=self.data.dtype)
+        idx, = np.nonzero(self.offsets == k)
+        first_col = max(0, k)
+        last_col = min(rows + k, cols)
+        result_size = last_col - first_col
+        if idx.size == 0:
+            return np.zeros(result_size, dtype=self.data.dtype)
+        result = self.data[idx[0], first_col:last_col]
+        padding = result_size - len(result)
+        if padding > 0:
+            result = np.pad(result, (0, padding), mode='constant')
+        return result
+
+    diagonal.__doc__ = _spbase.diagonal.__doc__
+
+    def tocsc(self, copy=False):
+        if self.nnz == 0:
+            return self._csc_container(self.shape, dtype=self.dtype)
+
+        num_rows, num_cols = self.shape
+        num_offsets, offset_len = self.data.shape
+        offset_inds = np.arange(offset_len)
+
+        row = offset_inds - self.offsets[:,None]
+        mask = (row >= 0)
+        mask &= (row < num_rows)
+        mask &= (offset_inds < num_cols)
+        mask &= (self.data != 0)
+
+        idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+        indptr = np.zeros(num_cols + 1, dtype=idx_dtype)
+        indptr[1:offset_len+1] = np.cumsum(mask.sum(axis=0)[:num_cols])
+        if offset_len < num_cols:
+            indptr[offset_len+1:] = indptr[offset_len]
+        indices = row.T[mask.T].astype(idx_dtype, copy=False)
+        data = self.data.T[mask.T]
+        return self._csc_container((data, indices, indptr), shape=self.shape,
+                                   dtype=self.dtype)
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def tocoo(self, copy=False):
+        num_rows, num_cols = self.shape
+        num_offsets, offset_len = self.data.shape
+        offset_inds = np.arange(offset_len)
+
+        row = offset_inds - self.offsets[:,None]
+        mask = (row >= 0)
+        mask &= (row < num_rows)
+        mask &= (offset_inds < num_cols)
+        mask &= (self.data != 0)
+        row = row[mask]
+        col = np.tile(offset_inds, num_offsets)[mask.ravel()]
+        idx_dtype = self._get_index_dtype(
+            arrays=(self.offsets,), maxval=max(self.shape)
+        )
+        row = row.astype(idx_dtype, copy=False)
+        col = col.astype(idx_dtype, copy=False)
+        data = self.data[mask]
+        # Note: this cannot set has_canonical_format=True, because despite the
+        # lack of duplicates, we do not generate sorted indices.
+        return self._coo_container(
+            (data, (row, col)), shape=self.shape, dtype=self.dtype, copy=False
+        )
+
+    tocoo.__doc__ = _spbase.tocoo.__doc__
+
+    # needed by _data_matrix
+    def _with_data(self, data, copy=True):
+        """Returns a matrix with the same sparsity structure as self,
+        but with different data.  By default the structure arrays are copied.
+        """
+        if copy:
+            return self._dia_container(
+                (data, self.offsets.copy()), shape=self.shape
+            )
+        else:
+            return self._dia_container(
+                (data, self.offsets), shape=self.shape
+            )
+
+    def resize(self, *shape):
+        shape = check_shape(shape)
+        M, N = shape
+        # we do not need to handle the case of expanding N
+        self.data = self.data[:, :N]
+
+        if (M > self.shape[0] and
+                np.any(self.offsets + self.shape[0] < self.data.shape[1])):
+            # explicitly clear values that were previously hidden
+            mask = (self.offsets[:, None] + self.shape[0] <=
+                    np.arange(self.data.shape[1]))
+            self.data[mask] = 0
+
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+
+def _invert_index(idx):
+    """Helper function to invert an index array."""
+    inv = np.zeros_like(idx)
+    inv[idx] = np.arange(len(idx))
+    return inv
+
+
+def isspmatrix_dia(x):
+    """Is `x` of dia_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a dia matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a dia matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import dia_array, dia_matrix, coo_matrix, isspmatrix_dia
+    >>> isspmatrix_dia(dia_matrix([[5]]))
+    True
+    >>> isspmatrix_dia(dia_array([[5]]))
+    False
+    >>> isspmatrix_dia(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, dia_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class dia_array(_dia_base, sparray):
+    """
+    Sparse array with DIAgonal storage.
+
+    This can be instantiated in several ways:
+        dia_array(D)
+            where D is a 2-D ndarray
+
+        dia_array(S)
+            with another sparse array or matrix S (equivalent to S.todia())
+
+        dia_array((M, N), [dtype])
+            to construct an empty array with shape (M, N),
+            dtype is optional, defaulting to dtype='d'.
+
+        dia_array((data, offsets), shape=(M, N))
+            where the ``data[k,:]`` stores the diagonal entries for
+            diagonal ``offsets[k]`` (See example below)
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        DIA format data array of the array
+    offsets
+        DIA format offset array of the array
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+    Sparse arrays with DIAgonal storage do not support slicing.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import dia_array
+    >>> dia_array((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
+    >>> offsets = np.array([0, -1, 2])
+    >>> dia_array((data, offsets), shape=(4, 4)).toarray()
+    array([[1, 0, 3, 0],
+           [1, 2, 0, 4],
+           [0, 2, 3, 0],
+           [0, 0, 3, 4]])
+
+    >>> from scipy.sparse import dia_array
+    >>> n = 10
+    >>> ex = np.ones(n)
+    >>> data = np.array([ex, 2 * ex, ex])
+    >>> offsets = np.array([-1, 0, 1])
+    >>> dia_array((data, offsets), shape=(n, n)).toarray()
+    array([[2., 1., 0., ..., 0., 0., 0.],
+           [1., 2., 1., ..., 0., 0., 0.],
+           [0., 1., 2., ..., 0., 0., 0.],
+           ...,
+           [0., 0., 0., ..., 2., 1., 0.],
+           [0., 0., 0., ..., 1., 2., 1.],
+           [0., 0., 0., ..., 0., 1., 2.]])
+    """
+
+
+class dia_matrix(spmatrix, _dia_base):
+    """
+    Sparse matrix with DIAgonal storage.
+
+    This can be instantiated in several ways:
+        dia_matrix(D)
+            where D is a 2-D ndarray
+
+        dia_matrix(S)
+            with another sparse array or matrix S (equivalent to S.todia())
+
+        dia_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N),
+            dtype is optional, defaulting to dtype='d'.
+
+        dia_matrix((data, offsets), shape=(M, N))
+            where the ``data[k,:]`` stores the diagonal entries for
+            diagonal ``offsets[k]`` (See example below)
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        DIA format data array of the matrix
+    offsets
+        DIA format offset array of the matrix
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+    Sparse matrices with DIAgonal storage do not support slicing.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.sparse import dia_matrix
+    >>> dia_matrix((3, 4), dtype=np.int8).toarray()
+    array([[0, 0, 0, 0],
+           [0, 0, 0, 0],
+           [0, 0, 0, 0]], dtype=int8)
+
+    >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
+    >>> offsets = np.array([0, -1, 2])
+    >>> dia_matrix((data, offsets), shape=(4, 4)).toarray()
+    array([[1, 0, 3, 0],
+           [1, 2, 0, 4],
+           [0, 2, 3, 0],
+           [0, 0, 3, 4]])
+
+    >>> from scipy.sparse import dia_matrix
+    >>> n = 10
+    >>> ex = np.ones(n)
+    >>> data = np.array([ex, 2 * ex, ex])
+    >>> offsets = np.array([-1, 0, 1])
+    >>> dia_matrix((data, offsets), shape=(n, n)).toarray()
+    array([[2., 1., 0., ..., 0., 0., 0.],
+           [1., 2., 1., ..., 0., 0., 0.],
+           [0., 1., 2., ..., 0., 0., 0.],
+           ...,
+           [0., 0., 0., ..., 2., 1., 0.],
+           [0., 0., 0., ..., 1., 2., 1.],
+           [0., 0., 0., ..., 0., 1., 2.]])
+    """
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_dok.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9814a9e8d0b2d5a67185faae9311f4216cc7d13
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_dok.py
@@ -0,0 +1,692 @@
+"""Dictionary Of Keys based matrix"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['dok_array', 'dok_matrix', 'isspmatrix_dok']
+
+import itertools
+from warnings import warn
+import numpy as np
+
+from ._matrix import spmatrix
+from ._base import _spbase, sparray, issparse
+from ._index import IndexMixin
+from ._sputils import (isdense, getdtype, isshape, isintlike, isscalarlike,
+                       upcast, upcast_scalar, check_shape)
+
+
+class _dok_base(_spbase, IndexMixin, dict):
+    _format = 'dok'
+    _allow_nd = (1, 2)
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _spbase.__init__(self, arg1, maxprint=maxprint)
+
+        if isinstance(arg1, tuple) and isshape(arg1, allow_nd=self._allow_nd):
+            self._shape = check_shape(arg1, allow_nd=self._allow_nd)
+            self._dict = {}
+            self.dtype = getdtype(dtype, default=float)
+        elif issparse(arg1):  # Sparse ctor
+            if arg1.format == self.format:
+                arg1 = arg1.copy() if copy else arg1
+            else:
+                arg1 = arg1.todok()
+
+            if dtype is not None:
+                arg1 = arg1.astype(dtype, copy=False)
+
+            self._dict = arg1._dict
+            self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd)
+            self.dtype = getdtype(arg1.dtype)
+        else:  # Dense ctor
+            try:
+                arg1 = np.asarray(arg1)
+            except Exception as e:
+                raise TypeError('Invalid input format.') from e
+
+            if arg1.ndim > 2:
+                raise ValueError(f"DOK arrays don't yet support {arg1.ndim}D input.")
+
+            if arg1.ndim == 1:
+                if dtype is not None:
+                    arg1 = arg1.astype(dtype)
+                self._dict = {i: v for i, v in enumerate(arg1) if v != 0}
+                self.dtype = getdtype(arg1.dtype)
+            else:
+                d = self._coo_container(arg1, shape=shape, dtype=dtype).todok()
+                self._dict = d._dict
+                self.dtype = getdtype(d.dtype)
+            self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd)
+
+    def update(self, val):
+        # Prevent direct usage of update
+        raise NotImplementedError("Direct update to DOK sparse format is not allowed.")
+
+    def _getnnz(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError(
+                "_getnnz over an axis is not implemented for DOK format."
+            )
+        return len(self._dict)
+
+    def count_nonzero(self, axis=None):
+        if axis is not None:
+            raise NotImplementedError(
+                "count_nonzero over an axis is not implemented for DOK format."
+            )
+        return sum(x != 0 for x in self.values())
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def __len__(self):
+        return len(self._dict)
+
+    def __contains__(self, key):
+        return key in self._dict
+
+    def setdefault(self, key, default=None, /):
+        return self._dict.setdefault(key, default)
+
+    def __delitem__(self, key, /):
+        del self._dict[key]
+
+    def clear(self):
+        return self._dict.clear()
+
+    def pop(self, /, *args):
+        return self._dict.pop(*args)
+
+    def __reversed__(self):
+        raise TypeError("reversed is not defined for dok_array type")
+
+    def __or__(self, other):
+        type_names = f"{type(self).__name__} and {type(other).__name__}"
+        raise TypeError(f"unsupported operand type for |: {type_names}")
+
+    def __ror__(self, other):
+        type_names = f"{type(self).__name__} and {type(other).__name__}"
+        raise TypeError(f"unsupported operand type for |: {type_names}")
+
+    def __ior__(self, other):
+        type_names = f"{type(self).__name__} and {type(other).__name__}"
+        raise TypeError(f"unsupported operand type for |: {type_names}")
+
+    def popitem(self):
+        return self._dict.popitem()
+
+    def items(self):
+        return self._dict.items()
+
+    def keys(self):
+        return self._dict.keys()
+
+    def values(self):
+        return self._dict.values()
+
+    def get(self, key, default=0.0):
+        """This provides dict.get method functionality with type checking"""
+        if key in self._dict:
+            return self._dict[key]
+        if isintlike(key) and self.ndim == 1:
+            key = (key,)
+        if self.ndim != len(key):
+            raise IndexError(f'Index {key} length needs to match self.shape')
+        try:
+            for i in key:
+                assert isintlike(i)
+        except (AssertionError, TypeError, ValueError) as e:
+            raise IndexError('Index must be or consist of integers.') from e
+        key = tuple(i + M if i < 0 else i for i, M in zip(key, self.shape))
+        if any(i < 0 or i >= M for i, M in zip(key, self.shape)):
+            raise IndexError('Index out of bounds.')
+        if self.ndim == 1:
+            key = key[0]
+        return self._dict.get(key, default)
+
+    # 1D get methods
+    def _get_int(self, idx):
+        return self._dict.get(idx, self.dtype.type(0))
+
+    def _get_slice(self, idx):
+        i_range = range(*idx.indices(self.shape[0]))
+        return self._get_array(list(i_range))
+
+    def _get_array(self, idx):
+        idx = np.asarray(idx)
+        if idx.ndim == 0:
+            val = self._dict.get(int(idx), self.dtype.type(0))
+            return np.array(val, stype=self.dtype)
+        new_dok = self._dok_container(idx.shape, dtype=self.dtype)
+        dok_vals = [self._dict.get(i, 0) for i in idx.ravel()]
+        if dok_vals:
+            if len(idx.shape) == 1:
+                for i, v in enumerate(dok_vals):
+                    if v:
+                        new_dok._dict[i] = v
+            else:
+                new_idx = np.unravel_index(np.arange(len(dok_vals)), idx.shape)
+                new_idx = new_idx[0] if len(new_idx) == 1 else zip(*new_idx)
+                for i, v in zip(new_idx, dok_vals, strict=True):
+                    if v:
+                        new_dok._dict[i] = v
+        return new_dok
+
+    # 2D get methods
+    def _get_intXint(self, row, col):
+        return self._dict.get((row, col), self.dtype.type(0))
+
+    def _get_intXslice(self, row, col):
+        return self._get_sliceXslice(slice(row, row + 1), col)
+
+    def _get_sliceXint(self, row, col):
+        return self._get_sliceXslice(row, slice(col, col + 1))
+
+    def _get_sliceXslice(self, row, col):
+        row_start, row_stop, row_step = row.indices(self.shape[0])
+        col_start, col_stop, col_step = col.indices(self.shape[1])
+        row_range = range(row_start, row_stop, row_step)
+        col_range = range(col_start, col_stop, col_step)
+        shape = (len(row_range), len(col_range))
+        # Switch paths only when advantageous
+        # (count the iterations in the loops, adjust for complexity)
+        if len(self) >= 2 * shape[0] * shape[1]:
+            # O(nr*nc) path: loop over 
+            return self._get_columnXarray(row_range, col_range)
+        # O(nnz) path: loop over entries of self
+        newdok = self._dok_container(shape, dtype=self.dtype)
+        for key in self.keys():
+            i, ri = divmod(int(key[0]) - row_start, row_step)
+            if ri != 0 or i < 0 or i >= shape[0]:
+                continue
+            j, rj = divmod(int(key[1]) - col_start, col_step)
+            if rj != 0 or j < 0 or j >= shape[1]:
+                continue
+            newdok._dict[i, j] = self._dict[key]
+        return newdok
+
+    def _get_intXarray(self, row, col):
+        return self._get_columnXarray([row], col.ravel())
+
+    def _get_arrayXint(self, row, col):
+        res = self._get_columnXarray(row.ravel(), [col])
+        if row.ndim > 1:
+            return res.reshape(row.shape)
+        return res
+
+    def _get_sliceXarray(self, row, col):
+        row = list(range(*row.indices(self.shape[0])))
+        return self._get_columnXarray(row, col)
+
+    def _get_arrayXslice(self, row, col):
+        col = list(range(*col.indices(self.shape[1])))
+        return self._get_columnXarray(row, col)
+
+    def _get_columnXarray(self, row, col):
+        # outer indexing
+        newdok = self._dok_container((len(row), len(col)), dtype=self.dtype)
+
+        for i, r in enumerate(row):
+            for j, c in enumerate(col):
+                v = self._dict.get((r, c), 0)
+                if v:
+                    newdok._dict[i, j] = v
+        return newdok
+
+    def _get_arrayXarray(self, row, col):
+        # inner indexing
+        i, j = map(np.atleast_2d, np.broadcast_arrays(row, col))
+        newdok = self._dok_container(i.shape, dtype=self.dtype)
+
+        for key in itertools.product(range(i.shape[0]), range(i.shape[1])):
+            v = self._dict.get((i[key], j[key]), 0)
+            if v:
+                newdok._dict[key] = v
+        return newdok
+
+    # 1D set methods
+    def _set_int(self, idx, x):
+        if x:
+            self._dict[idx] = x
+        elif idx in self._dict:
+            del self._dict[idx]
+
+    def _set_array(self, idx, x):
+        idx_set = idx.ravel()
+        x_set = x.ravel()
+        if len(idx_set) != len(x_set):
+            if len(x_set) == 1:
+                x_set = np.full(len(idx_set), x_set[0], dtype=self.dtype)
+            else:
+              raise ValueError("Need len(index)==len(data) or len(data)==1")
+        for i, v in zip(idx_set, x_set):
+            if v:
+                self._dict[i] = v
+            elif i in self._dict:
+                del self._dict[i]
+
+    # 2D set methods
+    def _set_intXint(self, row, col, x):
+        key = (row, col)
+        if x:
+            self._dict[key] = x
+        elif key in self._dict:
+            del self._dict[key]
+
+    def _set_arrayXarray(self, row, col, x):
+        row = list(map(int, row.ravel()))
+        col = list(map(int, col.ravel()))
+        x = x.ravel()
+        self._dict.update(zip(zip(row, col), x))
+
+        for i in np.nonzero(x == 0)[0]:
+            key = (row[i], col[i])
+            if self._dict[key] == 0:
+                # may have been superseded by later update
+                del self._dict[key]
+
+    def __add__(self, other):
+        if isscalarlike(other):
+            res_dtype = upcast_scalar(self.dtype, other)
+            new = self._dok_container(self.shape, dtype=res_dtype)
+            # Add this scalar to each element.
+            for key in itertools.product(*[range(d) for d in self.shape]):
+                aij = self._dict.get(key, 0) + other
+                if aij:
+                    new[key] = aij
+        elif issparse(other):
+            if other.shape != self.shape:
+                raise ValueError("Matrix dimensions are not equal.")
+            res_dtype = upcast(self.dtype, other.dtype)
+            new = self._dok_container(self.shape, dtype=res_dtype)
+            new._dict = self._dict.copy()
+            if other.format == "dok":
+                o_items = other.items()
+            else:
+                other = other.tocoo()
+                if self.ndim == 1:
+                    o_items = zip(other.coords[0], other.data)
+                else:
+                    o_items = zip(zip(*other.coords), other.data)
+            with np.errstate(over='ignore'):
+                new._dict.update((k, new[k] + v) for k, v in o_items)
+        elif isdense(other):
+            new = self.todense() + other
+        else:
+            return NotImplemented
+        return new
+
+    def __radd__(self, other):
+        return self + other  # addition is commutative
+
+    def __neg__(self):
+        if self.dtype.kind == 'b':
+            raise NotImplementedError(
+                'Negating a sparse boolean matrix is not supported.'
+            )
+        new = self._dok_container(self.shape, dtype=self.dtype)
+        new._dict.update((k, -v) for k, v in self.items())
+        return new
+
+    def _mul_scalar(self, other):
+        res_dtype = upcast_scalar(self.dtype, other)
+        # Multiply this scalar by every element.
+        new = self._dok_container(self.shape, dtype=res_dtype)
+        new._dict.update(((k, v * other) for k, v in self.items()))
+        return new
+
+    def _matmul_vector(self, other):
+        res_dtype = upcast(self.dtype, other.dtype)
+
+        # vector @ vector
+        if self.ndim == 1:
+            if issparse(other):
+                if other.format == "dok":
+                    keys = self.keys() & other.keys()
+                else:
+                    keys = self.keys() & other.tocoo().coords[0]
+                return res_dtype(sum(self._dict[k] * other._dict[k] for k in keys))
+            elif isdense(other):
+                return res_dtype(sum(other[k] * v for k, v in self.items()))
+            else:
+                return NotImplemented
+
+        # matrix @ vector
+        result = np.zeros(self.shape[0], dtype=res_dtype)
+        for (i, j), v in self.items():
+            result[i] += v * other[j]
+        return result
+
+    def _matmul_multivector(self, other):
+        result_dtype = upcast(self.dtype, other.dtype)
+        # vector @ multivector
+        if self.ndim == 1:
+            # works for other 1d or 2d
+            return sum(v * other[j] for j, v in self._dict.items())
+
+        # matrix @ multivector
+        M = self.shape[0]
+        new_shape = (M,) if other.ndim == 1 else (M, other.shape[1])
+        result = np.zeros(new_shape, dtype=result_dtype)
+        for (i, j), v in self.items():
+            result[i] += v * other[j]
+        return result
+
+    def __imul__(self, other):
+        if isscalarlike(other):
+            self._dict.update((k, v * other) for k, v in self.items())
+            return self
+        return NotImplemented
+
+    def __truediv__(self, other):
+        if isscalarlike(other):
+            res_dtype = upcast_scalar(self.dtype, other)
+            new = self._dok_container(self.shape, dtype=res_dtype)
+            new._dict.update(((k, v / other) for k, v in self.items()))
+            return new
+        return self.tocsr() / other
+
+    def __itruediv__(self, other):
+        if isscalarlike(other):
+            self._dict.update((k, v / other) for k, v in self.items())
+            return self
+        return NotImplemented
+
+    def __reduce__(self):
+        # this approach is necessary because __setstate__ is called after
+        # __setitem__ upon unpickling and since __init__ is not called there
+        # is no shape attribute hence it is not possible to unpickle it.
+        return dict.__reduce__(self)
+
+    def diagonal(self, k=0):
+        if self.ndim == 2:
+            return super().diagonal(k)
+        raise ValueError("diagonal requires two dimensions")
+
+    def transpose(self, axes=None, copy=False):
+        if self.ndim == 1:
+            return self.copy()
+
+        if axes is not None and axes != (1, 0):
+            raise ValueError(
+                "Sparse arrays/matrices do not support "
+                "an 'axes' parameter because swapping "
+                "dimensions is the only logical permutation."
+            )
+
+        M, N = self.shape
+        new = self._dok_container((N, M), dtype=self.dtype, copy=copy)
+        new._dict.update((((right, left), val) for (left, right), val in self.items()))
+        return new
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def conjtransp(self):
+        """DEPRECATED: Return the conjugate transpose.
+
+        .. deprecated:: 1.14.0
+
+            `conjtransp` is deprecated and will be removed in v1.16.0.
+            Use ``.T.conj()`` instead.
+        """
+        msg = ("`conjtransp` is deprecated and will be removed in v1.16.0. "
+                   "Use `.T.conj()` instead.")
+        warn(msg, DeprecationWarning, stacklevel=2)
+
+        if self.ndim == 1:
+            new = self.tocoo()
+            new.data = new.data.conjugate()
+            return new
+
+        M, N = self.shape
+        new = self._dok_container((N, M), dtype=self.dtype)
+        new._dict = {(right, left): np.conj(val) for (left, right), val in self.items()}
+        return new
+
+    def copy(self):
+        new = self._dok_container(self.shape, dtype=self.dtype)
+        new._dict.update(self._dict)
+        return new
+
+    copy.__doc__ = _spbase.copy.__doc__
+
+    @classmethod
+    def fromkeys(cls, iterable, value=1, /):
+        tmp = dict.fromkeys(iterable, value)
+        if isinstance(next(iter(tmp)), tuple):
+            shape = tuple(max(idx) + 1 for idx in zip(*tmp))
+        else:
+            shape = (max(tmp) + 1,)
+        result = cls(shape, dtype=type(value))
+        result._dict = tmp
+        return result
+
+    def tocoo(self, copy=False):
+        nnz = self.nnz
+        if nnz == 0:
+            return self._coo_container(self.shape, dtype=self.dtype)
+
+        idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+        data = np.fromiter(self.values(), dtype=self.dtype, count=nnz)
+        # handle 1d keys specially b/c not a tuple
+        inds = zip(*self.keys()) if self.ndim > 1 else (self.keys(),)
+        coords = tuple(np.fromiter(ix, dtype=idx_dtype, count=nnz) for ix in inds)
+        A = self._coo_container((data, coords), shape=self.shape, dtype=self.dtype)
+        A.has_canonical_format = True
+        return A
+
+    tocoo.__doc__ = _spbase.tocoo.__doc__
+
+    def todok(self, copy=False):
+        if copy:
+            return self.copy()
+        return self
+
+    todok.__doc__ = _spbase.todok.__doc__
+
+    def tocsc(self, copy=False):
+        if self.ndim == 1:
+            raise NotImplementedError("tocsr() not valid for 1d sparse array")
+        return self.tocoo(copy=False).tocsc(copy=copy)
+
+    tocsc.__doc__ = _spbase.tocsc.__doc__
+
+    def resize(self, *shape):
+        shape = check_shape(shape, allow_nd=self._allow_nd)
+        if len(shape) != len(self.shape):
+            # TODO implement resize across dimensions
+            raise NotImplementedError
+
+        if self.ndim == 1:
+            newN = shape[-1]
+            for i in list(self._dict):
+                if i >= newN:
+                    del self._dict[i]
+            self._shape = shape
+            return
+
+        newM, newN = shape
+        M, N = self.shape
+        if newM < M or newN < N:
+            # Remove all elements outside new dimensions
+            for i, j in list(self.keys()):
+                if i >= newM or j >= newN:
+                    del self._dict[i, j]
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+    # Added for 1d to avoid `tocsr` from _base.py
+    def astype(self, dtype, casting='unsafe', copy=True):
+        dtype = np.dtype(dtype)
+        if self.dtype != dtype:
+            result = self._dok_container(self.shape, dtype=dtype)
+            data = np.array(list(self._dict.values()), dtype=dtype)
+            result._dict = dict(zip(self._dict, data))
+            return result
+        elif copy:
+            return self.copy()
+        return self
+
+
+def isspmatrix_dok(x):
+    """Is `x` of dok_array type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a dok matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a dok matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import dok_array, dok_matrix, coo_matrix, isspmatrix_dok
+    >>> isspmatrix_dok(dok_matrix([[5]]))
+    True
+    >>> isspmatrix_dok(dok_array([[5]]))
+    False
+    >>> isspmatrix_dok(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, dok_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class dok_array(_dok_base, sparray):
+    """
+    Dictionary Of Keys based sparse array.
+
+    This is an efficient structure for constructing sparse
+    arrays incrementally.
+
+    This can be instantiated in several ways:
+        dok_array(D)
+            where D is a 2-D ndarray
+
+        dok_array(S)
+            with another sparse array or matrix S (equivalent to S.todok())
+
+        dok_array((M,N), [dtype])
+            create the array with initial shape (M,N)
+            dtype is optional, defaulting to dtype='d'
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+        Number of nonzero elements
+    size
+    T
+
+    Notes
+    -----
+
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    - Allows for efficient O(1) access of individual elements.
+    - Duplicates are not allowed.
+    - Can be efficiently converted to a coo_array once constructed.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import dok_array
+    >>> S = dok_array((5, 5), dtype=np.float32)
+    >>> for i in range(5):
+    ...     for j in range(5):
+    ...         S[i, j] = i + j    # Update element
+
+    """
+
+
+class dok_matrix(spmatrix, _dok_base):
+    """
+    Dictionary Of Keys based sparse matrix.
+
+    This is an efficient structure for constructing sparse
+    matrices incrementally.
+
+    This can be instantiated in several ways:
+        dok_matrix(D)
+            where D is a 2-D ndarray
+
+        dok_matrix(S)
+            with another sparse array or matrix S (equivalent to S.todok())
+
+        dok_matrix((M,N), [dtype])
+            create the matrix with initial shape (M,N)
+            dtype is optional, defaulting to dtype='d'
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+        Number of nonzero elements
+    size
+    T
+
+    Notes
+    -----
+
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    - Allows for efficient O(1) access of individual elements.
+    - Duplicates are not allowed.
+    - Can be efficiently converted to a coo_matrix once constructed.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import dok_matrix
+    >>> S = dok_matrix((5, 5), dtype=np.float32)
+    >>> for i in range(5):
+    ...     for j in range(5):
+    ...         S[i, j] = i + j    # Update element
+
+    """
+
+    def set_shape(self, shape):
+        new_matrix = self.reshape(shape, copy=False).asformat(self.format)
+        self.__dict__ = new_matrix.__dict__
+
+    def get_shape(self):
+        """Get shape of a sparse matrix."""
+        return self._shape
+
+    shape = property(fget=get_shape, fset=set_shape)
+
+    def __reversed__(self):
+        return self._dict.__reversed__()
+
+    def __or__(self, other):
+        if isinstance(other, _dok_base):
+            return self._dict | other._dict
+        return self._dict | other
+
+    def __ror__(self, other):
+        if isinstance(other, _dok_base):
+            return self._dict | other._dict
+        return self._dict | other
+
+    def __ior__(self, other):
+        if isinstance(other, _dok_base):
+            self._dict |= other._dict
+        else:
+            self._dict |= other
+        return self
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_extract.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ee1a88575926efa1d5a921edbd3d88696157dc2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_extract.py
@@ -0,0 +1,178 @@
+"""Functions to extract parts of sparse matrices
+"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['find', 'tril', 'triu']
+
+
+from ._coo import coo_matrix, coo_array
+from ._base import sparray
+
+
+def find(A):
+    """Return the indices and values of the nonzero elements of a matrix
+
+    Parameters
+    ----------
+    A : dense or sparse array or matrix
+        Matrix whose nonzero elements are desired.
+
+    Returns
+    -------
+    (I,J,V) : tuple of arrays
+        I,J, and V contain the row indices, column indices, and values
+        of the nonzero entries.
+
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, find
+    >>> A = csr_array([[7.0, 8.0, 0],[0, 0, 9.0]])
+    >>> find(A)
+    (array([0, 0, 1], dtype=int32),
+     array([0, 1, 2], dtype=int32),
+     array([ 7.,  8.,  9.]))
+
+    """
+
+    A = coo_array(A, copy=True)
+    A.sum_duplicates()
+    # remove explicit zeros
+    nz_mask = A.data != 0
+    return A.row[nz_mask], A.col[nz_mask], A.data[nz_mask]
+
+
+def tril(A, k=0, format=None):
+    """Return the lower triangular portion of a sparse array or matrix
+
+    Returns the elements on or below the k-th diagonal of A.
+        - k = 0 corresponds to the main diagonal
+        - k > 0 is above the main diagonal
+        - k < 0 is below the main diagonal
+
+    Parameters
+    ----------
+    A : dense or sparse array or matrix
+        Matrix whose lower trianglar portion is desired.
+    k : integer : optional
+        The top-most diagonal of the lower triangle.
+    format : string
+        Sparse format of the result, e.g. format="csr", etc.
+
+    Returns
+    -------
+    L : sparse matrix
+        Lower triangular portion of A in sparse format.
+
+    See Also
+    --------
+    triu : upper triangle in sparse format
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, tril
+    >>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
+    ...               dtype='int32')
+    >>> A.toarray()
+    array([[1, 2, 0, 0, 3],
+           [4, 5, 0, 6, 7],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> tril(A).toarray()
+    array([[1, 0, 0, 0, 0],
+           [4, 5, 0, 0, 0],
+           [0, 0, 8, 0, 0]], dtype=int32)
+    >>> tril(A).nnz
+    4
+    >>> tril(A, k=1).toarray()
+    array([[1, 2, 0, 0, 0],
+           [4, 5, 0, 0, 0],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> tril(A, k=-1).toarray()
+    array([[0, 0, 0, 0, 0],
+           [4, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0]], dtype=int32)
+    >>> tril(A, format='csc')
+    
+
+    """
+    coo_sparse = coo_array if isinstance(A, sparray) else coo_matrix
+
+    # convert to COOrdinate format where things are easy
+    A = coo_sparse(A, copy=False)
+    mask = A.row + k >= A.col
+
+    row = A.row[mask]
+    col = A.col[mask]
+    data = A.data[mask]
+    new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype)
+    return new_coo.asformat(format)
+
+
+def triu(A, k=0, format=None):
+    """Return the upper triangular portion of a sparse array or matrix
+
+    Returns the elements on or above the k-th diagonal of A.
+        - k = 0 corresponds to the main diagonal
+        - k > 0 is above the main diagonal
+        - k < 0 is below the main diagonal
+
+    Parameters
+    ----------
+    A : dense or sparse array or matrix
+        Matrix whose upper trianglar portion is desired.
+    k : integer : optional
+        The bottom-most diagonal of the upper triangle.
+    format : string
+        Sparse format of the result, e.g. format="csr", etc.
+
+    Returns
+    -------
+    L : sparse array or matrix
+        Upper triangular portion of A in sparse format.
+        Sparse array if A is a sparse array, otherwise matrix.
+
+    See Also
+    --------
+    tril : lower triangle in sparse format
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, triu
+    >>> A = csr_array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
+    ...                dtype='int32')
+    >>> A.toarray()
+    array([[1, 2, 0, 0, 3],
+           [4, 5, 0, 6, 7],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> triu(A).toarray()
+    array([[1, 2, 0, 0, 3],
+           [0, 5, 0, 6, 7],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> triu(A).nnz
+    8
+    >>> triu(A, k=1).toarray()
+    array([[0, 2, 0, 0, 3],
+           [0, 0, 0, 6, 7],
+           [0, 0, 0, 9, 0]], dtype=int32)
+    >>> triu(A, k=-1).toarray()
+    array([[1, 2, 0, 0, 3],
+           [4, 5, 0, 6, 7],
+           [0, 0, 8, 9, 0]], dtype=int32)
+    >>> triu(A, format='csc')
+    
+
+    """
+    coo_sparse = coo_array if isinstance(A, sparray) else coo_matrix
+
+    # convert to COOrdinate format where things are easy
+    A = coo_sparse(A, copy=False)
+    mask = A.row + k <= A.col
+
+    row = A.row[mask]
+    col = A.col[mask]
+    data = A.data[mask]
+    new_coo = coo_sparse((data, (row, col)), shape=A.shape, dtype=A.dtype)
+    return new_coo.asformat(format)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_index.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_index.py
new file mode 100644
index 0000000000000000000000000000000000000000..451df8b242c73b35036878feaf1f7ad302dc1f91
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_index.py
@@ -0,0 +1,444 @@
+"""Indexing mixin for sparse array/matrix classes.
+"""
+import numpy as np
+from ._sputils import isintlike
+from ._base import sparray, issparse
+
+INT_TYPES = (int, np.integer)
+
+
+def _broadcast_arrays(a, b):
+    """
+    Same as np.broadcast_arrays(a, b) but old writeability rules.
+
+    NumPy >= 1.17.0 transitions broadcast_arrays to return
+    read-only arrays. Set writeability explicitly to avoid warnings.
+    Retain the old writeability rules, as our Cython code assumes
+    the old behavior.
+    """
+    x, y = np.broadcast_arrays(a, b)
+    x.flags.writeable = a.flags.writeable
+    y.flags.writeable = b.flags.writeable
+    return x, y
+
+
+class IndexMixin:
+    """
+    This class provides common dispatching and validation logic for indexing.
+    """
+    def __getitem__(self, key):
+        index, new_shape = self._validate_indices(key)
+
+        # 1D array
+        if len(index) == 1:
+            idx = index[0]
+            if isinstance(idx, np.ndarray):
+                if idx.shape == ():
+                    idx = idx.item()
+            if isinstance(idx, INT_TYPES):
+                res = self._get_int(idx)
+            elif isinstance(idx, slice):
+                res = self._get_slice(idx)
+            else:  # assume array idx
+                res = self._get_array(idx)
+
+            # package the result and return
+            if not isinstance(self, sparray):
+                return res
+            # handle np.newaxis in idx when result would otherwise be a scalar
+            if res.shape == () and new_shape != ():
+                if len(new_shape) == 1:
+                    return self.__class__([res], shape=new_shape, dtype=self.dtype)
+                if len(new_shape) == 2:
+                    return self.__class__([[res]], shape=new_shape, dtype=self.dtype)
+            return res.reshape(new_shape)
+
+        # 2D array
+        row, col = index
+
+        # Dispatch to specialized methods.
+        if isinstance(row, INT_TYPES):
+            if isinstance(col, INT_TYPES):
+                res = self._get_intXint(row, col)
+            elif isinstance(col, slice):
+                res = self._get_intXslice(row, col)
+            elif col.ndim == 1:
+                res = self._get_intXarray(row, col)
+            elif col.ndim == 2:
+                res = self._get_intXarray(row, col)
+            else:
+                raise IndexError('index results in >2 dimensions')
+        elif isinstance(row, slice):
+            if isinstance(col, INT_TYPES):
+                res = self._get_sliceXint(row, col)
+            elif isinstance(col, slice):
+                if row == slice(None) and row == col:
+                    res = self.copy()
+                else:
+                    res = self._get_sliceXslice(row, col)
+            elif col.ndim == 1:
+                res = self._get_sliceXarray(row, col)
+            else:
+                raise IndexError('index results in >2 dimensions')
+        else:
+            if isinstance(col, INT_TYPES):
+                res = self._get_arrayXint(row, col)
+            elif isinstance(col, slice):
+                res = self._get_arrayXslice(row, col)
+            # arrayXarray preprocess
+            elif (row.ndim == 2 and row.shape[1] == 1
+                and (col.ndim == 1 or col.shape[0] == 1)):
+                # outer indexing
+                res = self._get_columnXarray(row[:, 0], col.ravel())
+            else:
+                # inner indexing
+                row, col = _broadcast_arrays(row, col)
+                if row.shape != col.shape:
+                    raise IndexError('number of row and column indices differ')
+                if row.size == 0:
+                    res = self.__class__(np.atleast_2d(row).shape, dtype=self.dtype)
+                else:
+                    res = self._get_arrayXarray(row, col)
+
+        # handle spmatrix (must be 2d, dont let 1d new_shape start reshape)
+        if not isinstance(self, sparray):
+            if new_shape == () or (len(new_shape) == 1 and res.ndim != 0):
+                # res handles cases not inflated by None
+                return res
+            if len(new_shape) == 1:
+                # shape inflated to 1D by None in index. Make 2D
+                new_shape = (1,) + new_shape
+            # reshape if needed (when None changes shape, e.g. A[1,:,None])
+            return res if new_shape == res.shape else res.reshape(new_shape)
+
+        # package the result and return
+        if res.shape != new_shape:
+            # handle formats that support indexing but not 1D (lil for now)
+            if self.format == "lil" and len(new_shape) != 2:
+                if res.shape == ():
+                    return self._coo_container([res], shape = new_shape)
+                return res.tocoo().reshape(new_shape)
+            return res.reshape(new_shape)
+        return res
+
+    def __setitem__(self, key, x):
+        index, _ = self._validate_indices(key)
+
+        # 1D array
+        if len(index) == 1:
+            idx = index[0]
+
+            if issparse(x):
+                x = x.toarray()
+            else:
+                x = np.asarray(x, dtype=self.dtype)
+
+            if isinstance(idx, INT_TYPES):
+                if x.size != 1:
+                    raise ValueError('Trying to assign a sequence to an item')
+                self._set_int(idx, x.flat[0])
+                return
+
+            if isinstance(idx, slice):
+                # check for simple case of slice that gives 1 item
+                # Note: Python `range` does not use lots of memory
+                idx_range = range(*idx.indices(self.shape[0]))
+                N = len(idx_range)
+                if N == 1 and x.size == 1:
+                    self._set_int(idx_range[0], x.flat[0])
+                    return
+                idx = np.arange(*idx.indices(self.shape[0]))
+                idx_shape = idx.shape
+            else:
+                idx_shape = idx.squeeze().shape
+            # broadcast scalar to full 1d
+            if x.squeeze().shape != idx_shape:
+                x = np.broadcast_to(x, idx.shape)
+            if x.size != 0:
+                self._set_array(idx, x)
+            return
+
+        # 2D array
+        row, col = index
+
+        if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES):
+            x = np.asarray(x, dtype=self.dtype)
+            if x.size != 1:
+                raise ValueError('Trying to assign a sequence to an item')
+            self._set_intXint(row, col, x.flat[0])
+            return
+
+        if isinstance(row, slice):
+            row = np.arange(*row.indices(self.shape[0]))[:, None]
+        else:
+            row = np.atleast_1d(row)
+
+        if isinstance(col, slice):
+            col = np.arange(*col.indices(self.shape[1]))[None, :]
+            if row.ndim == 1:
+                row = row[:, None]
+        else:
+            col = np.atleast_1d(col)
+
+        i, j = _broadcast_arrays(row, col)
+        if i.shape != j.shape:
+            raise IndexError('number of row and column indices differ')
+
+        if issparse(x):
+            if 0 in x.shape:
+                return
+            if i.ndim == 1:
+                # Inner indexing, so treat them like row vectors.
+                i = i[None]
+                j = j[None]
+            x = x.tocoo(copy=False).reshape(x._shape_as_2d, copy=True)
+            broadcast_row = x.shape[0] == 1 and i.shape[0] != 1
+            broadcast_col = x.shape[1] == 1 and i.shape[1] != 1
+            if not ((broadcast_row or x.shape[0] == i.shape[0]) and
+                    (broadcast_col or x.shape[1] == i.shape[1])):
+                raise ValueError('shape mismatch in assignment')
+            x.sum_duplicates()
+            self._set_arrayXarray_sparse(i, j, x)
+        else:
+            # Make x and i into the same shape
+            x = np.asarray(x, dtype=self.dtype)
+            if x.squeeze().shape != i.squeeze().shape:
+                x = np.broadcast_to(x, i.shape)
+            if x.size == 0:
+                return
+            x = x.reshape(i.shape)
+            self._set_arrayXarray(i, j, x)
+
+    def _validate_indices(self, key):
+        """Returns two tuples: (index tuple, requested shape tuple)"""
+        # single ellipsis
+        if key is Ellipsis:
+            return (slice(None),) * self.ndim, self.shape
+
+        if not isinstance(key, tuple):
+            key = [key]
+
+        ellps_pos = None
+        index_1st = []
+        prelim_ndim = 0
+        for i, idx in enumerate(key):
+            if idx is Ellipsis:
+                if ellps_pos is not None:
+                    raise IndexError('an index can only have a single ellipsis')
+                ellps_pos = i
+            elif idx is None:
+                index_1st.append(idx)
+            elif isinstance(idx, slice) or isintlike(idx):
+                index_1st.append(idx)
+                prelim_ndim += 1
+            elif (ix := _compatible_boolean_index(idx, self.ndim)) is not None:
+                index_1st.append(ix)
+                prelim_ndim += ix.ndim
+            elif issparse(idx):
+                # TODO: make sparse matrix indexing work for sparray
+                raise IndexError(
+                    'Indexing with sparse matrices is not supported '
+                    'except boolean indexing where matrix and index '
+                    'are equal shapes.')
+            else:  # dense array
+                index_1st.append(np.asarray(idx))
+                prelim_ndim += 1
+        ellip_slices = (self.ndim - prelim_ndim) * [slice(None)]
+        if ellip_slices:
+            if ellps_pos is None:
+                index_1st.extend(ellip_slices)
+            else:
+                index_1st = index_1st[:ellps_pos] + ellip_slices + index_1st[ellps_pos:]
+
+        # second pass (have processed ellipsis and preprocessed arrays)
+        idx_shape = []
+        index_ndim = 0
+        index = []
+        array_indices = []
+        for i, idx in enumerate(index_1st):
+            if idx is None:
+                idx_shape.append(1)
+            elif isinstance(idx, slice):
+                index.append(idx)
+                Ms = self._shape[index_ndim]
+                len_slice = len(range(*idx.indices(Ms)))
+                idx_shape.append(len_slice)
+                index_ndim += 1
+            elif isintlike(idx):
+                N = self._shape[index_ndim]
+                if not (-N <= idx < N):
+                    raise IndexError(f'index ({idx}) out of range')
+                idx = int(idx + N if idx < 0 else idx)
+                index.append(idx)
+                index_ndim += 1
+            # bool array (checked in first pass)
+            elif idx.dtype.kind == 'b':
+                ix = idx
+                tmp_ndim = index_ndim + ix.ndim
+                mid_shape = self._shape[index_ndim:tmp_ndim]
+                if ix.shape != mid_shape:
+                    raise IndexError(
+                        f"bool index {i} has shape {mid_shape} instead of {ix.shape}"
+                    )
+                index.extend(ix.nonzero())
+                array_indices.extend(range(index_ndim, tmp_ndim))
+                index_ndim = tmp_ndim
+            else:  # dense array
+                N = self._shape[index_ndim]
+                idx = self._asindices(idx, N)
+                index.append(idx)
+                array_indices.append(index_ndim)
+                index_ndim += 1
+        if index_ndim > self.ndim:
+            raise IndexError(
+                f'invalid index ndim. Array is {self.ndim}D. Index needs {index_ndim}D'
+            )
+        if len(array_indices) > 1:
+            idx_arrays = _broadcast_arrays(*(index[i] for i in array_indices))
+            if any(idx_arrays[0].shape != ix.shape for ix in idx_arrays[1:]):
+                shapes = " ".join(str(ix.shape) for ix in idx_arrays)
+                msg = (f'shape mismatch: indexing arrays could not be broadcast '
+                       f'together with shapes {shapes}')
+                raise IndexError(msg)
+            # TODO: handle this for nD (adjacent arrays stay, separated move to start)
+            idx_shape = list(idx_arrays[0].shape) + idx_shape
+        elif len(array_indices) == 1:
+            arr_index = array_indices[0]
+            arr_shape = list(index[arr_index].shape)
+            idx_shape = idx_shape[:arr_index] + arr_shape + idx_shape[arr_index:]
+        if (ndim := len(idx_shape)) > 2:
+            raise IndexError(f'Only 1D or 2D arrays allowed. Index makes {ndim}D')
+        return tuple(index), tuple(idx_shape)
+
+    def _asindices(self, idx, length):
+        """Convert `idx` to a valid index for an axis with a given length.
+
+        Subclasses that need special validation can override this method.
+        """
+        try:
+            x = np.asarray(idx)
+        except (ValueError, TypeError, MemoryError) as e:
+            raise IndexError('invalid index') from e
+
+        if x.ndim not in (1, 2):
+            raise IndexError('Index dimension must be 1 or 2')
+
+        if x.size == 0:
+            return x
+
+        # Check bounds
+        max_indx = x.max()
+        if max_indx >= length:
+            raise IndexError('index (%d) out of range' % max_indx)
+
+        min_indx = x.min()
+        if min_indx < 0:
+            if min_indx < -length:
+                raise IndexError('index (%d) out of range' % min_indx)
+            if x is idx or not x.flags.owndata:
+                x = x.copy()
+            x[x < 0] += length
+        return x
+
+    def _getrow(self, i):
+        """Return a copy of row i of the matrix, as a (1 x n) row vector.
+        """
+        M, N = self.shape
+        i = int(i)
+        if i < -M or i >= M:
+            raise IndexError('index (%d) out of range' % i)
+        if i < 0:
+            i += M
+        return self._get_intXslice(i, slice(None))
+
+    def _getcol(self, i):
+        """Return a copy of column i of the matrix, as a (m x 1) column vector.
+        """
+        M, N = self.shape
+        i = int(i)
+        if i < -N or i >= N:
+            raise IndexError('index (%d) out of range' % i)
+        if i < 0:
+            i += N
+        return self._get_sliceXint(slice(None), i)
+
+    def _get_int(self, idx):
+        raise NotImplementedError()
+
+    def _get_slice(self, idx):
+        raise NotImplementedError()
+
+    def _get_array(self, idx):
+        raise NotImplementedError()
+
+    def _get_intXint(self, row, col):
+        raise NotImplementedError()
+
+    def _get_intXarray(self, row, col):
+        raise NotImplementedError()
+
+    def _get_intXslice(self, row, col):
+        raise NotImplementedError()
+
+    def _get_sliceXint(self, row, col):
+        raise NotImplementedError()
+
+    def _get_sliceXslice(self, row, col):
+        raise NotImplementedError()
+
+    def _get_sliceXarray(self, row, col):
+        raise NotImplementedError()
+
+    def _get_arrayXint(self, row, col):
+        raise NotImplementedError()
+
+    def _get_arrayXslice(self, row, col):
+        raise NotImplementedError()
+
+    def _get_columnXarray(self, row, col):
+        raise NotImplementedError()
+
+    def _get_arrayXarray(self, row, col):
+        raise NotImplementedError()
+
+    def _set_int(self, idx, x):
+        raise NotImplementedError()
+
+    def _set_array(self, idx, x):
+        raise NotImplementedError()
+
+    def _set_intXint(self, row, col, x):
+        raise NotImplementedError()
+
+    def _set_arrayXarray(self, row, col, x):
+        raise NotImplementedError()
+
+    def _set_arrayXarray_sparse(self, row, col, x):
+        # Fall back to densifying x
+        x = np.asarray(x.toarray(), dtype=self.dtype)
+        x, _ = _broadcast_arrays(x, row)
+        self._set_arrayXarray(row, col, x)
+
+
+def _compatible_boolean_index(idx, desired_ndim):
+    """Check for boolean array or array-like. peek before asarray for array-like"""
+    # use attribute ndim to indicate a compatible array and check dtype
+    # if not, look at 1st element as quick rejection of bool, else slower asanyarray
+    if not hasattr(idx, 'ndim'):
+        # is first element boolean?
+        try:
+            ix = next(iter(idx), None)
+            for _ in range(desired_ndim):
+                if isinstance(ix, bool):
+                    break
+                ix = next(iter(ix), None)
+            else:
+                return None
+        except TypeError:
+            return None
+        # since first is boolean, construct array and check all elements
+        idx = np.asanyarray(idx)
+
+    if idx.dtype.kind == 'b':
+        return idx
+    return None
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_lil.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_lil.py
new file mode 100644
index 0000000000000000000000000000000000000000..479472445cd8bdc36374b3d8bc18e6f9df123306
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_lil.py
@@ -0,0 +1,632 @@
+"""List of Lists sparse matrix class
+"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['lil_array', 'lil_matrix', 'isspmatrix_lil']
+
+from bisect import bisect_left
+
+import numpy as np
+
+from ._matrix import spmatrix
+from ._base import _spbase, sparray, issparse
+from ._index import IndexMixin, INT_TYPES, _broadcast_arrays
+from ._sputils import (getdtype, isshape, isscalarlike, upcast_scalar,
+                       check_shape, check_reshape_kwargs)
+from . import _csparsetools
+
+
+class _lil_base(_spbase, IndexMixin):
+    _format = 'lil'
+
+    def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
+        _spbase.__init__(self, arg1, maxprint=maxprint)
+        self.dtype = getdtype(dtype, arg1, default=float)
+
+        # First get the shape
+        if issparse(arg1):
+            if arg1.format == "lil" and copy:
+                A = arg1.copy()
+            else:
+                A = arg1.tolil()
+
+            if dtype is not None:
+                newdtype = getdtype(dtype)
+                A = A.astype(newdtype, copy=False)
+
+            self._shape = check_shape(A.shape)
+            self.dtype = A.dtype
+            self.rows = A.rows
+            self.data = A.data
+        elif isinstance(arg1,tuple):
+            if isshape(arg1):
+                if shape is not None:
+                    raise ValueError('invalid use of shape parameter')
+                M, N = arg1
+                self._shape = check_shape((M, N))
+                self.rows = np.empty((M,), dtype=object)
+                self.data = np.empty((M,), dtype=object)
+                for i in range(M):
+                    self.rows[i] = []
+                    self.data[i] = []
+            else:
+                raise TypeError('unrecognized lil_array constructor usage')
+        else:
+            # assume A is dense
+            try:
+                A = self._ascontainer(arg1)
+            except TypeError as e:
+                raise TypeError('unsupported matrix type') from e
+            if isinstance(self, sparray) and A.ndim != 2:
+                raise ValueError(f"LIL arrays don't support {A.ndim}D input. Use 2D")
+            A = self._csr_container(A, dtype=dtype).tolil()
+
+            self._shape = check_shape(A.shape)
+            self.dtype = getdtype(A.dtype)
+            self.rows = A.rows
+            self.data = A.data
+
+    def __iadd__(self,other):
+        self[:,:] = self + other
+        return self
+
+    def __isub__(self,other):
+        self[:,:] = self - other
+        return self
+
+    def __imul__(self,other):
+        if isscalarlike(other):
+            self[:,:] = self * other
+            return self
+        else:
+            return NotImplemented
+
+    def __itruediv__(self,other):
+        if isscalarlike(other):
+            self[:,:] = self / other
+            return self
+        else:
+            return NotImplemented
+
+    # Whenever the dimensions change, empty lists should be created for each
+    # row
+
+    def _getnnz(self, axis=None):
+        if axis is None:
+            return sum([len(rowvals) for rowvals in self.data])
+        if axis < 0:
+            axis += 2
+        if axis == 0:
+            out = np.zeros(self.shape[1], dtype=np.intp)
+            for row in self.rows:
+                out[row] += 1
+            return out
+        elif axis == 1:
+            return np.array([len(rowvals) for rowvals in self.data], dtype=np.intp)
+        else:
+            raise ValueError('axis out of bounds')
+
+    _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+    def count_nonzero(self, axis=None):
+        if axis is None:
+            return sum(np.count_nonzero(rowvals) for rowvals in self.data)
+
+        if axis < 0:
+            axis += 2
+        if axis == 0:
+            out = np.zeros(self.shape[1], dtype=np.intp)
+            for row, data in zip(self.rows, self.data):
+                mask = [c for c, d in zip(row, data) if d != 0]
+                out[mask] += 1
+            return out
+        elif axis == 1:
+            return np.array(
+                [np.count_nonzero(rowvals) for rowvals in self.data], dtype=np.intp,
+            )
+        else:
+            raise ValueError('axis out of bounds')
+
+    count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+    def getrowview(self, i):
+        """Returns a view of the 'i'th row (without copying).
+        """
+        new = self._lil_container((1, self.shape[1]), dtype=self.dtype)
+        new.rows[0] = self.rows[i]
+        new.data[0] = self.data[i]
+        return new
+
+    def getrow(self, i):
+        """Returns a copy of the 'i'th row.
+        """
+        M, N = self.shape
+        if i < 0:
+            i += M
+        if i < 0 or i >= M:
+            raise IndexError('row index out of bounds')
+        new = self._lil_container((1, N), dtype=self.dtype)
+        new.rows[0] = self.rows[i][:]
+        new.data[0] = self.data[i][:]
+        return new
+
+    def __getitem__(self, key):
+        # Fast path for simple (int, int) indexing.
+        if (isinstance(key, tuple) and len(key) == 2 and
+                isinstance(key[0], INT_TYPES) and
+                isinstance(key[1], INT_TYPES)):
+            # lil_get1 handles validation for us.
+            return self._get_intXint(*key)
+        # Everything else takes the normal path.
+        return IndexMixin.__getitem__(self, key)
+
+    def _asindices(self, idx, N):
+        # LIL routines handle bounds-checking for us, so don't do it here.
+        try:
+            x = np.asarray(idx)
+        except (ValueError, TypeError, MemoryError) as e:
+            raise IndexError('invalid index') from e
+        if x.ndim not in (1, 2):
+            raise IndexError('Index dimension must be <= 2')
+        return x
+
+    def _get_intXint(self, row, col):
+        v = _csparsetools.lil_get1(self.shape[0], self.shape[1], self.rows,
+                                   self.data, row, col)
+        return self.dtype.type(v)
+
+    def _get_sliceXint(self, row, col):
+        row = range(*row.indices(self.shape[0]))
+        return self._get_row_ranges(row, slice(col, col+1))
+
+    def _get_arrayXint(self, row, col):
+        res = self._get_row_ranges(row.ravel(), slice(col, col+1))
+        if row.ndim > 1:
+            return res.reshape(row.shape)
+        return res
+
+    def _get_intXslice(self, row, col):
+        return self._get_row_ranges((row,), col)
+
+    def _get_sliceXslice(self, row, col):
+        row = range(*row.indices(self.shape[0]))
+        return self._get_row_ranges(row, col)
+
+    def _get_arrayXslice(self, row, col):
+        return self._get_row_ranges(row, col)
+
+    def _get_intXarray(self, row, col):
+        row = np.array(row, dtype=col.dtype, ndmin=1)
+        return self._get_columnXarray(row, col)
+
+    def _get_sliceXarray(self, row, col):
+        row = np.arange(*row.indices(self.shape[0]))
+        return self._get_columnXarray(row, col)
+
+    def _get_columnXarray(self, row, col):
+        # outer indexing
+        row, col = _broadcast_arrays(row[:,None], col)
+        return self._get_arrayXarray(row, col)
+
+    def _get_arrayXarray(self, row, col):
+        # inner indexing
+        i, j = map(np.atleast_2d, _prepare_index_for_memoryview(row, col))
+        new = self._lil_container(i.shape, dtype=self.dtype)
+        _csparsetools.lil_fancy_get(self.shape[0], self.shape[1],
+                                    self.rows, self.data,
+                                    new.rows, new.data,
+                                    i, j)
+        return new
+
+    def _get_row_ranges(self, rows, col_slice):
+        """
+        Fast path for indexing in the case where column index is slice.
+
+        This gains performance improvement over brute force by more
+        efficient skipping of zeros, by accessing the elements
+        column-wise in order.
+
+        Parameters
+        ----------
+        rows : sequence or range
+            Rows indexed. If range, must be within valid bounds.
+        col_slice : slice
+            Columns indexed
+
+        """
+        j_start, j_stop, j_stride = col_slice.indices(self.shape[1])
+        col_range = range(j_start, j_stop, j_stride)
+        nj = len(col_range)
+        new = self._lil_container((len(rows), nj), dtype=self.dtype)
+
+        _csparsetools.lil_get_row_ranges(self.shape[0], self.shape[1],
+                                         self.rows, self.data,
+                                         new.rows, new.data,
+                                         rows,
+                                         j_start, j_stop, j_stride, nj)
+
+        return new
+
+    def _set_intXint(self, row, col, x):
+        _csparsetools.lil_insert(self.shape[0], self.shape[1], self.rows,
+                                 self.data, row, col, x)
+
+    def _set_arrayXarray(self, row, col, x):
+        i, j, x = map(np.atleast_2d, _prepare_index_for_memoryview(row, col, x))
+        _csparsetools.lil_fancy_set(self.shape[0], self.shape[1],
+                                    self.rows, self.data,
+                                    i, j, x)
+
+    def _set_arrayXarray_sparse(self, row, col, x):
+        # Fall back to densifying x
+        x = np.asarray(x.toarray(), dtype=self.dtype)
+        x, _ = _broadcast_arrays(x, row)
+        self._set_arrayXarray(row, col, x)
+
+    def __setitem__(self, key, x):
+        if isinstance(key, tuple) and len(key) == 2:
+            row, col = key
+            # Fast path for simple (int, int) indexing.
+            if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES):
+                x = self.dtype.type(x)
+                if x.size > 1:
+                    raise ValueError("Trying to assign a sequence to an item")
+                return self._set_intXint(row, col, x)
+            # Fast path for full-matrix sparse assignment.
+            if (isinstance(row, slice) and isinstance(col, slice) and
+                    row == slice(None) and col == slice(None) and
+                    issparse(x) and x.shape == self.shape):
+                x = self._lil_container(x, dtype=self.dtype)
+                self.rows = x.rows
+                self.data = x.data
+                return
+        # Everything else takes the normal path.
+        IndexMixin.__setitem__(self, key, x)
+
+    def _mul_scalar(self, other):
+        if other == 0:
+            # Multiply by zero: return the zero matrix
+            new = self._lil_container(self.shape, dtype=self.dtype)
+        else:
+            res_dtype = upcast_scalar(self.dtype, other)
+
+            new = self.copy()
+            new = new.astype(res_dtype)
+            # Multiply this scalar by every element.
+            for j, rowvals in enumerate(new.data):
+                new.data[j] = [val*other for val in rowvals]
+        return new
+
+    def __truediv__(self, other):           # self / other
+        if isscalarlike(other):
+            new = self.copy()
+            new.dtype = np.result_type(self, other)
+            # Divide every element by this scalar
+            for j, rowvals in enumerate(new.data):
+                new.data[j] = [val/other for val in rowvals]
+            return new
+        else:
+            return self.tocsr() / other
+
+    def copy(self):
+        M, N = self.shape
+        new = self._lil_container(self.shape, dtype=self.dtype)
+        # This is ~14x faster than calling deepcopy() on rows and data.
+        _csparsetools.lil_get_row_ranges(M, N, self.rows, self.data,
+                                         new.rows, new.data, range(M),
+                                         0, N, 1, N)
+        return new
+
+    copy.__doc__ = _spbase.copy.__doc__
+
+    def reshape(self, *args, **kwargs):
+        shape = check_shape(args, self.shape)
+        order, copy = check_reshape_kwargs(kwargs)
+
+        # Return early if reshape is not required
+        if shape == self.shape:
+            if copy:
+                return self.copy()
+            else:
+                return self
+
+        new = self._lil_container(shape, dtype=self.dtype)
+
+        if order == 'C':
+            ncols = self.shape[1]
+            for i, row in enumerate(self.rows):
+                for col, j in enumerate(row):
+                    new_r, new_c = np.unravel_index(i * ncols + j, shape)
+                    new[new_r, new_c] = self[i, j]
+        elif order == 'F':
+            nrows = self.shape[0]
+            for i, row in enumerate(self.rows):
+                for col, j in enumerate(row):
+                    new_r, new_c = np.unravel_index(i + j * nrows, shape, order)
+                    new[new_r, new_c] = self[i, j]
+        else:
+            raise ValueError("'order' must be 'C' or 'F'")
+
+        return new
+
+    reshape.__doc__ = _spbase.reshape.__doc__
+
+    def resize(self, *shape):
+        shape = check_shape(shape)
+        new_M, new_N = shape
+        M, N = self.shape
+
+        if new_M < M:
+            self.rows = self.rows[:new_M]
+            self.data = self.data[:new_M]
+        elif new_M > M:
+            self.rows = np.resize(self.rows, new_M)
+            self.data = np.resize(self.data, new_M)
+            for i in range(M, new_M):
+                self.rows[i] = []
+                self.data[i] = []
+
+        if new_N < N:
+            for row, data in zip(self.rows, self.data):
+                trunc = bisect_left(row, new_N)
+                del row[trunc:]
+                del data[trunc:]
+
+        self._shape = shape
+
+    resize.__doc__ = _spbase.resize.__doc__
+
+    def toarray(self, order=None, out=None):
+        d = self._process_toarray_args(order, out)
+        for i, row in enumerate(self.rows):
+            for pos, j in enumerate(row):
+                d[i, j] = self.data[i][pos]
+        return d
+
+    toarray.__doc__ = _spbase.toarray.__doc__
+
+    def transpose(self, axes=None, copy=False):
+        return self.tocsr(copy=copy).transpose(axes=axes, copy=False).tolil(copy=False)
+
+    transpose.__doc__ = _spbase.transpose.__doc__
+
+    def tolil(self, copy=False):
+        if copy:
+            return self.copy()
+        else:
+            return self
+
+    tolil.__doc__ = _spbase.tolil.__doc__
+
+    def tocsr(self, copy=False):
+        M, N = self.shape
+        if M == 0 or N == 0:
+            return self._csr_container((M, N), dtype=self.dtype)
+
+        # construct indptr array
+        if M*N <= np.iinfo(np.int32).max:
+            # fast path: it is known that 64-bit indexing will not be needed.
+            idx_dtype = np.int32
+            indptr = np.empty(M + 1, dtype=idx_dtype)
+            indptr[0] = 0
+            _csparsetools.lil_get_lengths(self.rows, indptr[1:])
+            np.cumsum(indptr, out=indptr)
+            nnz = indptr[-1]
+        else:
+            idx_dtype = self._get_index_dtype(maxval=N)
+            lengths = np.empty(M, dtype=idx_dtype)
+            _csparsetools.lil_get_lengths(self.rows, lengths)
+            nnz = lengths.sum(dtype=np.int64)
+            idx_dtype = self._get_index_dtype(maxval=max(N, nnz))
+            indptr = np.empty(M + 1, dtype=idx_dtype)
+            indptr[0] = 0
+            np.cumsum(lengths, dtype=idx_dtype, out=indptr[1:])
+
+        indices = np.empty(nnz, dtype=idx_dtype)
+        data = np.empty(nnz, dtype=self.dtype)
+        _csparsetools.lil_flatten_to_array(self.rows, indices)
+        _csparsetools.lil_flatten_to_array(self.data, data)
+
+        # init csr matrix
+        return self._csr_container((data, indices, indptr), shape=self.shape)
+
+    tocsr.__doc__ = _spbase.tocsr.__doc__
+
+
+def _prepare_index_for_memoryview(i, j, x=None):
+    """
+    Convert index and data arrays to form suitable for passing to the
+    Cython fancy getset routines.
+
+    The conversions are necessary since to (i) ensure the integer
+    index arrays are in one of the accepted types, and (ii) to ensure
+    the arrays are writable so that Cython memoryview support doesn't
+    choke on them.
+
+    Parameters
+    ----------
+    i, j
+        Index arrays
+    x : optional
+        Data arrays
+
+    Returns
+    -------
+    i, j, x
+        Re-formatted arrays (x is omitted, if input was None)
+
+    """
+    if i.dtype > j.dtype:
+        j = j.astype(i.dtype)
+    elif i.dtype < j.dtype:
+        i = i.astype(j.dtype)
+
+    if not i.flags.writeable or i.dtype not in (np.int32, np.int64):
+        i = i.astype(np.intp)
+    if not j.flags.writeable or j.dtype not in (np.int32, np.int64):
+        j = j.astype(np.intp)
+
+    if x is not None:
+        if not x.flags.writeable:
+            x = x.copy()
+        return i, j, x
+    else:
+        return i, j
+
+
+def isspmatrix_lil(x):
+    """Is `x` of lil_matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a lil matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a lil matrix, False otherwise
+
+    Examples
+    --------
+    >>> from scipy.sparse import lil_array, lil_matrix, coo_matrix, isspmatrix_lil
+    >>> isspmatrix_lil(lil_matrix([[5]]))
+    True
+    >>> isspmatrix_lil(lil_array([[5]]))
+    False
+    >>> isspmatrix_lil(coo_matrix([[5]]))
+    False
+    """
+    return isinstance(x, lil_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class lil_array(_lil_base, sparray):
+    """
+    Row-based LIst of Lists sparse array.
+
+    This is a structure for constructing sparse arrays incrementally.
+    Note that inserting a single item can take linear time in the worst case;
+    to construct the array efficiently, make sure the items are pre-sorted by
+    index, per row.
+
+    This can be instantiated in several ways:
+        lil_array(D)
+            where D is a 2-D ndarray
+
+        lil_array(S)
+            with another sparse array or matrix S (equivalent to S.tolil())
+
+        lil_array((M, N), [dtype])
+            to construct an empty array with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the array
+    shape : 2-tuple
+        Shape of the array
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        LIL format data array of the array
+    rows
+        LIL format row index array of the array
+    T
+
+    Notes
+    -----
+    Sparse arrays can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the LIL format
+        - supports flexible slicing
+        - changes to the array sparsity structure are efficient
+
+    Disadvantages of the LIL format
+        - arithmetic operations LIL + LIL are slow (consider CSR or CSC)
+        - slow column slicing (consider CSC)
+        - slow matrix vector products (consider CSR or CSC)
+
+    Intended Usage
+        - LIL is a convenient format for constructing sparse arrays
+        - once an array has been constructed, convert to CSR or
+          CSC format for fast arithmetic and matrix vector operations
+        - consider using the COO format when constructing large arrays
+
+    Data Structure
+        - An array (``self.rows``) of rows, each of which is a sorted
+          list of column indices of non-zero elements.
+        - The corresponding nonzero values are stored in similar
+          fashion in ``self.data``.
+
+    """
+
+
+class lil_matrix(spmatrix, _lil_base):
+    """
+    Row-based LIst of Lists sparse matrix.
+
+    This is a structure for constructing sparse matrices incrementally.
+    Note that inserting a single item can take linear time in the worst case;
+    to construct the matrix efficiently, make sure the items are pre-sorted by
+    index, per row.
+
+    This can be instantiated in several ways:
+        lil_matrix(D)
+            where D is a 2-D ndarray
+
+        lil_matrix(S)
+            with another sparse array or matrix S (equivalent to S.tolil())
+
+        lil_matrix((M, N), [dtype])
+            to construct an empty matrix with shape (M, N)
+            dtype is optional, defaulting to dtype='d'.
+
+    Attributes
+    ----------
+    dtype : dtype
+        Data type of the matrix
+    shape : 2-tuple
+        Shape of the matrix
+    ndim : int
+        Number of dimensions (this is always 2)
+    nnz
+    size
+    data
+        LIL format data array of the matrix
+    rows
+        LIL format row index array of the matrix
+    T
+
+    Notes
+    -----
+    Sparse matrices can be used in arithmetic operations: they support
+    addition, subtraction, multiplication, division, and matrix power.
+
+    Advantages of the LIL format
+        - supports flexible slicing
+        - changes to the matrix sparsity structure are efficient
+
+    Disadvantages of the LIL format
+        - arithmetic operations LIL + LIL are slow (consider CSR or CSC)
+        - slow column slicing (consider CSC)
+        - slow matrix vector products (consider CSR or CSC)
+
+    Intended Usage
+        - LIL is a convenient format for constructing sparse matrices
+        - once a matrix has been constructed, convert to CSR or
+          CSC format for fast arithmetic and matrix vector operations
+        - consider using the COO format when constructing large matrices
+
+    Data Structure
+        - An array (``self.rows``) of rows, each of which is a sorted
+          list of column indices of non-zero elements.
+        - The corresponding nonzero values are stored in similar
+          fashion in ``self.data``.
+
+    """
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_matrix.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..351660ba389ea7f2adf2576e350e840783d894fa
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_matrix.py
@@ -0,0 +1,146 @@
+class spmatrix:
+    """This class provides a base class for all sparse matrix classes.
+
+    It cannot be instantiated.  Most of the work is provided by subclasses.
+    """
+    _allow_nd = (2,)
+
+    @property
+    def _bsr_container(self):
+        from ._bsr import bsr_matrix
+        return bsr_matrix
+
+    @property
+    def _coo_container(self):
+        from ._coo import coo_matrix
+        return coo_matrix
+
+    @property
+    def _csc_container(self):
+        from ._csc import csc_matrix
+        return csc_matrix
+
+    @property
+    def _csr_container(self):
+        from ._csr import csr_matrix
+        return csr_matrix
+
+    @property
+    def _dia_container(self):
+        from ._dia import dia_matrix
+        return dia_matrix
+
+    @property
+    def _dok_container(self):
+        from ._dok import dok_matrix
+        return dok_matrix
+
+    @property
+    def _lil_container(self):
+        from ._lil import lil_matrix
+        return lil_matrix
+
+    # Restore matrix multiplication
+    def __mul__(self, other):
+        return self._matmul_dispatch(other)
+
+    def __rmul__(self, other):
+        return self._rmatmul_dispatch(other)
+
+    # Restore matrix power
+    def __pow__(self, power):
+        from .linalg import matrix_power
+
+        return matrix_power(self, power)
+
+    ## Backward compatibility
+
+    def set_shape(self, shape):
+        """Set the shape of the matrix in-place"""
+        # Make sure copy is False since this is in place
+        # Make sure format is unchanged because we are doing a __dict__ swap
+        new_self = self.reshape(shape, copy=False).asformat(self.format)
+        self.__dict__ = new_self.__dict__
+
+    def get_shape(self):
+        """Get the shape of the matrix"""
+        return self._shape
+
+    shape = property(fget=get_shape, fset=set_shape,
+                     doc="Shape of the matrix")
+
+    def asfptype(self):
+        """Upcast matrix to a floating point format (if necessary)"""
+        return self._asfptype()
+
+    def getmaxprint(self):
+        """Maximum number of elements to display when printed."""
+        return self._getmaxprint()
+
+    def getformat(self):
+        """Matrix storage format"""
+        return self.format
+
+    def getnnz(self, axis=None):
+        """Number of stored values, including explicit zeros.
+
+        Parameters
+        ----------
+        axis : None, 0, or 1
+            Select between the number of values across the whole array, in
+            each column, or in each row.
+        """
+        return self._getnnz(axis=axis)
+
+    def getH(self):
+        """Return the Hermitian transpose of this matrix.
+
+        See Also
+        --------
+        numpy.matrix.getH : NumPy's implementation of `getH` for matrices
+        """
+        return self.conjugate().transpose()
+
+    def getcol(self, j):
+        """Returns a copy of column j of the matrix, as an (m x 1) sparse
+        matrix (column vector).
+        """
+        return self._getcol(j)
+
+    def getrow(self, i):
+        """Returns a copy of row i of the matrix, as a (1 x n) sparse
+        matrix (row vector).
+        """
+        return self._getrow(i)
+
+    def todense(self, order=None, out=None):
+        """
+        Return a dense representation of this sparse matrix.
+
+        Parameters
+        ----------
+        order : {'C', 'F'}, optional
+            Whether to store multi-dimensional data in C (row-major)
+            or Fortran (column-major) order in memory. The default
+            is 'None', which provides no ordering guarantees.
+            Cannot be specified in conjunction with the `out`
+            argument.
+
+        out : ndarray, 2-D, optional
+            If specified, uses this array (or `numpy.matrix`) as the
+            output buffer instead of allocating a new array to
+            return. The provided array must have the same shape and
+            dtype as the sparse matrix on which you are calling the
+            method.
+
+        Returns
+        -------
+        arr : numpy.matrix, 2-D
+            A NumPy matrix object with the same shape and containing
+            the same data represented by the sparse matrix, with the
+            requested memory order. If `out` was passed and was an
+            array (rather than a `numpy.matrix`), it will be filled
+            with the appropriate values and returned wrapped in a
+            `numpy.matrix` object that shares the same memory.
+        """
+        return super().todense(order, out)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b7f533926fd415a379cb08420b4a65a14baeb43
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_matrix_io.py
@@ -0,0 +1,167 @@
+import numpy as np
+import scipy as sp
+
+__all__ = ['save_npz', 'load_npz']
+
+
+# Make loading safe vs. malicious input
+PICKLE_KWARGS = dict(allow_pickle=False)
+
+
+def save_npz(file, matrix, compressed=True):
+    """ Save a sparse matrix or array to a file using ``.npz`` format.
+
+    Parameters
+    ----------
+    file : str or file-like object
+        Either the file name (string) or an open file (file-like object)
+        where the data will be saved. If file is a string, the ``.npz``
+        extension will be appended to the file name if it is not already
+        there.
+    matrix: spmatrix or sparray
+        The sparse matrix or array to save.
+        Supported formats: ``csc``, ``csr``, ``bsr``, ``dia`` or ``coo``.
+    compressed : bool, optional
+        Allow compressing the file. Default: True
+
+    See Also
+    --------
+    scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format.
+    numpy.savez: Save several arrays into a ``.npz`` archive.
+    numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive.
+
+    Examples
+    --------
+    Store sparse matrix to disk, and load it again:
+
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
+    >>> sparse_matrix
+    
+    >>> sparse_matrix.toarray()
+    array([[0, 0, 3],
+           [4, 0, 0]], dtype=int64)
+
+    >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
+    >>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
+
+    >>> sparse_matrix
+    
+    >>> sparse_matrix.toarray()
+    array([[0, 0, 3],
+           [4, 0, 0]], dtype=int64)
+    """
+    arrays_dict = {}
+    if matrix.format in ('csc', 'csr', 'bsr'):
+        arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr)
+    elif matrix.format == 'dia':
+        arrays_dict.update(offsets=matrix.offsets)
+    elif matrix.format == 'coo':
+        arrays_dict.update(row=matrix.row, col=matrix.col)
+    else:
+        msg = f'Save is not implemented for sparse matrix of format {matrix.format}.'
+        raise NotImplementedError(msg)
+    arrays_dict.update(
+        format=matrix.format.encode('ascii'),
+        shape=matrix.shape,
+        data=matrix.data
+    )
+    if isinstance(matrix, sp.sparse.sparray):
+        arrays_dict.update(_is_array=True)
+    if compressed:
+        np.savez_compressed(file, **arrays_dict)
+    else:
+        np.savez(file, **arrays_dict)
+
+
+def load_npz(file):
+    """ Load a sparse array/matrix from a file using ``.npz`` format.
+
+    Parameters
+    ----------
+    file : str or file-like object
+        Either the file name (string) or an open file (file-like object)
+        where the data will be loaded.
+
+    Returns
+    -------
+    result : csc_array, csr_array, bsr_array, dia_array or coo_array
+        A sparse array/matrix containing the loaded data.
+
+    Raises
+    ------
+    OSError
+        If the input file does not exist or cannot be read.
+
+    See Also
+    --------
+    scipy.sparse.save_npz: Save a sparse array/matrix to a file using ``.npz`` format.
+    numpy.load: Load several arrays from a ``.npz`` archive.
+
+    Examples
+    --------
+    Store sparse array/matrix to disk, and load it again:
+
+    >>> import numpy as np
+    >>> import scipy as sp
+    >>> sparse_array = sp.sparse.csc_array([[0, 0, 3], [4, 0, 0]])
+    >>> sparse_array
+    
+    >>> sparse_array.toarray()
+    array([[0, 0, 3],
+           [4, 0, 0]], dtype=int64)
+
+    >>> sp.sparse.save_npz('/tmp/sparse_array.npz', sparse_array)
+    >>> sparse_array = sp.sparse.load_npz('/tmp/sparse_array.npz')
+
+    >>> sparse_array
+    
+    >>> sparse_array.toarray()
+    array([[0, 0, 3],
+           [4, 0, 0]], dtype=int64)
+
+    In this example we force the result to be csr_array from csr_matrix
+    >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
+    >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
+    >>> tmp = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
+    >>> sparse_array = sp.sparse.csr_array(tmp)
+    """
+    with np.load(file, **PICKLE_KWARGS) as loaded:
+        sparse_format = loaded.get('format')
+        if sparse_format is None:
+            raise ValueError(f'The file {file} does not contain '
+                             f'a sparse array or matrix.')
+        sparse_format = sparse_format.item()
+
+        if not isinstance(sparse_format, str):
+            # Play safe with Python 2 vs 3 backward compatibility;
+            # files saved with SciPy < 1.0.0 may contain unicode or bytes.
+            sparse_format = sparse_format.decode('ascii')
+
+        if loaded.get('_is_array'):
+            sparse_type = sparse_format + '_array'
+        else:
+            sparse_type = sparse_format + '_matrix'
+
+        try:
+            cls = getattr(sp.sparse, f'{sparse_type}')
+        except AttributeError as e:
+            raise ValueError(f'Unknown format "{sparse_type}"') from e
+
+        if sparse_format in ('csc', 'csr', 'bsr'):
+            return cls((loaded['data'], loaded['indices'], loaded['indptr']),
+                       shape=loaded['shape'])
+        elif sparse_format == 'dia':
+            return cls((loaded['data'], loaded['offsets']),
+                       shape=loaded['shape'])
+        elif sparse_format == 'coo':
+            return cls((loaded['data'], (loaded['row'], loaded['col'])),
+                       shape=loaded['shape'])
+        else:
+            raise NotImplementedError(f'Load is not implemented for '
+                                      f'sparse matrix of format {sparse_format}.')
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e9b0abcede6387e74538baf839a303c6cc1b6be
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_spfuncs.py
@@ -0,0 +1,76 @@
+""" Functions that operate on sparse matrices
+"""
+
+__all__ = ['count_blocks','estimate_blocksize']
+
+from ._base import issparse
+from ._csr import csr_array
+from ._sparsetools import csr_count_blocks
+
+
+def estimate_blocksize(A,efficiency=0.7):
+    """Attempt to determine the blocksize of a sparse matrix
+
+    Returns a blocksize=(r,c) such that
+        - A.nnz / A.tobsr( (r,c) ).nnz > efficiency
+    """
+    if not (issparse(A) and A.format in ("csc", "csr")):
+        A = csr_array(A)
+
+    if A.nnz == 0:
+        return (1,1)
+
+    if not 0 < efficiency < 1.0:
+        raise ValueError('efficiency must satisfy 0.0 < efficiency < 1.0')
+
+    high_efficiency = (1.0 + efficiency) / 2.0
+    nnz = float(A.nnz)
+    M,N = A.shape
+
+    if M % 2 == 0 and N % 2 == 0:
+        e22 = nnz / (4 * count_blocks(A,(2,2)))
+    else:
+        e22 = 0.0
+
+    if M % 3 == 0 and N % 3 == 0:
+        e33 = nnz / (9 * count_blocks(A,(3,3)))
+    else:
+        e33 = 0.0
+
+    if e22 > high_efficiency and e33 > high_efficiency:
+        e66 = nnz / (36 * count_blocks(A,(6,6)))
+        if e66 > efficiency:
+            return (6,6)
+        else:
+            return (3,3)
+    else:
+        if M % 4 == 0 and N % 4 == 0:
+            e44 = nnz / (16 * count_blocks(A,(4,4)))
+        else:
+            e44 = 0.0
+
+        if e44 > efficiency:
+            return (4,4)
+        elif e33 > efficiency:
+            return (3,3)
+        elif e22 > efficiency:
+            return (2,2)
+        else:
+            return (1,1)
+
+
+def count_blocks(A,blocksize):
+    """For a given blocksize=(r,c) count the number of occupied
+    blocks in a sparse matrix A
+    """
+    r,c = blocksize
+    if r < 1 or c < 1:
+        raise ValueError('r and c must be positive')
+
+    if issparse(A):
+        if A.format == "csr":
+            M,N = A.shape
+            return csr_count_blocks(M,N,r,c,A.indptr,A.indices)
+        elif A.format == "csc":
+            return count_blocks(A.T,(c,r))
+    return count_blocks(csr_array(A),blocksize)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_sputils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_sputils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fb5b5fc6c2e37d0c61dd3a3aa0aa382c7486a03
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/_sputils.py
@@ -0,0 +1,617 @@
+""" Utility functions for sparse matrix module
+"""
+
+import sys
+from typing import Any, Literal, Union
+import operator
+import numpy as np
+from math import prod
+import scipy.sparse as sp
+from scipy._lib._util import np_long, np_ulong
+
+
+__all__ = ['upcast', 'getdtype', 'getdata', 'isscalarlike', 'isintlike',
+           'isshape', 'issequence', 'isdense', 'ismatrix', 'get_sum_dtype',
+           'broadcast_shapes']
+
+supported_dtypes = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc,
+                    np.uintc, np_long, np_ulong, np.longlong, np.ulonglong,
+                    np.float32, np.float64, np.longdouble,
+                    np.complex64, np.complex128, np.clongdouble]
+
+_upcast_memo = {}
+
+
+def upcast(*args):
+    """Returns the nearest supported sparse dtype for the
+    combination of one or more types.
+
+    upcast(t0, t1, ..., tn) -> T  where T is a supported dtype
+
+    Examples
+    --------
+    >>> from scipy.sparse._sputils import upcast
+    >>> upcast('int32')
+    
+    >>> upcast('bool')
+    
+    >>> upcast('int32','float32')
+    
+    >>> upcast('bool',complex,float)
+    
+
+    """
+
+    t = _upcast_memo.get(hash(args))
+    if t is not None:
+        return t
+
+    upcast = np.result_type(*args)
+
+    for t in supported_dtypes:
+        if np.can_cast(upcast, t):
+            _upcast_memo[hash(args)] = t
+            return t
+
+    raise TypeError(f'no supported conversion for types: {args!r}')
+
+
+def upcast_char(*args):
+    """Same as `upcast` but taking dtype.char as input (faster)."""
+    t = _upcast_memo.get(args)
+    if t is not None:
+        return t
+    t = upcast(*map(np.dtype, args))
+    _upcast_memo[args] = t
+    return t
+
+
+def upcast_scalar(dtype, scalar):
+    """Determine data type for binary operation between an array of
+    type `dtype` and a scalar.
+    """
+    return (np.array([0], dtype=dtype) * scalar).dtype
+
+
+def downcast_intp_index(arr):
+    """
+    Down-cast index array to np.intp dtype if it is of a larger dtype.
+
+    Raise an error if the array contains a value that is too large for
+    intp.
+    """
+    if arr.dtype.itemsize > np.dtype(np.intp).itemsize:
+        if arr.size == 0:
+            return arr.astype(np.intp)
+        maxval = arr.max()
+        minval = arr.min()
+        if maxval > np.iinfo(np.intp).max or minval < np.iinfo(np.intp).min:
+            raise ValueError("Cannot deal with arrays with indices larger "
+                             "than the machine maximum address size "
+                             "(e.g. 64-bit indices on 32-bit machine).")
+        return arr.astype(np.intp)
+    return arr
+
+
+def to_native(A):
+    """
+    Ensure that the data type of the NumPy array `A` has native byte order.
+
+    `A` must be a NumPy array.  If the data type of `A` does not have native
+    byte order, a copy of `A` with a native byte order is returned. Otherwise
+    `A` is returned.
+    """
+    dt = A.dtype
+    if dt.isnative:
+        # Don't call `asarray()` if A is already native, to avoid unnecessarily
+        # creating a view of the input array.
+        return A
+    return np.asarray(A, dtype=dt.newbyteorder('native'))
+
+
+def getdtype(dtype, a=None, default=None):
+    """Form a supported numpy dtype based on input arguments.
+
+    Returns a valid ``numpy.dtype`` from `dtype` if not None,
+    or else ``a.dtype`` if possible, or else the given `default`
+    if not None, or else raise a ``TypeError``.
+
+    The resulting ``dtype`` must be in ``supported_dtypes``:
+        bool_, int8, uint8, int16, uint16, int32, uint32,
+        int64, uint64, longlong, ulonglong, float32, float64,
+        longdouble, complex64, complex128, clongdouble
+    """
+    if dtype is None:
+        try:
+            newdtype = a.dtype
+        except AttributeError as e:
+            if default is not None:
+                newdtype = np.dtype(default)
+            else:
+                raise TypeError("could not interpret data type") from e
+    else:
+        newdtype = np.dtype(dtype)
+
+    if newdtype not in supported_dtypes:
+        supported_dtypes_fmt = ", ".join(t.__name__ for t in supported_dtypes)
+        raise ValueError(f"scipy.sparse does not support dtype {newdtype.name}. "
+                         f"The only supported types are: {supported_dtypes_fmt}.")
+    return newdtype
+
+
+def getdata(obj, dtype=None, copy=False) -> np.ndarray:
+    """
+    This is a wrapper of `np.array(obj, dtype=dtype, copy=copy)`
+    that will generate a warning if the result is an object array.
+    """
+    data = np.array(obj, dtype=dtype, copy=copy)
+    # Defer to getdtype for checking that the dtype is OK.
+    # This is called for the validation only; we don't need the return value.
+    getdtype(data.dtype)
+    return data
+
+
+def safely_cast_index_arrays(A, idx_dtype=np.int32, msg=""):
+    """Safely cast sparse array indices to `idx_dtype`.
+
+    Check the shape of `A` to determine if it is safe to cast its index
+    arrays to dtype `idx_dtype`. If any dimension in shape is larger than
+    fits in the dtype, casting is unsafe so raise ``ValueError``.
+    If safe, cast the index arrays to `idx_dtype` and return the result
+    without changing the input `A`. The caller can assign results to `A`
+    attributes if desired or use the recast index arrays directly.
+
+    Unless downcasting is needed, the original index arrays are returned.
+    You can test e.g. ``A.indptr is new_indptr`` to see if downcasting occurred.
+
+    .. versionadded:: 1.15.0
+
+    Parameters
+    ----------
+    A : sparse array or matrix
+        The array for which index arrays should be downcast.
+    idx_dtype : dtype
+        Desired dtype. Should be an integer dtype (default: ``np.int32``).
+        Most of scipy.sparse uses either int64 or int32.
+    msg : string, optional
+        A string to be added to the end of the ValueError message
+        if the array shape is too big to fit in `idx_dtype`.
+        The error message is ``f" values too large for {msg}"``
+        It should indicate why the downcasting is needed, e.g. "SuperLU",
+        and defaults to f"dtype {idx_dtype}".
+
+    Returns
+    -------
+    idx_arrays : ndarray or tuple of ndarrays
+        Based on ``A.format``, index arrays are returned after casting to `idx_dtype`.
+        For CSC/CSR, returns ``(indices, indptr)``.
+        For COO, returns ``coords``.
+        For DIA, returns ``offsets``.
+        For BSR, returns ``(indices, indptr)``.
+
+    Raises
+    ------
+    ValueError
+        If the array has shape that would not fit in the new dtype, or if
+        the sparse format does not use index arrays.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import sparse
+    >>> data = [3]
+    >>> coords = (np.array([3]), np.array([1]))  # Note: int64 arrays
+    >>> A = sparse.coo_array((data, coords))
+    >>> A.coords[0].dtype
+    dtype('int64')
+
+    >>> # rescast after construction, raising exception if shape too big
+    >>> coords = sparse.safely_cast_index_arrays(A, np.int32)
+    >>> A.coords[0] is coords[0]  # False if casting is needed
+    False
+    >>> A.coords = coords  # set the index dtype of A
+    >>> A.coords[0].dtype
+    dtype('int32')
+    """
+    if not msg:
+        msg = f"dtype {idx_dtype}"
+    # check for safe downcasting
+    max_value = np.iinfo(idx_dtype).max
+
+    if A.format in ("csc", "csr"):
+        # indptr[-1] is max b/c indptr always sorted
+        if A.indptr[-1] > max_value:
+            raise ValueError(f"indptr values too large for {msg}")
+
+        # check shape vs dtype
+        if max(*A.shape) > max_value:
+            if (A.indices > max_value).any():
+                raise ValueError(f"indices values too large for {msg}")
+
+        indices = A.indices.astype(idx_dtype, copy=False)
+        indptr = A.indptr.astype(idx_dtype, copy=False)
+        return indices, indptr
+
+    elif A.format == "coo":
+        if max(*A.shape) > max_value:
+            if any((co > max_value).any() for co in A.coords):
+                raise ValueError(f"coords values too large for {msg}")
+        return tuple(co.astype(idx_dtype, copy=False) for co in A.coords)
+
+    elif A.format == "dia":
+        if max(*A.shape) > max_value:
+            if (A.offsets > max_value).any():
+                raise ValueError(f"offsets values too large for {msg}")
+        offsets = A.offsets.astype(idx_dtype, copy=False)
+        return offsets
+
+    elif A.format == 'bsr':
+        R, C = A.blocksize
+        if A.indptr[-1] * R > max_value:
+            raise ValueError("indptr values too large for {msg}")
+        if max(*A.shape) > max_value:
+            if (A.indices * C > max_value).any():
+                raise ValueError(f"indices values too large for {msg}")
+        indices = A.indices.astype(idx_dtype, copy=False)
+        indptr = A.indptr.astype(idx_dtype, copy=False)
+        return indices, indptr
+
+    else:
+        raise TypeError(f'Format {A.format} is not associated with index arrays. '
+                        'DOK and LIL have dict and list, not array.')
+
+
+def get_index_dtype(arrays=(), maxval=None, check_contents=False):
+    """
+    Based on input (integer) arrays `a`, determine a suitable index data
+    type that can hold the data in the arrays.
+
+    Parameters
+    ----------
+    arrays : tuple of array_like
+        Input arrays whose types/contents to check
+    maxval : float, optional
+        Maximum value needed
+    check_contents : bool, optional
+        Whether to check the values in the arrays and not just their types.
+        Default: False (check only the types)
+
+    Returns
+    -------
+    dtype : dtype
+        Suitable index data type (int32 or int64)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import sparse
+    >>> # select index dtype based on shape
+    >>> shape = (3, 3)
+    >>> idx_dtype = sparse.get_index_dtype(maxval=max(shape))
+    >>> data = [1.1, 3.0, 1.5]
+    >>> indices = np.array([0, 1, 0], dtype=idx_dtype)
+    >>> indptr = np.array([0, 2, 3, 3], dtype=idx_dtype)
+    >>> A = sparse.csr_array((data, indices, indptr), shape=shape)
+    >>> A.indptr.dtype
+    dtype('int32')
+
+    >>> # select based on larger of existing arrays and shape
+    >>> shape = (3, 3)
+    >>> idx_dtype = sparse.get_index_dtype(A.indptr, maxval=max(shape))
+    >>> idx_dtype
+    
+    """
+    # not using intc directly due to misinteractions with pythran
+    if np.intc().itemsize != 4:
+        return np.int64
+
+    int32min = np.int32(np.iinfo(np.int32).min)
+    int32max = np.int32(np.iinfo(np.int32).max)
+
+    if maxval is not None:
+        maxval = np.int64(maxval)
+        if maxval > int32max:
+            return np.int64
+
+    if isinstance(arrays, np.ndarray):
+        arrays = (arrays,)
+
+    for arr in arrays:
+        arr = np.asarray(arr)
+        if not np.can_cast(arr.dtype, np.int32):
+            if check_contents:
+                if arr.size == 0:
+                    # a bigger type not needed
+                    continue
+                elif np.issubdtype(arr.dtype, np.integer):
+                    maxval = arr.max()
+                    minval = arr.min()
+                    if minval >= int32min and maxval <= int32max:
+                        # a bigger type not needed
+                        continue
+            return np.int64
+    return np.int32
+
+
+def get_sum_dtype(dtype: np.dtype) -> np.dtype:
+    """Mimic numpy's casting for np.sum"""
+    if dtype.kind == 'u' and np.can_cast(dtype, np.uint):
+        return np.uint
+    if np.can_cast(dtype, np.int_):
+        return np.int_
+    return dtype
+
+
+def isscalarlike(x) -> bool:
+    """Is x either a scalar, an array scalar, or a 0-dim array?"""
+    return np.isscalar(x) or (isdense(x) and x.ndim == 0)
+
+
+def isintlike(x) -> bool:
+    """Is x appropriate as an index into a sparse matrix? Returns True
+    if it can be cast safely to a machine int.
+    """
+    # Fast-path check to eliminate non-scalar values. operator.index would
+    # catch this case too, but the exception catching is slow.
+    if np.ndim(x) != 0:
+        return False
+    try:
+        operator.index(x)
+    except (TypeError, ValueError):
+        try:
+            loose_int = bool(int(x) == x)
+        except (TypeError, ValueError):
+            return False
+        if loose_int:
+            msg = "Inexact indices into sparse matrices are not allowed"
+            raise ValueError(msg)
+        return loose_int
+    return True
+
+
+def isshape(x, nonneg=False, *, allow_nd=(2,)) -> bool:
+    """Is x a valid tuple of dimensions?
+
+    If nonneg, also checks that the dimensions are non-negative.
+    Shapes of length in the tuple allow_nd are allowed.
+    """
+    ndim = len(x)
+    if ndim not in allow_nd:
+        return False
+
+    for d in x:
+        if not isintlike(d):
+            return False
+        if nonneg and d < 0:
+            return False
+    return True
+
+
+def issequence(t) -> bool:
+    return ((isinstance(t, list | tuple) and
+            (len(t) == 0 or np.isscalar(t[0]))) or
+            (isinstance(t, np.ndarray) and (t.ndim == 1)))
+
+
+def ismatrix(t) -> bool:
+    return ((isinstance(t, list | tuple) and
+             len(t) > 0 and issequence(t[0])) or
+            (isinstance(t, np.ndarray) and t.ndim == 2))
+
+
+def isdense(x) -> bool:
+    return isinstance(x, np.ndarray)
+
+
+def validateaxis(axis) -> None:
+    if axis is None:
+        return
+    axis_type = type(axis)
+
+    # In NumPy, you can pass in tuples for 'axis', but they are
+    # not very useful for sparse matrices given their limited
+    # dimensions, so let's make it explicit that they are not
+    # allowed to be passed in
+    if isinstance(axis, tuple):
+        raise TypeError("Tuples are not accepted for the 'axis' parameter. "
+                        "Please pass in one of the following: "
+                        "{-2, -1, 0, 1, None}.")
+
+    # If not a tuple, check that the provided axis is actually
+    # an integer and raise a TypeError similar to NumPy's
+    if not np.issubdtype(np.dtype(axis_type), np.integer):
+        raise TypeError(f"axis must be an integer, not {axis_type.__name__}")
+
+    if not (-2 <= axis <= 1):
+        raise ValueError("axis out of range")
+
+
+def check_shape(args, current_shape=None, *, allow_nd=(2,)) -> tuple[int, ...]:
+    """Imitate numpy.matrix handling of shape arguments
+
+    Parameters
+    ----------
+    args : array_like
+        Data structures providing information about the shape of the sparse array.
+    current_shape : tuple, optional
+        The current shape of the sparse array or matrix.
+        If None (default), the current shape will be inferred from args.
+    allow_nd : tuple of ints, optional default: (2,)
+        If shape does not have a length in the tuple allow_nd an error is raised.
+
+    Returns
+    -------
+    new_shape: tuple
+        The new shape after validation.
+    """
+    if len(args) == 0:
+        raise TypeError("function missing 1 required positional argument: 'shape'")
+    if len(args) == 1:
+        try:
+            shape_iter = iter(args[0])
+        except TypeError:
+            new_shape = (operator.index(args[0]), )
+        else:
+            new_shape = tuple(operator.index(arg) for arg in shape_iter)
+    else:
+        new_shape = tuple(operator.index(arg) for arg in args)
+
+    if current_shape is None:
+        if len(new_shape) not in allow_nd:
+            raise ValueError(f'shape must have length in {allow_nd}. Got {new_shape=}')
+        if any(d < 0 for d in new_shape):
+            raise ValueError("'shape' elements cannot be negative")
+    else:
+        # Check the current size only if needed
+        current_size = prod(current_shape)
+
+        # Check for negatives
+        negative_indexes = [i for i, x in enumerate(new_shape) if x < 0]
+        if not negative_indexes:
+            new_size = prod(new_shape)
+            if new_size != current_size:
+                raise ValueError(f'cannot reshape array of size {current_size}'
+                                 f' into shape {new_shape}')
+        elif len(negative_indexes) == 1:
+            skip = negative_indexes[0]
+            specified = prod(new_shape[:skip] + new_shape[skip+1:])
+            unspecified, remainder = divmod(current_size, specified)
+            if remainder != 0:
+                err_shape = tuple('newshape' if x < 0 else x for x in new_shape)
+                raise ValueError(f'cannot reshape array of size {current_size}'
+                                 f' into shape {err_shape}')
+            new_shape = new_shape[:skip] + (unspecified,) + new_shape[skip+1:]
+        else:
+            raise ValueError('can only specify one unknown dimension')
+
+    if len(new_shape) not in allow_nd:
+        raise ValueError(f'shape must have length in {allow_nd}. Got {new_shape=}')
+
+    return new_shape
+
+
+def broadcast_shapes(*shapes):
+    """Check if shapes can be broadcast and return resulting shape
+
+    This is similar to the NumPy ``broadcast_shapes`` function but
+    does not check memory consequences of the resulting dense matrix.
+
+    Parameters
+    ----------
+    *shapes : tuple of shape tuples
+        The tuple of shapes to be considered for broadcasting.
+        Shapes should be tuples of non-negative integers.
+
+    Returns
+    -------
+    new_shape : tuple of integers
+        The shape that results from broadcasting th input shapes.
+    """
+    if not shapes:
+        return ()
+    shapes = [shp if isinstance(shp, (tuple, list)) else (shp,) for shp in shapes]
+    big_shp = max(shapes, key=len)
+    out = list(big_shp)
+    for shp in shapes:
+        if shp is big_shp:
+            continue
+        for i, x in enumerate(shp, start=-len(shp)):
+            if x != 1 and x != out[i]:
+                if out[i] != 1:
+                    raise ValueError("shapes cannot be broadcast to a single shape.")
+                out[i] = x
+    return (*out,)
+
+
+def check_reshape_kwargs(kwargs):
+    """Unpack keyword arguments for reshape function.
+
+    This is useful because keyword arguments after star arguments are not
+    allowed in Python 2, but star keyword arguments are. This function unpacks
+    'order' and 'copy' from the star keyword arguments (with defaults) and
+    throws an error for any remaining.
+    """
+
+    order = kwargs.pop('order', 'C')
+    copy = kwargs.pop('copy', False)
+    if kwargs:  # Some unused kwargs remain
+        raise TypeError("reshape() got unexpected keywords arguments: "
+                        f"{', '.join(kwargs.keys())}")
+    return order, copy
+
+
+def is_pydata_spmatrix(m) -> bool:
+    """
+    Check whether object is pydata/sparse matrix, avoiding importing the module.
+    """
+    base_cls = getattr(sys.modules.get('sparse'), 'SparseArray', None)
+    return base_cls is not None and isinstance(m, base_cls)
+
+
+def convert_pydata_sparse_to_scipy(
+    arg: Any,
+    target_format: None | Literal["csc", "csr"] = None,
+    accept_fv: Any = None,
+) -> Union[Any, "sp.spmatrix"]:
+    """
+    Convert a pydata/sparse array to scipy sparse matrix,
+    pass through anything else.
+    """
+    if is_pydata_spmatrix(arg):
+        # The `accept_fv` keyword is new in PyData Sparse 0.15.4 (May 2024),
+        # remove the `except` once the minimum supported version is >=0.15.4
+        try:
+            arg = arg.to_scipy_sparse(accept_fv=accept_fv)
+        except TypeError:
+            arg = arg.to_scipy_sparse()
+        if target_format is not None:
+            arg = arg.asformat(target_format)
+        elif arg.format not in ("csc", "csr"):
+            arg = arg.tocsc()
+    return arg
+
+
+###############################################################################
+# Wrappers for NumPy types that are deprecated
+
+# Numpy versions of these functions raise deprecation warnings, the
+# ones below do not.
+
+def matrix(*args, **kwargs):
+    return np.array(*args, **kwargs).view(np.matrix)
+
+
+def asmatrix(data, dtype=None):
+    if isinstance(data, np.matrix) and (dtype is None or data.dtype == dtype):
+        return data
+    return np.asarray(data, dtype=dtype).view(np.matrix)
+
+###############################################################################
+
+
+def _todata(s) -> np.ndarray:
+    """Access nonzero values, possibly after summing duplicates.
+
+    Parameters
+    ----------
+    s : sparse array
+        Input sparse array.
+
+    Returns
+    -------
+    data: ndarray
+      Nonzero values of the array, with shape (s.nnz,)
+
+    """
+    if isinstance(s, sp._data._data_matrix):
+        return s._deduped_data()
+
+    if isinstance(s, sp.dok_array):
+        return np.fromiter(s.values(), dtype=s.dtype, count=s.nnz)
+
+    if isinstance(s, sp.lil_array):
+        data = np.empty(s.nnz, dtype=s.dtype)
+        sp._csparsetools.lil_flatten_to_array(s.data, data)
+        return data
+
+    return s.tocoo()._deduped_data()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/base.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0a427e4570e07cc71e9e45bf98c7cf61798125b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/base.py
@@ -0,0 +1,33 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'MAXPRINT',
+    'SparseEfficiencyWarning',
+    'SparseFormatWarning',
+    'SparseWarning',
+    'asmatrix',
+    'check_reshape_kwargs',
+    'check_shape',
+    'get_sum_dtype',
+    'isdense',
+    'isscalarlike',
+    'issparse',
+    'isspmatrix',
+    'spmatrix',
+    'validateaxis',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="base",
+                                   private_modules=["_base"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/bsr.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/bsr.py
new file mode 100644
index 0000000000000000000000000000000000000000..c686301a78fc3e2221600eb06035a5cb12898cdb
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/bsr.py
@@ -0,0 +1,36 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'bsr_matmat',
+    'bsr_matrix',
+    'bsr_matvec',
+    'bsr_matvecs',
+    'bsr_sort_indices',
+    'bsr_tocsr',
+    'bsr_transpose',
+    'check_shape',
+    'csr_matmat_maxnnz',
+    'getdata',
+    'getdtype',
+    'isshape',
+    'isspmatrix_bsr',
+    'spmatrix',
+    'to_native',
+    'upcast',
+    'warn',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="bsr",
+                                   private_modules=["_bsr"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/compressed.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/compressed.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6dc8a73e5ab527cfe0b73d558dae25047cfb98b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/compressed.py
@@ -0,0 +1,43 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'IndexMixin',
+    'SparseEfficiencyWarning',
+    'check_shape',
+    'csr_column_index1',
+    'csr_column_index2',
+    'csr_row_index',
+    'csr_row_slice',
+    'csr_sample_offsets',
+    'csr_sample_values',
+    'csr_todense',
+    'downcast_intp_index',
+    'get_csr_submatrix',
+    'get_sum_dtype',
+    'getdtype',
+    'is_pydata_spmatrix',
+    'isdense',
+    'isintlike',
+    'isscalarlike',
+    'isshape',
+    'operator',
+    'to_native',
+    'upcast',
+    'upcast_char',
+    'warn',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="compressed",
+                                   private_modules=["_compressed"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/construct.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3d34d2fd38887877980727bceaaa215129bf283
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/construct.py
@@ -0,0 +1,44 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'block_diag',
+    'bmat',
+    'bsr_matrix',
+    'check_random_state',
+    'coo_matrix',
+    'csc_matrix',
+    'csr_hstack',
+    'csr_matrix',
+    'dia_matrix',
+    'diags',
+    'eye',
+    'get_index_dtype',
+    'hstack',
+    'identity',
+    'isscalarlike',
+    'issparse',
+    'kron',
+    'kronsum',
+    'numbers',
+    'rand',
+    'random',
+    'rng_integers',
+    'spdiags',
+    'upcast',
+    'vstack',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="construct",
+                                   private_modules=["_construct"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/coo.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..bda2da3d09a676ab79739331a21ba26102bb90ae
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/coo.py
@@ -0,0 +1,37 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'SparseEfficiencyWarning',
+    'check_reshape_kwargs',
+    'check_shape',
+    'coo_matrix',
+    'coo_matvec',
+    'coo_tocsr',
+    'coo_todense',
+    'downcast_intp_index',
+    'getdata',
+    'getdtype',
+    'isshape',
+    'isspmatrix_coo',
+    'operator',
+    'spmatrix',
+    'to_native',
+    'upcast',
+    'upcast_char',
+    'warn',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="coo",
+                                   private_modules=["_coo"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csc.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..d140b841e0724155f8602a4215836e2c8a7fad72
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csc.py
@@ -0,0 +1,25 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'csc_matrix',
+    'csc_tocsr',
+    'expandptr',
+    'isspmatrix_csc',
+    'spmatrix',
+    'upcast',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="csc",
+                                   private_modules=["_csc"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b190a24deb9f2818893a120f8ea376fbfb8d6fe
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py
@@ -0,0 +1,119 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_array_almost_equal
+from scipy.sparse import csgraph, csr_array
+
+
+def test_weak_connections():
+    Xde = np.array([[0, 1, 0],
+                    [0, 0, 0],
+                    [0, 0, 0]])
+
+    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)
+
+    for X in Xsp, Xde:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='weak')
+
+        assert_equal(n_components, 2)
+        assert_array_almost_equal(labels, [0, 0, 1])
+
+
+def test_strong_connections():
+    X1de = np.array([[0, 1, 0],
+                     [0, 0, 0],
+                     [0, 0, 0]])
+    X2de = X1de + X1de.T
+
+    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
+    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)
+
+    for X in X1sp, X1de:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='strong')
+
+        assert_equal(n_components, 3)
+        labels.sort()
+        assert_array_almost_equal(labels, [0, 1, 2])
+
+    for X in X2sp, X2de:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='strong')
+
+        assert_equal(n_components, 2)
+        labels.sort()
+        assert_array_almost_equal(labels, [0, 0, 1])
+
+
+def test_strong_connections2():
+    X = np.array([[0, 0, 0, 0, 0, 0],
+                  [1, 0, 1, 0, 0, 0],
+                  [0, 0, 0, 1, 0, 0],
+                  [0, 0, 1, 0, 1, 0],
+                  [0, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 0, 1, 0]])
+    n_components, labels =\
+        csgraph.connected_components(X, directed=True,
+                                     connection='strong')
+    assert_equal(n_components, 5)
+    labels.sort()
+    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4])
+
+
+def test_weak_connections2():
+    X = np.array([[0, 0, 0, 0, 0, 0],
+                  [1, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 1, 0, 0],
+                  [0, 0, 1, 0, 1, 0],
+                  [0, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 0, 1, 0]])
+    n_components, labels =\
+        csgraph.connected_components(X, directed=True,
+                                     connection='weak')
+    assert_equal(n_components, 2)
+    labels.sort()
+    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1])
+
+
+def test_ticket1876():
+    # Regression test: this failed in the original implementation
+    # There should be two strongly-connected components; previously gave one
+    g = np.array([[0, 1, 1, 0],
+                  [1, 0, 0, 1],
+                  [0, 0, 0, 1],
+                  [0, 0, 1, 0]])
+    n_components, labels = csgraph.connected_components(g, connection='strong')
+
+    assert_equal(n_components, 2)
+    assert_equal(labels[0], labels[1])
+    assert_equal(labels[2], labels[3])
+
+
+def test_fully_connected_graph():
+    # Fully connected dense matrices raised an exception.
+    # https://github.com/scipy/scipy/issues/3818
+    g = np.ones((4, 4))
+    n_components, labels = csgraph.connected_components(g)
+    assert_equal(n_components, 1)
+
+
+def test_int64_indices_undirected():
+    # See https://github.com/scipy/scipy/issues/18716
+    g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
+    assert g.indices.dtype == np.int64
+    n, labels = csgraph.connected_components(g, directed=False)
+    assert n == 1
+    assert_array_almost_equal(labels, [0, 0])
+
+
+def test_int64_indices_directed():
+    # See https://github.com/scipy/scipy/issues/18716
+    g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
+    assert g.indices.dtype == np.int64
+    n, labels = csgraph.connected_components(g, directed=True,
+                                             connection='strong')
+    assert n == 2
+    assert_array_almost_equal(labels, [1, 0])
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..c92eb985a1145c4b7c1777f0449bb423402f6d66
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py
@@ -0,0 +1,209 @@
+import numpy as np
+from numpy.testing import assert_array_equal
+import pytest
+
+from scipy.sparse import csr_array, csc_array, csr_matrix
+from scipy.sparse.csgraph import maximum_flow
+from scipy.sparse.csgraph._flow import (
+    _add_reverse_edges, _make_edge_pointers, _make_tails
+)
+
+methods = ['edmonds_karp', 'dinic']
+
+def test_raises_on_dense_input():
+    with pytest.raises(TypeError):
+        graph = np.array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_csc_input():
+    with pytest.raises(TypeError):
+        graph = csc_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_floating_point_input():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1.5], [0, 0]], dtype=np.float64)
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_non_square_input():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1, 2], [2, 1, 0]])
+        maximum_flow(graph, 0, 1)
+
+
+def test_raises_when_source_is_sink():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 0)
+        maximum_flow(graph, 0, 0, method='edmonds_karp')
+
+
+@pytest.mark.parametrize('method', methods)
+@pytest.mark.parametrize('source', [-1, 2, 3])
+def test_raises_when_source_is_out_of_bounds(source, method):
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, source, 1, method=method)
+
+
+@pytest.mark.parametrize('method', methods)
+@pytest.mark.parametrize('sink', [-1, 2, 3])
+def test_raises_when_sink_is_out_of_bounds(sink, method):
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, sink, method=method)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_simple_graph(method):
+    # This graph looks as follows:
+    #     (0) --5--> (1)
+    graph = csr_array([[0, 5], [0, 0]])
+    res = maximum_flow(graph, 0, 1, method=method)
+    assert res.flow_value == 5
+    expected_flow = np.array([[0, 5], [-5, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_return_type(method):
+    graph = csr_array([[0, 5], [0, 0]])
+    assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_array)
+    graph = csr_matrix([[0, 5], [0, 0]])
+    assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_matrix)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_bottle_neck_graph(method):
+    # This graph cannot use the full capacity between 0 and 1:
+    #     (0) --5--> (1) --3--> (2)
+    graph = csr_array([[0, 5, 0], [0, 0, 3], [0, 0, 0]])
+    res = maximum_flow(graph, 0, 2, method=method)
+    assert res.flow_value == 3
+    expected_flow = np.array([[0, 3, 0], [-3, 0, 3], [0, -3, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_backwards_flow(method):
+    # This example causes backwards flow between vertices 3 and 4,
+    # and so this test ensures that we handle that accordingly. See
+    #     https://stackoverflow.com/q/38843963/5085211
+    # for more information.
+    graph = csr_array([[0, 10, 0, 0, 10, 0, 0, 0],
+                       [0, 0, 10, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 10, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0, 0, 10],
+                       [0, 0, 0, 10, 0, 10, 0, 0],
+                       [0, 0, 0, 0, 0, 0, 10, 0],
+                       [0, 0, 0, 0, 0, 0, 0, 10],
+                       [0, 0, 0, 0, 0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 7, method=method)
+    assert res.flow_value == 20
+    expected_flow = np.array([[0, 10, 0, 0, 10, 0, 0, 0],
+                              [-10, 0, 10, 0, 0, 0, 0, 0],
+                              [0, -10, 0, 10, 0, 0, 0, 0],
+                              [0, 0, -10, 0, 0, 0, 0, 10],
+                              [-10, 0, 0, 0, 0, 10, 0, 0],
+                              [0, 0, 0, 0, -10, 0, 10, 0],
+                              [0, 0, 0, 0, 0, -10, 0, 10],
+                              [0, 0, 0, -10, 0, 0, -10, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_example_from_clrs_chapter_26_1(method):
+    # See page 659 in CLRS second edition, but note that the maximum flow
+    # we find is slightly different than the one in CLRS; we push a flow of
+    # 12 to v_1 instead of v_2.
+    graph = csr_array([[0, 16, 13, 0, 0, 0],
+                       [0, 0, 10, 12, 0, 0],
+                       [0, 4, 0, 0, 14, 0],
+                       [0, 0, 9, 0, 0, 20],
+                       [0, 0, 0, 7, 0, 4],
+                       [0, 0, 0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 5, method=method)
+    assert res.flow_value == 23
+    expected_flow = np.array([[0, 12, 11, 0, 0, 0],
+                              [-12, 0, 0, 12, 0, 0],
+                              [-11, 0, 0, 0, 11, 0],
+                              [0, -12, 0, 0, -7, 19],
+                              [0, 0, -11, 7, 0, 4],
+                              [0, 0, 0, -19, -4, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_disconnected_graph(method):
+    # This tests the following disconnected graph:
+    #     (0) --5--> (1)    (2) --3--> (3)
+    graph = csr_array([[0, 5, 0, 0],
+                       [0, 0, 0, 0],
+                       [0, 0, 9, 3],
+                       [0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 3, method=method)
+    assert res.flow_value == 0
+    expected_flow = np.zeros((4, 4), dtype=np.int32)
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_add_reverse_edges_large_graph(method):
+    # Regression test for https://github.com/scipy/scipy/issues/14385
+    n = 100_000
+    indices = np.arange(1, n)
+    indptr = np.array(list(range(n)) + [n - 1])
+    data = np.ones(n - 1, dtype=np.int32)
+    graph = csr_array((data, indices, indptr), shape=(n, n))
+    res = maximum_flow(graph, 0, n - 1, method=method)
+    assert res.flow_value == 1
+    expected_flow = graph - graph.transpose()
+    assert_array_equal(res.flow.data, expected_flow.data)
+    assert_array_equal(res.flow.indices, expected_flow.indices)
+    assert_array_equal(res.flow.indptr, expected_flow.indptr)
+
+
+@pytest.mark.parametrize("a,b_data_expected", [
+    ([[]], []),
+    ([[0], [0]], []),
+    ([[1, 0, 2], [0, 0, 0], [0, 3, 0]], [1, 2, 0, 0, 3]),
+    ([[9, 8, 7], [4, 5, 6], [0, 0, 0]], [9, 8, 7, 4, 5, 6, 0, 0])])
+def test_add_reverse_edges(a, b_data_expected):
+    """Test that the reversal of the edges of the input graph works
+    as expected.
+    """
+    a = csr_array(a, dtype=np.int32, shape=(len(a), len(a)))
+    b = _add_reverse_edges(a)
+    assert_array_equal(b.data, b_data_expected)
+
+
+@pytest.mark.parametrize("a,expected", [
+    ([[]], []),
+    ([[0]], []),
+    ([[1]], [0]),
+    ([[0, 1], [10, 0]], [1, 0]),
+    ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 3, 4, 1, 2])
+])
+def test_make_edge_pointers(a, expected):
+    a = csr_array(a, dtype=np.int32)
+    rev_edge_ptr = _make_edge_pointers(a)
+    assert_array_equal(rev_edge_ptr, expected)
+
+
+@pytest.mark.parametrize("a,expected", [
+    ([[]], []),
+    ([[0]], []),
+    ([[1]], [0]),
+    ([[0, 1], [10, 0]], [0, 1]),
+    ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 0, 1, 2, 2])
+])
+def test_make_tails(a, expected):
+    a = csr_array(a, dtype=np.int32)
+    tails = _make_tails(a)
+    assert_array_equal(tails, expected)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..1476c29a3ba97869c6c38be4d717641a494c1183
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py
@@ -0,0 +1,194 @@
+import pytest
+
+import numpy as np
+import scipy.sparse as sp
+import scipy.sparse.csgraph as spgraph
+from scipy._lib import _pep440
+
+from numpy.testing import assert_equal
+
+try:
+    import sparse
+except Exception:
+    sparse = None
+
+pytestmark = pytest.mark.skipif(sparse is None,
+                                reason="pydata/sparse not installed")
+
+
+msg = "pydata/sparse (0.15.1) does not implement necessary operations"
+
+
+sparse_params = (pytest.param("COO"),
+                 pytest.param("DOK", marks=[pytest.mark.xfail(reason=msg)]))
+
+
+def check_sparse_version(min_ver):
+    if sparse is None:
+        return pytest.mark.skip(reason="sparse is not installed")
+    return pytest.mark.skipif(
+        _pep440.parse(sparse.__version__) < _pep440.Version(min_ver),
+        reason=f"sparse version >= {min_ver} required"
+    )
+
+
+@pytest.fixture(params=sparse_params)
+def sparse_cls(request):
+    return getattr(sparse, request.param)
+
+
+@pytest.fixture
+def graphs(sparse_cls):
+    graph = [
+        [0, 1, 1, 0, 0],
+        [0, 0, 1, 0, 0],
+        [0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 1],
+        [0, 0, 0, 0, 0],
+    ]
+    A_dense = np.array(graph)
+    A_sparse = sparse_cls(A_dense)
+    return A_dense, A_sparse
+
+
+@pytest.mark.parametrize(
+    "func",
+    [
+        spgraph.shortest_path,
+        spgraph.dijkstra,
+        spgraph.floyd_warshall,
+        spgraph.bellman_ford,
+        spgraph.johnson,
+        spgraph.reverse_cuthill_mckee,
+        spgraph.maximum_bipartite_matching,
+        spgraph.structural_rank,
+    ]
+)
+def test_csgraph_equiv(func, graphs):
+    A_dense, A_sparse = graphs
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+    assert_equal(actual, desired)
+
+
+def test_connected_components(graphs):
+    A_dense, A_sparse = graphs
+    func = spgraph.connected_components
+
+    actual_comp, actual_labels = func(A_sparse)
+    desired_comp, desired_labels, = func(sp.csc_array(A_dense))
+
+    assert actual_comp == desired_comp
+    assert_equal(actual_labels, desired_labels)
+
+
+def test_laplacian(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.laplacian
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+@pytest.mark.parametrize(
+    "func", [spgraph.breadth_first_order, spgraph.depth_first_order]
+)
+def test_order_search(graphs, func):
+    A_dense, A_sparse = graphs
+
+    actual = func(A_sparse, 0)
+    desired = func(sp.csc_array(A_dense), 0)
+
+    assert_equal(actual, desired)
+
+
+@pytest.mark.parametrize(
+    "func", [spgraph.breadth_first_tree, spgraph.depth_first_tree]
+)
+def test_tree_search(graphs, func):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+
+    actual = func(A_sparse, 0)
+    desired = func(sp.csc_array(A_dense), 0)
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+def test_minimum_spanning_tree(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.minimum_spanning_tree
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+def test_maximum_flow(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.maximum_flow
+
+    actual = func(A_sparse, 0, 2)
+    desired = func(sp.csr_array(A_dense), 0, 2)
+
+    assert actual.flow_value == desired.flow_value
+    assert isinstance(actual.flow, sparse_cls)
+
+    assert_equal(actual.flow.todense(), desired.flow.todense())
+
+
+def test_min_weight_full_bipartite_matching(graphs):
+    A_dense, A_sparse = graphs
+    func = spgraph.min_weight_full_bipartite_matching
+
+    actual = func(A_sparse[0:2, 1:3])
+    desired = func(sp.csc_array(A_dense)[0:2, 1:3])
+
+    assert_equal(actual, desired)
+
+
+@check_sparse_version("0.15.4")
+@pytest.mark.parametrize(
+    "func",
+    [
+        spgraph.shortest_path,
+        spgraph.dijkstra,
+        spgraph.floyd_warshall,
+        spgraph.bellman_ford,
+        spgraph.johnson,
+        spgraph.minimum_spanning_tree,
+    ]
+)
+@pytest.mark.parametrize(
+    "fill_value, comp_func",
+    [(np.inf, np.isposinf), (np.nan, np.isnan)],
+)
+def test_nonzero_fill_value(graphs, func, fill_value, comp_func):
+    A_dense, A_sparse = graphs
+    A_sparse = A_sparse.astype(float)
+    A_sparse.fill_value = fill_value
+    sparse_cls = type(A_sparse)
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    if func == spgraph.minimum_spanning_tree:
+        assert isinstance(actual, sparse_cls)
+        assert comp_func(actual.fill_value)
+        actual = actual.todense()
+        actual[comp_func(actual)] = 0.0
+        assert_equal(actual, desired.todense())
+    else:
+        assert_equal(actual, desired)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csr.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..86bb1e072ebe4480e9dcb01f2d36f7387872b898
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/csr.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'csr_count_blocks',
+    'csr_matrix',
+    'csr_tobsr',
+    'csr_tocsc',
+    'get_csr_submatrix',
+    'isspmatrix_csr',
+    'spmatrix',
+    'upcast',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="csr",
+                                   private_modules=["_csr"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/data.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/data.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9958bcda6dd35ac0779514d79b7f1c494c1b01a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/data.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'isscalarlike',
+    'name',
+    'npfunc',
+    'validateaxis',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="data",
+                                   private_modules=["_data"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/dia.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/dia.py
new file mode 100644
index 0000000000000000000000000000000000000000..f79abd39f114b23df8ceb6eafb7fcc1c07218dcb
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/dia.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'check_shape',
+    'dia_matrix',
+    'dia_matvec',
+    'get_sum_dtype',
+    'getdtype',
+    'isshape',
+    'isspmatrix_dia',
+    'spmatrix',
+    'upcast_char',
+    'validateaxis',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="dia",
+                                   private_modules=["_dia"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/dok.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..847824456eaa3145d5ecb078e30251875168775b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/dok.py
@@ -0,0 +1,32 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'IndexMixin',
+    'check_shape',
+    'dok_matrix',
+    'getdtype',
+    'isdense',
+    'isintlike',
+    'isscalarlike',
+    'isshape',
+    'isspmatrix_dok',
+    'itertools',
+    'spmatrix',
+    'upcast',
+    'upcast_scalar',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="dok",
+                                   private_modules=["_dok"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/extract.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..be5e161b6f99e57e2b2a6b3d4f1ef6427c07658d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/extract.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'coo_matrix',
+    'find',
+    'tril',
+    'triu',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="extract",
+                                   private_modules=["_extract"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/lil.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/lil.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f7bf8eb03bb36a1b2fa77c5fc0840e532ab64fd
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/lil.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.sparse` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'isspmatrix_lil',
+    'lil_array',
+    'lil_matrix',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse", module="lil",
+                                   private_modules=["_lil"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae19314d48b3689a556b2a795689a3a1b75458da
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py
@@ -0,0 +1,148 @@
+"""
+Sparse linear algebra (:mod:`scipy.sparse.linalg`)
+==================================================
+
+.. currentmodule:: scipy.sparse.linalg
+
+Abstract linear operators
+-------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   LinearOperator -- abstract representation of a linear operator
+   aslinearoperator -- convert an object to an abstract linear operator
+
+Matrix Operations
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   inv -- compute the sparse matrix inverse
+   expm -- compute the sparse matrix exponential
+   expm_multiply -- compute the product of a matrix exponential and a matrix
+   matrix_power -- compute the matrix power by raising a matrix to an exponent
+
+Matrix norms
+------------
+
+.. autosummary::
+   :toctree: generated/
+
+   norm -- Norm of a sparse matrix
+   onenormest -- Estimate the 1-norm of a sparse matrix
+
+Solving linear problems
+-----------------------
+
+Direct methods for linear equation systems:
+
+.. autosummary::
+   :toctree: generated/
+
+   spsolve -- Solve the sparse linear system Ax=b
+   spsolve_triangular -- Solve sparse linear system Ax=b for a triangular A.
+   is_sptriangular -- Check if sparse A is triangular.
+   spbandwidth -- Find the bandwidth of a sparse matrix.
+   factorized -- Pre-factorize matrix to a function solving a linear system
+   MatrixRankWarning -- Warning on exactly singular matrices
+   use_solver -- Select direct solver to use
+
+Iterative methods for linear equation systems:
+
+.. autosummary::
+   :toctree: generated/
+
+   bicg -- Use BIConjugate Gradient iteration to solve Ax = b
+   bicgstab -- Use BIConjugate Gradient STABilized iteration to solve Ax = b
+   cg -- Use Conjugate Gradient iteration to solve Ax = b
+   cgs -- Use Conjugate Gradient Squared iteration to solve Ax = b
+   gmres -- Use Generalized Minimal RESidual iteration to solve Ax = b
+   lgmres -- Solve a matrix equation using the LGMRES algorithm
+   minres -- Use MINimum RESidual iteration to solve Ax = b
+   qmr -- Use Quasi-Minimal Residual iteration to solve Ax = b
+   gcrotmk -- Solve a matrix equation using the GCROT(m,k) algorithm
+   tfqmr -- Use Transpose-Free Quasi-Minimal Residual iteration to solve Ax = b
+
+Iterative methods for least-squares problems:
+
+.. autosummary::
+   :toctree: generated/
+
+   lsqr -- Find the least-squares solution to a sparse linear equation system
+   lsmr -- Find the least-squares solution to a sparse linear equation system
+
+Matrix factorizations
+---------------------
+
+Eigenvalue problems:
+
+.. autosummary::
+   :toctree: generated/
+
+   eigs -- Find k eigenvalues and eigenvectors of the square matrix A
+   eigsh -- Find k eigenvalues and eigenvectors of a symmetric matrix
+   lobpcg -- Solve symmetric partial eigenproblems with optional preconditioning
+
+Singular values problems:
+
+.. autosummary::
+   :toctree: generated/
+
+   svds -- Compute k singular values/vectors for a sparse matrix
+
+The `svds` function supports the following solvers:
+
+.. toctree::
+
+    sparse.linalg.svds-arpack
+    sparse.linalg.svds-lobpcg
+    sparse.linalg.svds-propack
+
+Complete or incomplete LU factorizations
+
+.. autosummary::
+   :toctree: generated/
+
+   splu -- Compute a LU decomposition for a sparse matrix
+   spilu -- Compute an incomplete LU decomposition for a sparse matrix
+   SuperLU -- Object representing an LU factorization
+
+Sparse arrays with structure
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   LaplacianNd -- Laplacian on a uniform rectangular grid in ``N`` dimensions
+
+Exceptions
+----------
+
+.. autosummary::
+   :toctree: generated/
+
+   ArpackNoConvergence
+   ArpackError
+
+"""
+
+from ._isolve import *
+from ._dsolve import *
+from ._interface import *
+from ._eigen import *
+from ._matfuncs import *
+from ._onenormest import *
+from ._norm import *
+from ._expm_multiply import *
+from ._special_sparse_arrays import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import isolve, dsolve, interface, eigen, 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/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_expm_multiply.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_expm_multiply.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f5a7a8508a6a9d102a836469d8fb76ddc9534b4
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_expm_multiply.py
@@ -0,0 +1,816 @@
+"""Compute the action of the matrix exponential."""
+from warnings import warn
+
+import numpy as np
+
+import scipy.linalg
+import scipy.sparse.linalg
+from scipy.linalg._decomp_qr import qr
+from scipy.sparse._sputils import is_pydata_spmatrix
+from scipy.sparse.linalg import aslinearoperator
+from scipy.sparse.linalg._interface import IdentityOperator
+from scipy.sparse.linalg._onenormest import onenormest
+
+__all__ = ['expm_multiply']
+
+
+def _exact_inf_norm(A):
+    # A compatibility function which should eventually disappear.
+    if scipy.sparse.issparse(A):
+        return max(abs(A).sum(axis=1).flat)
+    elif is_pydata_spmatrix(A):
+        return max(abs(A).sum(axis=1))
+    else:
+        return np.linalg.norm(A, np.inf)
+
+
+def _exact_1_norm(A):
+    # A compatibility function which should eventually disappear.
+    if scipy.sparse.issparse(A):
+        return max(abs(A).sum(axis=0).flat)
+    elif is_pydata_spmatrix(A):
+        return max(abs(A).sum(axis=0))
+    else:
+        return np.linalg.norm(A, 1)
+
+
+def _trace(A):
+    # A compatibility function which should eventually disappear.
+    if is_pydata_spmatrix(A):
+        return A.to_scipy_sparse().trace()
+    else:
+        return A.trace()
+
+
+def traceest(A, m3, seed=None):
+    """Estimate `np.trace(A)` using `3*m3` matrix-vector products.
+
+    The result is not deterministic.
+
+    Parameters
+    ----------
+    A : LinearOperator
+        Linear operator whose trace will be estimated. Has to be square.
+    m3 : int
+        Number of matrix-vector products divided by 3 used to estimate the
+        trace.
+    seed : optional
+        Seed for `numpy.random.default_rng`.
+        Can be provided to obtain deterministic results.
+
+    Returns
+    -------
+    trace : LinearOperator.dtype
+        Estimate of the trace
+
+    Notes
+    -----
+    This is the Hutch++ algorithm given in [1]_.
+
+    References
+    ----------
+    .. [1] Meyer, Raphael A., Cameron Musco, Christopher Musco, and David P.
+       Woodruff. "Hutch++: Optimal Stochastic Trace Estimation." In Symposium
+       on Simplicity in Algorithms (SOSA), pp. 142-155. Society for Industrial
+       and Applied Mathematics, 2021
+       https://doi.org/10.1137/1.9781611976496.16
+
+    """
+    rng = np.random.default_rng(seed)
+    if len(A.shape) != 2 or A.shape[-1] != A.shape[-2]:
+        raise ValueError("Expected A to be like a square matrix.")
+    n = A.shape[-1]
+    S = rng.choice([-1.0, +1.0], [n, m3])
+    Q, _ = qr(A.matmat(S), overwrite_a=True, mode='economic')
+    trQAQ = np.trace(Q.conj().T @ A.matmat(Q))
+    G = rng.choice([-1, +1], [n, m3])
+    right = G - Q@(Q.conj().T @ G)
+    trGAG = np.trace(right.conj().T @ A.matmat(right))
+    return trQAQ + trGAG/m3
+
+
+def _ident_like(A):
+    # A compatibility function which should eventually disappear.
+    if scipy.sparse.issparse(A):
+        # Creates a sparse matrix in dia format
+        out = scipy.sparse.eye(A.shape[0], A.shape[1], dtype=A.dtype)
+        if scipy.sparse.issparse(A):
+            return out.asformat(A.format)
+        return scipy.sparse.dia_array(out).asformat(A.format)
+    elif is_pydata_spmatrix(A):
+        import sparse
+        return sparse.eye(A.shape[0], A.shape[1], dtype=A.dtype)
+    elif isinstance(A, scipy.sparse.linalg.LinearOperator):
+        return IdentityOperator(A.shape, dtype=A.dtype)
+    else:
+        return np.eye(A.shape[0], A.shape[1], dtype=A.dtype)
+
+
+def expm_multiply(A, B, start=None, stop=None, num=None,
+                  endpoint=None, traceA=None):
+    """
+    Compute the action of the matrix exponential of A on B.
+
+    Parameters
+    ----------
+    A : transposable linear operator
+        The operator whose exponential is of interest.
+    B : ndarray, sparse array
+        The matrix or vector to be multiplied by the matrix exponential of A.
+    start : scalar, optional
+        The starting time point of the sequence.
+    stop : scalar, optional
+        The end time point of the sequence, unless `endpoint` is set to False.
+        In that case, the sequence consists of all but the last of ``num + 1``
+        evenly spaced time points, so that `stop` is excluded.
+        Note that the step size changes when `endpoint` is False.
+    num : int, optional
+        Number of time points to use.
+    endpoint : bool, optional
+        If True, `stop` is the last time point.  Otherwise, it is not included.
+    traceA : scalar, optional
+        Trace of `A`. If not given the trace is estimated for linear operators,
+        or calculated exactly for sparse matrices. It is used to precondition
+        `A`, thus an approximate trace is acceptable.
+        For linear operators, `traceA` should be provided to ensure performance
+        as the estimation is not guaranteed to be reliable for all cases.
+
+        .. versionadded:: 1.9.0
+
+    Returns
+    -------
+    expm_A_B : ndarray
+         The result of the action :math:`e^{t_k A} B`.
+
+    Warns
+    -----
+    UserWarning
+        If `A` is a linear operator and ``traceA=None`` (default).
+
+    Notes
+    -----
+    The optional arguments defining the sequence of evenly spaced time points
+    are compatible with the arguments of `numpy.linspace`.
+
+    The output ndarray shape is somewhat complicated so I explain it here.
+    The ndim of the output could be either 1, 2, or 3.
+    It would be 1 if you are computing the expm action on a single vector
+    at a single time point.
+    It would be 2 if you are computing the expm action on a vector
+    at multiple time points, or if you are computing the expm action
+    on a matrix at a single time point.
+    It would be 3 if you want the action on a matrix with multiple
+    columns at multiple time points.
+    If multiple time points are requested, expm_A_B[0] will always
+    be the action of the expm at the first time point,
+    regardless of whether the action is on a vector or a matrix.
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2011)
+           "Computing the Action of the Matrix Exponential,
+           with an Application to Exponential Integrators."
+           SIAM Journal on Scientific Computing,
+           33 (2). pp. 488-511. ISSN 1064-8275
+           http://eprints.ma.man.ac.uk/1591/
+
+    .. [2] Nicholas J. Higham and Awad H. Al-Mohy (2010)
+           "Computing Matrix Functions."
+           Acta Numerica,
+           19. 159-208. ISSN 0962-4929
+           http://eprints.ma.man.ac.uk/1451/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import expm, expm_multiply
+    >>> A = csc_array([[1, 0], [0, 1]])
+    >>> A.toarray()
+    array([[1, 0],
+           [0, 1]], dtype=int64)
+    >>> B = np.array([np.exp(-1.), np.exp(-2.)])
+    >>> B
+    array([ 0.36787944,  0.13533528])
+    >>> expm_multiply(A, B, start=1, stop=2, num=3, endpoint=True)
+    array([[ 1.        ,  0.36787944],
+           [ 1.64872127,  0.60653066],
+           [ 2.71828183,  1.        ]])
+    >>> expm(A).dot(B)                  # Verify 1st timestep
+    array([ 1.        ,  0.36787944])
+    >>> expm(1.5*A).dot(B)              # Verify 2nd timestep
+    array([ 1.64872127,  0.60653066])
+    >>> expm(2*A).dot(B)                # Verify 3rd timestep
+    array([ 2.71828183,  1.        ])
+    """
+    if all(arg is None for arg in (start, stop, num, endpoint)):
+        X = _expm_multiply_simple(A, B, traceA=traceA)
+    else:
+        X, status = _expm_multiply_interval(A, B, start, stop, num,
+                                            endpoint, traceA=traceA)
+    return X
+
+
+def _expm_multiply_simple(A, B, t=1.0, traceA=None, balance=False):
+    """
+    Compute the action of the matrix exponential at a single time point.
+
+    Parameters
+    ----------
+    A : transposable linear operator
+        The operator whose exponential is of interest.
+    B : ndarray
+        The matrix to be multiplied by the matrix exponential of A.
+    t : float
+        A time point.
+    traceA : scalar, optional
+        Trace of `A`. If not given the trace is estimated for linear operators,
+        or calculated exactly for sparse matrices. It is used to precondition
+        `A`, thus an approximate trace is acceptable
+    balance : bool
+        Indicates whether or not to apply balancing.
+
+    Returns
+    -------
+    F : ndarray
+        :math:`e^{t A} B`
+
+    Notes
+    -----
+    This is algorithm (3.2) in Al-Mohy and Higham (2011).
+
+    """
+    if balance:
+        raise NotImplementedError
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected A to be like a square matrix')
+    if A.shape[1] != B.shape[0]:
+        raise ValueError(f'shapes of matrices A {A.shape} and B {B.shape}'
+                         ' are incompatible')
+    ident = _ident_like(A)
+    is_linear_operator = isinstance(A, scipy.sparse.linalg.LinearOperator)
+    n = A.shape[0]
+    if len(B.shape) == 1:
+        n0 = 1
+    elif len(B.shape) == 2:
+        n0 = B.shape[1]
+    else:
+        raise ValueError('expected B to be like a matrix or a vector')
+    u_d = 2**-53
+    tol = u_d
+    if traceA is None:
+        if is_linear_operator:
+            warn("Trace of LinearOperator not available, it will be estimated."
+                 " Provide `traceA` to ensure performance.", stacklevel=3)
+        # m3=1 is bit arbitrary choice, a more accurate trace (larger m3) might
+        # speed up exponential calculation, but trace estimation is more costly
+        traceA = traceest(A, m3=1) if is_linear_operator else _trace(A)
+    mu = traceA / float(n)
+    A = A - mu * ident
+    A_1_norm = onenormest(A) if is_linear_operator else _exact_1_norm(A)
+    if t*A_1_norm == 0:
+        m_star, s = 0, 1
+    else:
+        ell = 2
+        norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell)
+        m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
+    return _expm_multiply_simple_core(A, B, t, mu, m_star, s, tol, balance)
+
+
+def _expm_multiply_simple_core(A, B, t, mu, m_star, s, tol=None, balance=False):
+    """
+    A helper function.
+    """
+    if balance:
+        raise NotImplementedError
+    if tol is None:
+        u_d = 2 ** -53
+        tol = u_d
+    F = B
+    eta = np.exp(t*mu / float(s))
+    for i in range(s):
+        c1 = _exact_inf_norm(B)
+        for j in range(m_star):
+            coeff = t / float(s*(j+1))
+            B = coeff * A.dot(B)
+            c2 = _exact_inf_norm(B)
+            F = F + B
+            if c1 + c2 <= tol * _exact_inf_norm(F):
+                break
+            c1 = c2
+        F = eta * F
+        B = F
+    return F
+
+
+# This table helps to compute bounds.
+# They seem to have been difficult to calculate, involving symbolic
+# manipulation of equations, followed by numerical root finding.
+_theta = {
+        # The first 30 values are from table A.3 of Computing Matrix Functions.
+        1: 2.29e-16,
+        2: 2.58e-8,
+        3: 1.39e-5,
+        4: 3.40e-4,
+        5: 2.40e-3,
+        6: 9.07e-3,
+        7: 2.38e-2,
+        8: 5.00e-2,
+        9: 8.96e-2,
+        10: 1.44e-1,
+        # 11
+        11: 2.14e-1,
+        12: 3.00e-1,
+        13: 4.00e-1,
+        14: 5.14e-1,
+        15: 6.41e-1,
+        16: 7.81e-1,
+        17: 9.31e-1,
+        18: 1.09,
+        19: 1.26,
+        20: 1.44,
+        # 21
+        21: 1.62,
+        22: 1.82,
+        23: 2.01,
+        24: 2.22,
+        25: 2.43,
+        26: 2.64,
+        27: 2.86,
+        28: 3.08,
+        29: 3.31,
+        30: 3.54,
+        # The rest are from table 3.1 of
+        # Computing the Action of the Matrix Exponential.
+        35: 4.7,
+        40: 6.0,
+        45: 7.2,
+        50: 8.5,
+        55: 9.9,
+        }
+
+
+def _onenormest_matrix_power(A, p,
+        t=2, itmax=5, compute_v=False, compute_w=False):
+    """
+    Efficiently estimate the 1-norm of A^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.
+
+    """
+    #XXX Eventually turn this into an API function in the  _onenormest module,
+    #XXX and remove its underscore,
+    #XXX but wait until expm_multiply goes into scipy.
+    from scipy.sparse.linalg._onenormest import onenormest
+    return onenormest(aslinearoperator(A) ** p)
+
+class LazyOperatorNormInfo:
+    """
+    Information about an operator is lazily computed.
+
+    The information includes the exact 1-norm of the operator,
+    in addition to estimates of 1-norms of powers of the operator.
+    This uses the notation of Computing the Action (2011).
+    This class is specialized enough to probably not be of general interest
+    outside of this module.
+
+    """
+
+    def __init__(self, A, A_1_norm=None, ell=2, scale=1):
+        """
+        Provide the operator and some norm-related information.
+
+        Parameters
+        ----------
+        A : linear operator
+            The operator of interest.
+        A_1_norm : float, optional
+            The exact 1-norm of A.
+        ell : int, optional
+            A technical parameter controlling norm estimation quality.
+        scale : int, optional
+            If specified, return the norms of scale*A instead of A.
+
+        """
+        self._A = A
+        self._A_1_norm = A_1_norm
+        self._ell = ell
+        self._d = {}
+        self._scale = scale
+
+    def set_scale(self,scale):
+        """
+        Set the scale parameter.
+        """
+        self._scale = scale
+
+    def onenorm(self):
+        """
+        Compute the exact 1-norm.
+        """
+        if self._A_1_norm is None:
+            self._A_1_norm = _exact_1_norm(self._A)
+        return self._scale*self._A_1_norm
+
+    def d(self, p):
+        """
+        Lazily estimate :math:`d_p(A) ~= || A^p ||^(1/p)`
+        where :math:`||.||` is the 1-norm.
+        """
+        if p not in self._d:
+            est = _onenormest_matrix_power(self._A, p, self._ell)
+            self._d[p] = est ** (1.0 / p)
+        return self._scale*self._d[p]
+
+    def alpha(self, p):
+        """
+        Lazily compute max(d(p), d(p+1)).
+        """
+        return max(self.d(p), self.d(p+1))
+
+def _compute_cost_div_m(m, p, norm_info):
+    """
+    A helper function for computing bounds.
+
+    This is equation (3.10).
+    It measures cost in terms of the number of required matrix products.
+
+    Parameters
+    ----------
+    m : int
+        A valid key of _theta.
+    p : int
+        A matrix power.
+    norm_info : LazyOperatorNormInfo
+        Information about 1-norms of related operators.
+
+    Returns
+    -------
+    cost_div_m : int
+        Required number of matrix products divided by m.
+
+    """
+    return int(np.ceil(norm_info.alpha(p) / _theta[m]))
+
+
+def _compute_p_max(m_max):
+    """
+    Compute the largest positive integer p such that p*(p-1) <= m_max + 1.
+
+    Do this in a slightly dumb way, but safe and not too slow.
+
+    Parameters
+    ----------
+    m_max : int
+        A count related to bounds.
+
+    """
+    sqrt_m_max = np.sqrt(m_max)
+    p_low = int(np.floor(sqrt_m_max))
+    p_high = int(np.ceil(sqrt_m_max + 1))
+    return max(p for p in range(p_low, p_high+1) if p*(p-1) <= m_max + 1)
+
+
+def _fragment_3_1(norm_info, n0, tol, m_max=55, ell=2):
+    """
+    A helper function for the _expm_multiply_* functions.
+
+    Parameters
+    ----------
+    norm_info : LazyOperatorNormInfo
+        Information about norms of certain linear operators of interest.
+    n0 : int
+        Number of columns in the _expm_multiply_* B matrix.
+    tol : float
+        Expected to be
+        :math:`2^{-24}` for single precision or
+        :math:`2^{-53}` for double precision.
+    m_max : int
+        A value related to a bound.
+    ell : int
+        The number of columns used in the 1-norm approximation.
+        This is usually taken to be small, maybe between 1 and 5.
+
+    Returns
+    -------
+    best_m : int
+        Related to bounds for error control.
+    best_s : int
+        Amount of scaling.
+
+    Notes
+    -----
+    This is code fragment (3.1) in Al-Mohy and Higham (2011).
+    The discussion of default values for m_max and ell
+    is given between the definitions of equation (3.11)
+    and the definition of equation (3.12).
+
+    """
+    if ell < 1:
+        raise ValueError('expected ell to be a positive integer')
+    best_m = None
+    best_s = None
+    if _condition_3_13(norm_info.onenorm(), n0, m_max, ell):
+        for m, theta in _theta.items():
+            s = int(np.ceil(norm_info.onenorm() / theta))
+            if best_m is None or m * s < best_m * best_s:
+                best_m = m
+                best_s = s
+    else:
+        # Equation (3.11).
+        for p in range(2, _compute_p_max(m_max) + 1):
+            for m in range(p*(p-1)-1, m_max+1):
+                if m in _theta:
+                    s = _compute_cost_div_m(m, p, norm_info)
+                    if best_m is None or m * s < best_m * best_s:
+                        best_m = m
+                        best_s = s
+        best_s = max(best_s, 1)
+    return best_m, best_s
+
+
+def _condition_3_13(A_1_norm, n0, m_max, ell):
+    """
+    A helper function for the _expm_multiply_* functions.
+
+    Parameters
+    ----------
+    A_1_norm : float
+        The precomputed 1-norm of A.
+    n0 : int
+        Number of columns in the _expm_multiply_* B matrix.
+    m_max : int
+        A value related to a bound.
+    ell : int
+        The number of columns used in the 1-norm approximation.
+        This is usually taken to be small, maybe between 1 and 5.
+
+    Returns
+    -------
+    value : bool
+        Indicates whether or not the condition has been met.
+
+    Notes
+    -----
+    This is condition (3.13) in Al-Mohy and Higham (2011).
+
+    """
+
+    # This is the rhs of equation (3.12).
+    p_max = _compute_p_max(m_max)
+    a = 2 * ell * p_max * (p_max + 3)
+
+    # Evaluate the condition (3.13).
+    b = _theta[m_max] / float(n0 * m_max)
+    return A_1_norm <= a * b
+
+
+def _expm_multiply_interval(A, B, start=None, stop=None, num=None,
+                            endpoint=None, traceA=None, balance=False,
+                            status_only=False):
+    """
+    Compute the action of the matrix exponential at multiple time points.
+
+    Parameters
+    ----------
+    A : transposable linear operator
+        The operator whose exponential is of interest.
+    B : ndarray
+        The matrix to be multiplied by the matrix exponential of A.
+    start : scalar, optional
+        The starting time point of the sequence.
+    stop : scalar, optional
+        The end time point of the sequence, unless `endpoint` is set to False.
+        In that case, the sequence consists of all but the last of ``num + 1``
+        evenly spaced time points, so that `stop` is excluded.
+        Note that the step size changes when `endpoint` is False.
+    num : int, optional
+        Number of time points to use.
+    traceA : scalar, optional
+        Trace of `A`. If not given the trace is estimated for linear operators,
+        or calculated exactly for sparse matrices. It is used to precondition
+        `A`, thus an approximate trace is acceptable
+    endpoint : bool, optional
+        If True, `stop` is the last time point. Otherwise, it is not included.
+    balance : bool
+        Indicates whether or not to apply balancing.
+    status_only : bool
+        A flag that is set to True for some debugging and testing operations.
+
+    Returns
+    -------
+    F : ndarray
+        :math:`e^{t_k A} B`
+    status : int
+        An integer status for testing and debugging.
+
+    Notes
+    -----
+    This is algorithm (5.2) in Al-Mohy and Higham (2011).
+
+    There seems to be a typo, where line 15 of the algorithm should be
+    moved to line 6.5 (between lines 6 and 7).
+
+    """
+    if balance:
+        raise NotImplementedError
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected A to be like a square matrix')
+    if A.shape[1] != B.shape[0]:
+        raise ValueError(f'shapes of matrices A {A.shape} and B {B.shape}'
+                         ' are incompatible')
+    ident = _ident_like(A)
+    is_linear_operator = isinstance(A, scipy.sparse.linalg.LinearOperator)
+    n = A.shape[0]
+    if len(B.shape) == 1:
+        n0 = 1
+    elif len(B.shape) == 2:
+        n0 = B.shape[1]
+    else:
+        raise ValueError('expected B to be like a matrix or a vector')
+    u_d = 2**-53
+    tol = u_d
+    if traceA is None:
+        if is_linear_operator:
+            warn("Trace of LinearOperator not available, it will be estimated."
+                 " Provide `traceA` to ensure performance.", stacklevel=3)
+        # m3=5 is bit arbitrary choice, a more accurate trace (larger m3) might
+        # speed up exponential calculation, but trace estimation is also costly
+        # an educated guess would need to consider the number of time points
+        traceA = traceest(A, m3=5) if is_linear_operator else _trace(A)
+    mu = traceA / float(n)
+
+    # Get the linspace samples, attempting to preserve the linspace defaults.
+    linspace_kwargs = {'retstep': True}
+    if num is not None:
+        linspace_kwargs['num'] = num
+    if endpoint is not None:
+        linspace_kwargs['endpoint'] = endpoint
+    samples, step = np.linspace(start, stop, **linspace_kwargs)
+
+    # Convert the linspace output to the notation used by the publication.
+    nsamples = len(samples)
+    if nsamples < 2:
+        raise ValueError('at least two time points are required')
+    q = nsamples - 1
+    h = step
+    t_0 = samples[0]
+    t_q = samples[q]
+
+    # Define the output ndarray.
+    # Use an ndim=3 shape, such that the last two indices
+    # are the ones that may be involved in level 3 BLAS operations.
+    X_shape = (nsamples,) + B.shape
+    X = np.empty(X_shape, dtype=np.result_type(A.dtype, B.dtype, float))
+    t = t_q - t_0
+    A = A - mu * ident
+    A_1_norm = onenormest(A) if is_linear_operator else _exact_1_norm(A)
+    ell = 2
+    norm_info = LazyOperatorNormInfo(t*A, A_1_norm=t*A_1_norm, ell=ell)
+    if t*A_1_norm == 0:
+        m_star, s = 0, 1
+    else:
+        m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
+
+    # Compute the expm action up to the initial time point.
+    action_t0 = _expm_multiply_simple_core(A, B, t_0, mu, m_star, s)
+    if scipy.sparse.issparse(action_t0):
+        action_t0 = action_t0.toarray()
+    elif is_pydata_spmatrix(action_t0):
+        action_t0 = action_t0.todense()
+    X[0] = action_t0
+
+    # Compute the expm action at the rest of the time points.
+    if q <= s:
+        if status_only:
+            return 0
+        else:
+            return _expm_multiply_interval_core_0(A, X,
+                    h, mu, q, norm_info, tol, ell,n0)
+    elif not (q % s):
+        if status_only:
+            return 1
+        else:
+            return _expm_multiply_interval_core_1(A, X,
+                    h, mu, m_star, s, q, tol)
+    elif (q % s):
+        if status_only:
+            return 2
+        else:
+            return _expm_multiply_interval_core_2(A, X,
+                    h, mu, m_star, s, q, tol)
+    else:
+        raise Exception('internal error')
+
+
+def _expm_multiply_interval_core_0(A, X, h, mu, q, norm_info, tol, ell, n0):
+    """
+    A helper function, for the case q <= s.
+    """
+
+    # Compute the new values of m_star and s which should be applied
+    # over intervals of size t/q
+    if norm_info.onenorm() == 0:
+        m_star, s = 0, 1
+    else:
+        norm_info.set_scale(1./q)
+        m_star, s = _fragment_3_1(norm_info, n0, tol, ell=ell)
+        norm_info.set_scale(1)
+
+    for k in range(q):
+        X[k+1] = _expm_multiply_simple_core(A, X[k], h, mu, m_star, s)
+    return X, 0
+
+
+def _expm_multiply_interval_core_1(A, X, h, mu, m_star, s, q, tol):
+    """
+    A helper function, for the case q > s and q % s == 0.
+    """
+    d = q // s
+    input_shape = X.shape[1:]
+    K_shape = (m_star + 1, ) + input_shape
+    K = np.empty(K_shape, dtype=X.dtype)
+    for i in range(s):
+        Z = X[i*d]
+        K[0] = Z
+        high_p = 0
+        for k in range(1, d+1):
+            F = K[0]
+            c1 = _exact_inf_norm(F)
+            for p in range(1, m_star+1):
+                if p > high_p:
+                    K[p] = h * A.dot(K[p-1]) / float(p)
+                coeff = float(pow(k, p))
+                F = F + coeff * K[p]
+                inf_norm_K_p_1 = _exact_inf_norm(K[p])
+                c2 = coeff * inf_norm_K_p_1
+                if c1 + c2 <= tol * _exact_inf_norm(F):
+                    break
+                c1 = c2
+            X[k + i*d] = np.exp(k*h*mu) * F
+    return X, 1
+
+
+def _expm_multiply_interval_core_2(A, X, h, mu, m_star, s, q, tol):
+    """
+    A helper function, for the case q > s and q % s > 0.
+    """
+    d = q // s
+    j = q // d
+    r = q - d * j
+    input_shape = X.shape[1:]
+    K_shape = (m_star + 1, ) + input_shape
+    K = np.empty(K_shape, dtype=X.dtype)
+    for i in range(j + 1):
+        Z = X[i*d]
+        K[0] = Z
+        high_p = 0
+        if i < j:
+            effective_d = d
+        else:
+            effective_d = r
+        for k in range(1, effective_d+1):
+            F = K[0]
+            c1 = _exact_inf_norm(F)
+            for p in range(1, m_star+1):
+                if p == high_p + 1:
+                    K[p] = h * A.dot(K[p-1]) / float(p)
+                    high_p = p
+                coeff = float(pow(k, p))
+                F = F + coeff * K[p]
+                inf_norm_K_p_1 = _exact_inf_norm(K[p])
+                c2 = coeff * inf_norm_K_p_1
+                if c1 + c2 <= tol * _exact_inf_norm(F):
+                    break
+                c1 = c2
+            X[k + i*d] = np.exp(k*h*mu) * F
+    return X, 2
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_interface.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..510c4ff254eb561fd93da5ca3bda66c2dc92770f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_interface.py
@@ -0,0 +1,921 @@
+"""Abstract linear algebra library.
+
+This module defines a class hierarchy that implements a kind of "lazy"
+matrix representation, called the ``LinearOperator``. It can be used to do
+linear algebra with extremely large sparse or structured matrices, without
+representing those explicitly in memory. Such matrices can be added,
+multiplied, transposed, etc.
+
+As a motivating example, suppose you want have a matrix where almost all of
+the elements have the value one. The standard sparse matrix representation
+skips the storage of zeros, but not ones. By contrast, a LinearOperator is
+able to represent such matrices efficiently. First, we need a compact way to
+represent an all-ones matrix::
+
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg._interface import LinearOperator
+    >>> class Ones(LinearOperator):
+    ...     def __init__(self, shape):
+    ...         super().__init__(dtype=None, shape=shape)
+    ...     def _matvec(self, x):
+    ...         return np.repeat(x.sum(), self.shape[0])
+
+Instances of this class emulate ``np.ones(shape)``, but using a constant
+amount of storage, independent of ``shape``. The ``_matvec`` method specifies
+how this linear operator multiplies with (operates on) a vector. We can now
+add this operator to a sparse matrix that stores only offsets from one::
+
+    >>> from scipy.sparse.linalg._interface import aslinearoperator
+    >>> from scipy.sparse import csr_array
+    >>> offsets = csr_array([[1, 0, 2], [0, -1, 0], [0, 0, 3]])
+    >>> A = aslinearoperator(offsets) + Ones(offsets.shape)
+    >>> A.dot([1, 2, 3])
+    array([13,  4, 15])
+
+The result is the same as that given by its dense, explicitly-stored
+counterpart::
+
+    >>> (np.ones(A.shape, A.dtype) + offsets.toarray()).dot([1, 2, 3])
+    array([13,  4, 15])
+
+Several algorithms in the ``scipy.sparse`` library are able to operate on
+``LinearOperator`` instances.
+"""
+
+import warnings
+
+import numpy as np
+
+from scipy.sparse import issparse
+from scipy.sparse._sputils import isshape, isintlike, asmatrix, is_pydata_spmatrix
+
+__all__ = ['LinearOperator', 'aslinearoperator']
+
+
+class LinearOperator:
+    """Common interface for performing matrix vector products
+
+    Many iterative methods (e.g. cg, gmres) do not need to know the
+    individual entries of a matrix to solve a linear system A@x=b.
+    Such solvers only require the computation of matrix vector
+    products, A@v where v is a dense vector.  This class serves as
+    an abstract interface between iterative solvers and matrix-like
+    objects.
+
+    To construct a concrete LinearOperator, either pass appropriate
+    callables to the constructor of this class, or subclass it.
+
+    A subclass must implement either one of the methods ``_matvec``
+    and ``_matmat``, and the attributes/properties ``shape`` (pair of
+    integers) and ``dtype`` (may be None). It may call the ``__init__``
+    on this class to have these attributes validated. Implementing
+    ``_matvec`` automatically implements ``_matmat`` (using a naive
+    algorithm) and vice-versa.
+
+    Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint``
+    to implement the Hermitian adjoint (conjugate transpose). As with
+    ``_matvec`` and ``_matmat``, implementing either ``_rmatvec`` or
+    ``_adjoint`` implements the other automatically. Implementing
+    ``_adjoint`` is preferable; ``_rmatvec`` is mostly there for
+    backwards compatibility.
+
+    Parameters
+    ----------
+    shape : tuple
+        Matrix dimensions (M, N).
+    matvec : callable f(v)
+        Returns returns A @ v.
+    rmatvec : callable f(v)
+        Returns A^H @ v, where A^H is the conjugate transpose of A.
+    matmat : callable f(V)
+        Returns A @ V, where V is a dense matrix with dimensions (N, K).
+    dtype : dtype
+        Data type of the matrix.
+    rmatmat : callable f(V)
+        Returns A^H @ V, where V is a dense matrix with dimensions (M, K).
+
+    Attributes
+    ----------
+    args : tuple
+        For linear operators describing products etc. of other linear
+        operators, the operands of the binary operation.
+    ndim : int
+        Number of dimensions (this is always 2)
+
+    See Also
+    --------
+    aslinearoperator : Construct LinearOperators
+
+    Notes
+    -----
+    The user-defined matvec() function must properly handle the case
+    where v has shape (N,) as well as the (N,1) case.  The shape of
+    the return type is handled internally by LinearOperator.
+
+    It is highly recommended to explicitly specify the `dtype`, otherwise
+    it is determined automatically at the cost of a single matvec application
+    on `int8` zero vector using the promoted `dtype` of the output.
+    Python `int` could be difficult to automatically cast to numpy integers
+    in the definition of the `matvec` so the determination may be inaccurate.
+    It is assumed that `matmat`, `rmatvec`, and `rmatmat` would result in
+    the same dtype of the output given an `int8` input as `matvec`.
+
+    LinearOperator instances can also be multiplied, added with each
+    other and exponentiated, all lazily: the result of these operations
+    is always a new, composite LinearOperator, that defers linear
+    operations to the original operators and combines the results.
+
+    More details regarding how to subclass a LinearOperator and several
+    examples of concrete LinearOperator instances can be found in the
+    external project `PyLops `_.
+
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import LinearOperator
+    >>> def mv(v):
+    ...     return np.array([2*v[0], 3*v[1]])
+    ...
+    >>> A = LinearOperator((2,2), matvec=mv)
+    >>> A
+    <2x2 _CustomLinearOperator with dtype=int8>
+    >>> A.matvec(np.ones(2))
+    array([ 2.,  3.])
+    >>> A @ np.ones(2)
+    array([ 2.,  3.])
+
+    """
+
+    ndim = 2
+    # Necessary for right matmul with numpy arrays.
+    __array_ufunc__ = None
+
+    def __new__(cls, *args, **kwargs):
+        if cls is LinearOperator:
+            # Operate as _CustomLinearOperator factory.
+            return super().__new__(_CustomLinearOperator)
+        else:
+            obj = super().__new__(cls)
+
+            if (type(obj)._matvec == LinearOperator._matvec
+                    and type(obj)._matmat == LinearOperator._matmat):
+                warnings.warn("LinearOperator subclass should implement"
+                              " at least one of _matvec and _matmat.",
+                              category=RuntimeWarning, stacklevel=2)
+
+            return obj
+
+    def __init__(self, dtype, shape):
+        """Initialize this LinearOperator.
+
+        To be called by subclasses. ``dtype`` may be None; ``shape`` should
+        be convertible to a length-2 tuple.
+        """
+        if dtype is not None:
+            dtype = np.dtype(dtype)
+
+        shape = tuple(shape)
+        if not isshape(shape):
+            raise ValueError(f"invalid shape {shape!r} (must be 2-d)")
+
+        self.dtype = dtype
+        self.shape = shape
+
+    def _init_dtype(self):
+        """Determine the dtype by executing `matvec` on an `int8` test vector.
+
+        In `np.promote_types` hierarchy, the type `int8` is the smallest,
+        so we call `matvec` on `int8` and use the promoted dtype of the output
+        to set the default `dtype` of the `LinearOperator`.
+        We assume that `matmat`, `rmatvec`, and `rmatmat` would result in
+        the same dtype of the output given an `int8` input as `matvec`.
+
+        Called from subclasses at the end of the __init__ routine.
+        """
+        if self.dtype is None:
+            v = np.zeros(self.shape[-1], dtype=np.int8)
+            try:
+                matvec_v = np.asarray(self.matvec(v))
+            except OverflowError:
+                # Python large `int` promoted to `np.int64`or `np.int32`
+                self.dtype = np.dtype(int)
+            else:
+                self.dtype = matvec_v.dtype
+
+    def _matmat(self, X):
+        """Default matrix-matrix multiplication handler.
+
+        Falls back on the user-defined _matvec method, so defining that will
+        define matrix multiplication (though in a very suboptimal way).
+        """
+
+        return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T])
+
+    def _matvec(self, x):
+        """Default matrix-vector multiplication handler.
+
+        If self is a linear operator of shape (M, N), then this method will
+        be called on a shape (N,) or (N, 1) ndarray, and should return a
+        shape (M,) or (M, 1) ndarray.
+
+        This default implementation falls back on _matmat, so defining that
+        will define matrix-vector multiplication as well.
+        """
+        return self.matmat(x.reshape(-1, 1))
+
+    def matvec(self, x):
+        """Matrix-vector multiplication.
+
+        Performs the operation y=A@x where A is an MxN linear
+        operator and x is a column vector or 1-d array.
+
+        Parameters
+        ----------
+        x : {matrix, ndarray}
+            An array with shape (N,) or (N,1).
+
+        Returns
+        -------
+        y : {matrix, ndarray}
+            A matrix or ndarray with shape (M,) or (M,1) depending
+            on the type and shape of the x argument.
+
+        Notes
+        -----
+        This matvec wraps the user-specified matvec routine or overridden
+        _matvec method to ensure that y has the correct shape and type.
+
+        """
+
+        x = np.asanyarray(x)
+
+        M,N = self.shape
+
+        if x.shape != (N,) and x.shape != (N,1):
+            raise ValueError('dimension mismatch')
+
+        y = self._matvec(x)
+
+        if isinstance(x, np.matrix):
+            y = asmatrix(y)
+        else:
+            y = np.asarray(y)
+
+        if x.ndim == 1:
+            y = y.reshape(M)
+        elif x.ndim == 2:
+            y = y.reshape(M,1)
+        else:
+            raise ValueError('invalid shape returned by user-defined matvec()')
+
+        return y
+
+    def rmatvec(self, x):
+        """Adjoint matrix-vector multiplication.
+
+        Performs the operation y = A^H @ x where A is an MxN linear
+        operator and x is a column vector or 1-d array.
+
+        Parameters
+        ----------
+        x : {matrix, ndarray}
+            An array with shape (M,) or (M,1).
+
+        Returns
+        -------
+        y : {matrix, ndarray}
+            A matrix or ndarray with shape (N,) or (N,1) depending
+            on the type and shape of the x argument.
+
+        Notes
+        -----
+        This rmatvec wraps the user-specified rmatvec routine or overridden
+        _rmatvec method to ensure that y has the correct shape and type.
+
+        """
+
+        x = np.asanyarray(x)
+
+        M,N = self.shape
+
+        if x.shape != (M,) and x.shape != (M,1):
+            raise ValueError('dimension mismatch')
+
+        y = self._rmatvec(x)
+
+        if isinstance(x, np.matrix):
+            y = asmatrix(y)
+        else:
+            y = np.asarray(y)
+
+        if x.ndim == 1:
+            y = y.reshape(N)
+        elif x.ndim == 2:
+            y = y.reshape(N,1)
+        else:
+            raise ValueError('invalid shape returned by user-defined rmatvec()')
+
+        return y
+
+    def _rmatvec(self, x):
+        """Default implementation of _rmatvec; defers to adjoint."""
+        if type(self)._adjoint == LinearOperator._adjoint:
+            # _adjoint not overridden, prevent infinite recursion
+            if (hasattr(self, "_rmatmat")
+                    and type(self)._rmatmat != LinearOperator._rmatmat):
+                # Try to use _rmatmat as a fallback
+                return self._rmatmat(x.reshape(-1, 1)).reshape(-1)
+            raise NotImplementedError
+        else:
+            return self.H.matvec(x)
+
+    def matmat(self, X):
+        """Matrix-matrix multiplication.
+
+        Performs the operation y=A@X where A is an MxN linear
+        operator and X dense N*K matrix or ndarray.
+
+        Parameters
+        ----------
+        X : {matrix, ndarray}
+            An array with shape (N,K).
+
+        Returns
+        -------
+        Y : {matrix, ndarray}
+            A matrix or ndarray with shape (M,K) depending on
+            the type of the X argument.
+
+        Notes
+        -----
+        This matmat wraps any user-specified matmat routine or overridden
+        _matmat method to ensure that y has the correct type.
+
+        """
+        if not (issparse(X) or is_pydata_spmatrix(X)):
+            X = np.asanyarray(X)
+
+        if X.ndim != 2:
+            raise ValueError(f'expected 2-d ndarray or matrix, not {X.ndim}-d')
+
+        if X.shape[0] != self.shape[1]:
+            raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}')
+
+        try:
+            Y = self._matmat(X)
+        except Exception as e:
+            if issparse(X) or is_pydata_spmatrix(X):
+                raise TypeError(
+                    "Unable to multiply a LinearOperator with a sparse matrix."
+                    " Wrap the matrix in aslinearoperator first."
+                ) from e
+            raise
+
+        if isinstance(Y, np.matrix):
+            Y = asmatrix(Y)
+
+        return Y
+
+    def rmatmat(self, X):
+        """Adjoint matrix-matrix multiplication.
+
+        Performs the operation y = A^H @ x where A is an MxN linear
+        operator and x is a column vector or 1-d array, or 2-d array.
+        The default implementation defers to the adjoint.
+
+        Parameters
+        ----------
+        X : {matrix, ndarray}
+            A matrix or 2D array.
+
+        Returns
+        -------
+        Y : {matrix, ndarray}
+            A matrix or 2D array depending on the type of the input.
+
+        Notes
+        -----
+        This rmatmat wraps the user-specified rmatmat routine.
+
+        """
+        if not (issparse(X) or is_pydata_spmatrix(X)):
+            X = np.asanyarray(X)
+
+        if X.ndim != 2:
+            raise ValueError('expected 2-d ndarray or matrix, not %d-d'
+                             % X.ndim)
+
+        if X.shape[0] != self.shape[0]:
+            raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}')
+
+        try:
+            Y = self._rmatmat(X)
+        except Exception as e:
+            if issparse(X) or is_pydata_spmatrix(X):
+                raise TypeError(
+                    "Unable to multiply a LinearOperator with a sparse matrix."
+                    " Wrap the matrix in aslinearoperator() first."
+                ) from e
+            raise
+
+        if isinstance(Y, np.matrix):
+            Y = asmatrix(Y)
+        return Y
+
+    def _rmatmat(self, X):
+        """Default implementation of _rmatmat defers to rmatvec or adjoint."""
+        if type(self)._adjoint == LinearOperator._adjoint:
+            return np.hstack([self.rmatvec(col.reshape(-1, 1)) for col in X.T])
+        else:
+            return self.H.matmat(X)
+
+    def __call__(self, x):
+        return self@x
+
+    def __mul__(self, x):
+        return self.dot(x)
+
+    def __truediv__(self, other):
+        if not np.isscalar(other):
+            raise ValueError("Can only divide a linear operator by a scalar.")
+
+        return _ScaledLinearOperator(self, 1.0/other)
+
+    def dot(self, x):
+        """Matrix-matrix or matrix-vector multiplication.
+
+        Parameters
+        ----------
+        x : array_like
+            1-d or 2-d array, representing a vector or matrix.
+
+        Returns
+        -------
+        Ax : array
+            1-d or 2-d array (depending on the shape of x) that represents
+            the result of applying this linear operator on x.
+
+        """
+        if isinstance(x, LinearOperator):
+            return _ProductLinearOperator(self, x)
+        elif np.isscalar(x):
+            return _ScaledLinearOperator(self, x)
+        else:
+            if not issparse(x) and not is_pydata_spmatrix(x):
+                # Sparse matrices shouldn't be converted to numpy arrays.
+                x = np.asarray(x)
+
+            if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1:
+                return self.matvec(x)
+            elif x.ndim == 2:
+                return self.matmat(x)
+            else:
+                raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}')
+
+    def __matmul__(self, other):
+        if np.isscalar(other):
+            raise ValueError("Scalar operands are not allowed, "
+                             "use '*' instead")
+        return self.__mul__(other)
+
+    def __rmatmul__(self, other):
+        if np.isscalar(other):
+            raise ValueError("Scalar operands are not allowed, "
+                             "use '*' instead")
+        return self.__rmul__(other)
+
+    def __rmul__(self, x):
+        if np.isscalar(x):
+            return _ScaledLinearOperator(self, x)
+        else:
+            return self._rdot(x)
+
+    def _rdot(self, x):
+        """Matrix-matrix or matrix-vector multiplication from the right.
+
+        Parameters
+        ----------
+        x : array_like
+            1-d or 2-d array, representing a vector or matrix.
+
+        Returns
+        -------
+        xA : array
+            1-d or 2-d array (depending on the shape of x) that represents
+            the result of applying this linear operator on x from the right.
+
+        Notes
+        -----
+        This is copied from dot to implement right multiplication.
+        """
+        if isinstance(x, LinearOperator):
+            return _ProductLinearOperator(x, self)
+        elif np.isscalar(x):
+            return _ScaledLinearOperator(self, x)
+        else:
+            if not issparse(x) and not is_pydata_spmatrix(x):
+                # Sparse matrices shouldn't be converted to numpy arrays.
+                x = np.asarray(x)
+
+            # We use transpose instead of rmatvec/rmatmat to avoid
+            # unnecessary complex conjugation if possible.
+            if x.ndim == 1 or x.ndim == 2 and x.shape[0] == 1:
+                return self.T.matvec(x.T).T
+            elif x.ndim == 2:
+                return self.T.matmat(x.T).T
+            else:
+                raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}')
+
+    def __pow__(self, p):
+        if np.isscalar(p):
+            return _PowerLinearOperator(self, p)
+        else:
+            return NotImplemented
+
+    def __add__(self, x):
+        if isinstance(x, LinearOperator):
+            return _SumLinearOperator(self, x)
+        else:
+            return NotImplemented
+
+    def __neg__(self):
+        return _ScaledLinearOperator(self, -1)
+
+    def __sub__(self, x):
+        return self.__add__(-x)
+
+    def __repr__(self):
+        M,N = self.shape
+        if self.dtype is None:
+            dt = 'unspecified dtype'
+        else:
+            dt = 'dtype=' + str(self.dtype)
+
+        return '<%dx%d %s with %s>' % (M, N, self.__class__.__name__, dt)
+
+    def adjoint(self):
+        """Hermitian adjoint.
+
+        Returns the Hermitian adjoint of self, aka the Hermitian
+        conjugate or Hermitian transpose. For a complex matrix, the
+        Hermitian adjoint is equal to the conjugate transpose.
+
+        Can be abbreviated self.H instead of self.adjoint().
+
+        Returns
+        -------
+        A_H : LinearOperator
+            Hermitian adjoint of self.
+        """
+        return self._adjoint()
+
+    H = property(adjoint)
+
+    def transpose(self):
+        """Transpose this linear operator.
+
+        Returns a LinearOperator that represents the transpose of this one.
+        Can be abbreviated self.T instead of self.transpose().
+        """
+        return self._transpose()
+
+    T = property(transpose)
+
+    def _adjoint(self):
+        """Default implementation of _adjoint; defers to rmatvec."""
+        return _AdjointLinearOperator(self)
+
+    def _transpose(self):
+        """ Default implementation of _transpose; defers to rmatvec + conj"""
+        return _TransposedLinearOperator(self)
+
+
+class _CustomLinearOperator(LinearOperator):
+    """Linear operator defined in terms of user-specified operations."""
+
+    def __init__(self, shape, matvec, rmatvec=None, matmat=None,
+                 dtype=None, rmatmat=None):
+        super().__init__(dtype, shape)
+
+        self.args = ()
+
+        self.__matvec_impl = matvec
+        self.__rmatvec_impl = rmatvec
+        self.__rmatmat_impl = rmatmat
+        self.__matmat_impl = matmat
+
+        self._init_dtype()
+
+    def _matmat(self, X):
+        if self.__matmat_impl is not None:
+            return self.__matmat_impl(X)
+        else:
+            return super()._matmat(X)
+
+    def _matvec(self, x):
+        return self.__matvec_impl(x)
+
+    def _rmatvec(self, x):
+        func = self.__rmatvec_impl
+        if func is None:
+            raise NotImplementedError("rmatvec is not defined")
+        return self.__rmatvec_impl(x)
+
+    def _rmatmat(self, X):
+        if self.__rmatmat_impl is not None:
+            return self.__rmatmat_impl(X)
+        else:
+            return super()._rmatmat(X)
+
+    def _adjoint(self):
+        return _CustomLinearOperator(shape=(self.shape[1], self.shape[0]),
+                                     matvec=self.__rmatvec_impl,
+                                     rmatvec=self.__matvec_impl,
+                                     matmat=self.__rmatmat_impl,
+                                     rmatmat=self.__matmat_impl,
+                                     dtype=self.dtype)
+
+
+class _AdjointLinearOperator(LinearOperator):
+    """Adjoint of arbitrary Linear Operator"""
+
+    def __init__(self, A):
+        shape = (A.shape[1], A.shape[0])
+        super().__init__(dtype=A.dtype, shape=shape)
+        self.A = A
+        self.args = (A,)
+
+    def _matvec(self, x):
+        return self.A._rmatvec(x)
+
+    def _rmatvec(self, x):
+        return self.A._matvec(x)
+
+    def _matmat(self, x):
+        return self.A._rmatmat(x)
+
+    def _rmatmat(self, x):
+        return self.A._matmat(x)
+
+class _TransposedLinearOperator(LinearOperator):
+    """Transposition of arbitrary Linear Operator"""
+
+    def __init__(self, A):
+        shape = (A.shape[1], A.shape[0])
+        super().__init__(dtype=A.dtype, shape=shape)
+        self.A = A
+        self.args = (A,)
+
+    def _matvec(self, x):
+        # NB. np.conj works also on sparse matrices
+        return np.conj(self.A._rmatvec(np.conj(x)))
+
+    def _rmatvec(self, x):
+        return np.conj(self.A._matvec(np.conj(x)))
+
+    def _matmat(self, x):
+        # NB. np.conj works also on sparse matrices
+        return np.conj(self.A._rmatmat(np.conj(x)))
+
+    def _rmatmat(self, x):
+        return np.conj(self.A._matmat(np.conj(x)))
+
+def _get_dtype(operators, dtypes=None):
+    if dtypes is None:
+        dtypes = []
+    for obj in operators:
+        if obj is not None and hasattr(obj, 'dtype'):
+            dtypes.append(obj.dtype)
+    return np.result_type(*dtypes)
+
+
+class _SumLinearOperator(LinearOperator):
+    def __init__(self, A, B):
+        if not isinstance(A, LinearOperator) or \
+                not isinstance(B, LinearOperator):
+            raise ValueError('both operands have to be a LinearOperator')
+        if A.shape != B.shape:
+            raise ValueError(f'cannot add {A} and {B}: shape mismatch')
+        self.args = (A, B)
+        super().__init__(_get_dtype([A, B]), A.shape)
+
+    def _matvec(self, x):
+        return self.args[0].matvec(x) + self.args[1].matvec(x)
+
+    def _rmatvec(self, x):
+        return self.args[0].rmatvec(x) + self.args[1].rmatvec(x)
+
+    def _rmatmat(self, x):
+        return self.args[0].rmatmat(x) + self.args[1].rmatmat(x)
+
+    def _matmat(self, x):
+        return self.args[0].matmat(x) + self.args[1].matmat(x)
+
+    def _adjoint(self):
+        A, B = self.args
+        return A.H + B.H
+
+
+class _ProductLinearOperator(LinearOperator):
+    def __init__(self, A, B):
+        if not isinstance(A, LinearOperator) or \
+                not isinstance(B, LinearOperator):
+            raise ValueError('both operands have to be a LinearOperator')
+        if A.shape[1] != B.shape[0]:
+            raise ValueError(f'cannot multiply {A} and {B}: shape mismatch')
+        super().__init__(_get_dtype([A, B]),
+                                                     (A.shape[0], B.shape[1]))
+        self.args = (A, B)
+
+    def _matvec(self, x):
+        return self.args[0].matvec(self.args[1].matvec(x))
+
+    def _rmatvec(self, x):
+        return self.args[1].rmatvec(self.args[0].rmatvec(x))
+
+    def _rmatmat(self, x):
+        return self.args[1].rmatmat(self.args[0].rmatmat(x))
+
+    def _matmat(self, x):
+        return self.args[0].matmat(self.args[1].matmat(x))
+
+    def _adjoint(self):
+        A, B = self.args
+        return B.H @ A.H
+
+
+class _ScaledLinearOperator(LinearOperator):
+    def __init__(self, A, alpha):
+        if not isinstance(A, LinearOperator):
+            raise ValueError('LinearOperator expected as A')
+        if not np.isscalar(alpha):
+            raise ValueError('scalar expected as alpha')
+        if isinstance(A, _ScaledLinearOperator):
+            A, alpha_original = A.args
+            # Avoid in-place multiplication so that we don't accidentally mutate
+            # the original prefactor.
+            alpha = alpha * alpha_original
+
+        dtype = _get_dtype([A], [type(alpha)])
+        super().__init__(dtype, A.shape)
+        self.args = (A, alpha)
+        # Note: args[1] is alpha (a scalar), so use `*` below, not `@`
+
+    def _matvec(self, x):
+        return self.args[1] * self.args[0].matvec(x)
+
+    def _rmatvec(self, x):
+        return np.conj(self.args[1]) * self.args[0].rmatvec(x)
+
+    def _rmatmat(self, x):
+        return np.conj(self.args[1]) * self.args[0].rmatmat(x)
+
+    def _matmat(self, x):
+        return self.args[1] * self.args[0].matmat(x)
+
+    def _adjoint(self):
+        A, alpha = self.args
+        return A.H * np.conj(alpha)
+
+
+class _PowerLinearOperator(LinearOperator):
+    def __init__(self, A, p):
+        if not isinstance(A, LinearOperator):
+            raise ValueError('LinearOperator expected as A')
+        if A.shape[0] != A.shape[1]:
+            raise ValueError(f'square LinearOperator expected, got {A!r}')
+        if not isintlike(p) or p < 0:
+            raise ValueError('non-negative integer expected as p')
+
+        super().__init__(_get_dtype([A]), A.shape)
+        self.args = (A, p)
+
+    def _power(self, fun, x):
+        res = np.array(x, copy=True)
+        for i in range(self.args[1]):
+            res = fun(res)
+        return res
+
+    def _matvec(self, x):
+        return self._power(self.args[0].matvec, x)
+
+    def _rmatvec(self, x):
+        return self._power(self.args[0].rmatvec, x)
+
+    def _rmatmat(self, x):
+        return self._power(self.args[0].rmatmat, x)
+
+    def _matmat(self, x):
+        return self._power(self.args[0].matmat, x)
+
+    def _adjoint(self):
+        A, p = self.args
+        return A.H ** p
+
+
+class MatrixLinearOperator(LinearOperator):
+    def __init__(self, A):
+        super().__init__(A.dtype, A.shape)
+        self.A = A
+        self.__adj = None
+        self.args = (A,)
+
+    def _matmat(self, X):
+        return self.A.dot(X)
+
+    def _adjoint(self):
+        if self.__adj is None:
+            self.__adj = _AdjointMatrixOperator(self.A)
+        return self.__adj
+
+
+class _AdjointMatrixOperator(MatrixLinearOperator):
+    def __init__(self, adjoint_array):
+        self.A = adjoint_array.T.conj()
+        self.args = (adjoint_array,)
+        self.shape = adjoint_array.shape[1], adjoint_array.shape[0]
+
+    @property
+    def dtype(self):
+        return self.args[0].dtype
+
+    def _adjoint(self):
+        return MatrixLinearOperator(self.args[0])
+
+
+class IdentityOperator(LinearOperator):
+    def __init__(self, shape, dtype=None):
+        super().__init__(dtype, shape)
+
+    def _matvec(self, x):
+        return x
+
+    def _rmatvec(self, x):
+        return x
+
+    def _rmatmat(self, x):
+        return x
+
+    def _matmat(self, x):
+        return x
+
+    def _adjoint(self):
+        return self
+
+
+def aslinearoperator(A):
+    """Return A as a LinearOperator.
+
+    'A' may be any of the following types:
+     - ndarray
+     - matrix
+     - sparse array (e.g. csr_array, lil_array, etc.)
+     - LinearOperator
+     - An object with .shape and .matvec attributes
+
+    See the LinearOperator documentation for additional information.
+
+    Notes
+    -----
+    If 'A' has no .dtype attribute, the data type is determined by calling
+    :func:`LinearOperator.matvec()` - set the .dtype attribute to prevent this
+    call upon the linear operator creation.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import aslinearoperator
+    >>> M = np.array([[1,2,3],[4,5,6]], dtype=np.int32)
+    >>> aslinearoperator(M)
+    <2x3 MatrixLinearOperator with dtype=int32>
+    """
+    if isinstance(A, LinearOperator):
+        return A
+
+    elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):
+        if A.ndim > 2:
+            raise ValueError('array must have ndim <= 2')
+        A = np.atleast_2d(np.asarray(A))
+        return MatrixLinearOperator(A)
+
+    elif issparse(A) or is_pydata_spmatrix(A):
+        return MatrixLinearOperator(A)
+
+    else:
+        if hasattr(A, 'shape') and hasattr(A, 'matvec'):
+            rmatvec = None
+            rmatmat = None
+            dtype = None
+
+            if hasattr(A, 'rmatvec'):
+                rmatvec = A.rmatvec
+            if hasattr(A, 'rmatmat'):
+                rmatmat = A.rmatmat
+            if hasattr(A, 'dtype'):
+                dtype = A.dtype
+            return LinearOperator(A.shape, A.matvec, rmatvec=rmatvec,
+                                  rmatmat=rmatmat, dtype=dtype)
+
+        else:
+            raise TypeError('type not understood')
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_norm.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_norm.py
new file mode 100644
index 0000000000000000000000000000000000000000..821ed02bb1b1d7c2047d5e5dcb3049cc2bf8ad02
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_norm.py
@@ -0,0 +1,195 @@
+"""Sparse matrix norms.
+
+"""
+import numpy as np
+from scipy.sparse import issparse
+from scipy.sparse.linalg import svds
+from scipy.sparse._sputils import convert_pydata_sparse_to_scipy
+import scipy.sparse as sp
+
+from numpy import sqrt, abs
+
+__all__ = ['norm']
+
+
+def _sparse_frobenius_norm(x):
+    data = sp._sputils._todata(x)
+    return np.linalg.norm(data)
+
+
+def norm(x, ord=None, axis=None):
+    """
+    Norm of a sparse matrix
+
+    This function is able to return one of seven different matrix norms,
+    depending on the value of the ``ord`` parameter.
+
+    Parameters
+    ----------
+    x : a sparse array
+        Input sparse array.
+    ord : {non-zero int, inf, -inf, 'fro'}, 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 `x` 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 `x`
+        is 1-D) or a matrix norm (when `x` is 2-D) is returned.
+
+    Returns
+    -------
+    n : float or ndarray
+
+    Notes
+    -----
+    Some of the ord are not implemented because some associated functions like,
+    _multi_svd_norm, are not yet available for sparse array.
+
+    This docstring is modified based on numpy.linalg.norm.
+    https://github.com/numpy/numpy/blob/main/numpy/linalg/linalg.py
+
+    The following norms can be calculated:
+
+    =====  ============================
+    ord    norm for sparse arrays
+    =====  ============================
+    None   Frobenius norm
+    'fro'  Frobenius norm
+    inf    max(sum(abs(x), axis=1))
+    -inf   min(sum(abs(x), axis=1))
+    0      abs(x).sum(axis=axis)
+    1      max(sum(abs(x), axis=0))
+    -1     min(sum(abs(x), axis=0))
+    2      Spectral norm (the largest singular value)
+    -2     Not implemented
+    other  Not implemented
+    =====  ============================
+
+    The Frobenius norm is given by [1]_:
+
+        :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
+
+    References
+    ----------
+    .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
+        Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_array, diags_array
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import norm
+    >>> a = np.arange(9) - 4
+    >>> 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]])
+
+    >>> b = csr_array(b)
+    >>> norm(b)
+    7.745966692414834
+    >>> norm(b, 'fro')
+    7.745966692414834
+    >>> norm(b, np.inf)
+    9
+    >>> norm(b, -np.inf)
+    2
+    >>> norm(b, 1)
+    7
+    >>> norm(b, -1)
+    6
+
+    The matrix 2-norm or the spectral norm is the largest singular
+    value, computed approximately and with limitations.
+
+    >>> b = diags_array([-1, 1], [0, 1], shape=(9, 10))
+    >>> norm(b, 2)
+    1.9753...
+    """
+    x = convert_pydata_sparse_to_scipy(x, target_format="csr")
+    if not issparse(x):
+        raise TypeError("input is not sparse. use numpy.linalg.norm")
+
+    # Check the default case first and handle it immediately.
+    if axis is None and ord in (None, 'fro', 'f'):
+        return _sparse_frobenius_norm(x)
+
+    # Some norms require functions that are not implemented for all types.
+    x = x.tocsr()
+
+    if axis is None:
+        axis = tuple(range(x.ndim))
+    elif not isinstance(axis, tuple):
+        msg = "'axis' must be None, an integer or a tuple of integers"
+        try:
+            int_axis = int(axis)
+        except TypeError as e:
+            raise TypeError(msg) from e
+        if axis != int_axis:
+            raise TypeError(msg)
+        axis = (int_axis,)
+
+    nd = x.ndim
+    if len(axis) == 2:
+        row_axis, col_axis = axis
+        if not (-nd <= row_axis < nd and -nd <= col_axis < nd):
+            message = f'Invalid axis {axis!r} for an array with shape {x.shape!r}'
+            raise ValueError(message)
+        if row_axis % nd == col_axis % nd:
+            raise ValueError('Duplicate axes given.')
+        if ord == 2:
+            # Only solver="lobpcg" supports all numpy dtypes
+            _, s, _ = svds(x, k=1, solver="lobpcg")
+            return s[0]
+        elif ord == -2:
+            raise NotImplementedError
+            #return _multi_svd_norm(x, row_axis, col_axis, amin)
+        elif ord == 1:
+            return abs(x).sum(axis=row_axis).max()
+        elif ord == np.inf:
+            return abs(x).sum(axis=col_axis).max()
+        elif ord == -1:
+            return abs(x).sum(axis=row_axis).min()
+        elif ord == -np.inf:
+            return abs(x).sum(axis=col_axis).min()
+        elif ord in (None, 'f', 'fro'):
+            # The axis order does not matter for this norm.
+            return _sparse_frobenius_norm(x)
+        else:
+            raise ValueError("Invalid norm order for matrices.")
+    elif len(axis) == 1:
+        a, = axis
+        if not (-nd <= a < nd):
+            message = f'Invalid axis {axis!r} for an array with shape {x.shape!r}'
+            raise ValueError(message)
+        if ord == np.inf:
+            M = abs(x).max(axis=a)
+        elif ord == -np.inf:
+            M = abs(x).min(axis=a)
+        elif ord == 0:
+            # Zero norm
+            M = (x != 0).sum(axis=a)
+        elif ord == 1:
+            # special case for speedup
+            M = abs(x).sum(axis=a)
+        elif ord in (2, None):
+            M = sqrt(abs(x).power(2).sum(axis=a))
+        else:
+            try:
+                ord + 1
+            except TypeError as e:
+                raise ValueError('Invalid norm order for vectors.') from e
+            M = np.power(abs(x).power(ord).sum(axis=a), 1 / ord)
+        if hasattr(M, 'toarray'):
+            return M.toarray().ravel()
+        elif hasattr(M, 'A'):
+            return M.A.ravel()
+        else:
+            return M.ravel()
+    else:
+        raise ValueError("Improper number of dimensions to norm.")
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9e806ab6fbd5a2910de823a1046bce225d60a13
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.py
@@ -0,0 +1,467 @@
+"""Sparse block 1-norm estimator.
+"""
+
+import numpy as np
+from scipy.sparse.linalg import aslinearoperator
+
+
+__all__ = ['onenormest']
+
+
+def onenormest(A, t=2, itmax=5, compute_v=False, compute_w=False):
+    """
+    Compute a lower bound of the 1-norm of a sparse array.
+
+    Parameters
+    ----------
+    A : ndarray or other linear operator
+        A linear operator that can be transposed and that can
+        produce matrix products.
+    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 array.
+    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.
+
+    Notes
+    -----
+    This is algorithm 2.4 of [1].
+
+    In [2] it is described as follows.
+    "This algorithm typically requires the evaluation of
+    about 4t matrix-vector products and almost invariably
+    produces a norm estimate (which is, in fact, a lower
+    bound on the norm) correct to within a factor 3."
+
+    .. versionadded:: 0.13.0
+
+    References
+    ----------
+    .. [1] 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. Vol. 21, No. 4, pp. 1185-1201.
+
+    .. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
+           "A new scaling and squaring algorithm for the matrix exponential."
+           SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import onenormest
+    >>> A = csc_array([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float)
+    >>> A.toarray()
+    array([[ 1.,  0.,  0.],
+           [ 5.,  8.,  2.],
+           [ 0., -1.,  0.]])
+    >>> onenormest(A)
+    9.0
+    >>> np.linalg.norm(A.toarray(), ord=1)
+    9.0
+    """
+
+    # Check the input.
+    A = aslinearoperator(A)
+    if A.shape[0] != A.shape[1]:
+        raise ValueError('expected the operator to act like a square matrix')
+
+    # If the operator size is small compared to t,
+    # then it is easier to compute the exact norm.
+    # Otherwise estimate the norm.
+    n = A.shape[1]
+    if t >= n:
+        A_explicit = np.asarray(aslinearoperator(A).matmat(np.identity(n)))
+        if A_explicit.shape != (n, n):
+            raise Exception('internal error: ',
+                    'unexpected shape ' + str(A_explicit.shape))
+        col_abs_sums = abs(A_explicit).sum(axis=0)
+        if col_abs_sums.shape != (n, ):
+            raise Exception('internal error: ',
+                    'unexpected shape ' + str(col_abs_sums.shape))
+        argmax_j = np.argmax(col_abs_sums)
+        v = elementary_vector(n, argmax_j)
+        w = A_explicit[:, argmax_j]
+        est = col_abs_sums[argmax_j]
+    else:
+        est, v, w, nmults, nresamples = _onenormest_core(A, A.H, t, itmax)
+
+    # Report the norm estimate along with some certificates of the estimate.
+    if compute_v or compute_w:
+        result = (est,)
+        if compute_v:
+            result += (v,)
+        if compute_w:
+            result += (w,)
+        return result
+    else:
+        return est
+
+
+def _blocked_elementwise(func):
+    """
+    Decorator for an elementwise function, to apply it blockwise along
+    first dimension, to avoid excessive memory usage in temporaries.
+    """
+    block_size = 2**20
+
+    def wrapper(x):
+        if x.shape[0] < block_size:
+            return func(x)
+        else:
+            y0 = func(x[:block_size])
+            y = np.zeros((x.shape[0],) + y0.shape[1:], dtype=y0.dtype)
+            y[:block_size] = y0
+            del y0
+            for j in range(block_size, x.shape[0], block_size):
+                y[j:j+block_size] = func(x[j:j+block_size])
+            return y
+    return wrapper
+
+
+@_blocked_elementwise
+def sign_round_up(X):
+    """
+    This should do the right thing for both real and complex matrices.
+
+    From Higham and Tisseur:
+    "Everything in this section remains valid for complex matrices
+    provided that sign(A) is redefined as the matrix (aij / |aij|)
+    (and sign(0) = 1) transposes are replaced by conjugate transposes."
+
+    """
+    Y = X.copy()
+    Y[Y == 0] = 1
+    Y /= np.abs(Y)
+    return Y
+
+
+@_blocked_elementwise
+def _max_abs_axis1(X):
+    return np.max(np.abs(X), axis=1)
+
+
+def _sum_abs_axis0(X):
+    block_size = 2**20
+    r = None
+    for j in range(0, X.shape[0], block_size):
+        y = np.sum(np.abs(X[j:j+block_size]), axis=0)
+        if r is None:
+            r = y
+        else:
+            r += y
+    return r
+
+
+def elementary_vector(n, i):
+    v = np.zeros(n, dtype=float)
+    v[i] = 1
+    return v
+
+
+def vectors_are_parallel(v, w):
+    # Columns are considered parallel when they are equal or negative.
+    # Entries are required to be in {-1, 1},
+    # which guarantees that the magnitudes of the vectors are identical.
+    if v.ndim != 1 or v.shape != w.shape:
+        raise ValueError('expected conformant vectors with entries in {-1,1}')
+    n = v.shape[0]
+    return np.dot(v, w) == n
+
+
+def every_col_of_X_is_parallel_to_a_col_of_Y(X, Y):
+    for v in X.T:
+        if not any(vectors_are_parallel(v, w) for w in Y.T):
+            return False
+    return True
+
+
+def column_needs_resampling(i, X, Y=None):
+    # column i of X needs resampling if either
+    # it is parallel to a previous column of X or
+    # it is parallel to a column of Y
+    n, t = X.shape
+    v = X[:, i]
+    if any(vectors_are_parallel(v, X[:, j]) for j in range(i)):
+        return True
+    if Y is not None:
+        if any(vectors_are_parallel(v, w) for w in Y.T):
+            return True
+    return False
+
+
+def resample_column(i, X):
+    X[:, i] = np.random.randint(0, 2, size=X.shape[0])*2 - 1
+
+
+def less_than_or_close(a, b):
+    return np.allclose(a, b) or (a < b)
+
+
+def _algorithm_2_2(A, AT, t):
+    """
+    This is Algorithm 2.2.
+
+    Parameters
+    ----------
+    A : ndarray or other linear operator
+        A linear operator that can produce matrix products.
+    AT : ndarray or other linear operator
+        The transpose of A.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+
+    Returns
+    -------
+    g : sequence
+        A non-negative decreasing vector
+        such that g[j] is a lower bound for the 1-norm
+        of the column of A of jth largest 1-norm.
+        The first entry of this vector is therefore a lower bound
+        on the 1-norm of the linear operator A.
+        This sequence has length t.
+    ind : sequence
+        The ith entry of ind is the index of the column A whose 1-norm
+        is given by g[i].
+        This sequence of indices has length t, and its entries are
+        chosen from range(n), possibly with repetition,
+        where n is the order of the operator A.
+
+    Notes
+    -----
+    This algorithm is mainly for testing.
+    It uses the 'ind' array in a way that is similar to
+    its usage in algorithm 2.4. This algorithm 2.2 may be easier to test,
+    so it gives a chance of uncovering bugs related to indexing
+    which could have propagated less noticeably to algorithm 2.4.
+
+    """
+    A_linear_operator = aslinearoperator(A)
+    AT_linear_operator = aslinearoperator(AT)
+    n = A_linear_operator.shape[0]
+
+    # Initialize the X block with columns of unit 1-norm.
+    X = np.ones((n, t))
+    if t > 1:
+        X[:, 1:] = np.random.randint(0, 2, size=(n, t-1))*2 - 1
+    X /= float(n)
+
+    # Iteratively improve the lower bounds.
+    # Track extra things, to assert invariants for debugging.
+    g_prev = None
+    h_prev = None
+    k = 1
+    ind = range(t)
+    while True:
+        Y = np.asarray(A_linear_operator.matmat(X))
+        g = _sum_abs_axis0(Y)
+        best_j = np.argmax(g)
+        g.sort()
+        g = g[::-1]
+        S = sign_round_up(Y)
+        Z = np.asarray(AT_linear_operator.matmat(S))
+        h = _max_abs_axis1(Z)
+
+        # If this algorithm runs for fewer than two iterations,
+        # then its return values do not have the properties indicated
+        # in the description of the algorithm.
+        # In particular, the entries of g are not 1-norms of any
+        # column of A until the second iteration.
+        # Therefore we will require the algorithm to run for at least
+        # two iterations, even though this requirement is not stated
+        # in the description of the algorithm.
+        if k >= 2:
+            if less_than_or_close(max(h), np.dot(Z[:, best_j], X[:, best_j])):
+                break
+        ind = np.argsort(h)[::-1][:t]
+        h = h[ind]
+        for j in range(t):
+            X[:, j] = elementary_vector(n, ind[j])
+
+        # Check invariant (2.2).
+        if k >= 2:
+            if not less_than_or_close(g_prev[0], h_prev[0]):
+                raise Exception('invariant (2.2) is violated')
+            if not less_than_or_close(h_prev[0], g[0]):
+                raise Exception('invariant (2.2) is violated')
+
+        # Check invariant (2.3).
+        if k >= 3:
+            for j in range(t):
+                if not less_than_or_close(g[j], g_prev[j]):
+                    raise Exception('invariant (2.3) is violated')
+
+        # Update for the next iteration.
+        g_prev = g
+        h_prev = h
+        k += 1
+
+    # Return the lower bounds and the corresponding column indices.
+    return g, ind
+
+
+def _onenormest_core(A, AT, t, itmax):
+    """
+    Compute a lower bound of the 1-norm of a sparse array.
+
+    Parameters
+    ----------
+    A : ndarray or other linear operator
+        A linear operator that can produce matrix products.
+    AT : ndarray or other linear operator
+        The transpose of A.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+    itmax : int, optional
+        Use at most this many iterations.
+
+    Returns
+    -------
+    est : float
+        An underestimate of the 1-norm of the sparse array.
+    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.
+    nmults : int, optional
+        The number of matrix products that were computed.
+    nresamples : int, optional
+        The number of times a parallel column was observed,
+        necessitating a re-randomization of the column.
+
+    Notes
+    -----
+    This is algorithm 2.4.
+
+    """
+    # This function is a more or less direct translation
+    # of Algorithm 2.4 from the Higham and Tisseur (2000) paper.
+    A_linear_operator = aslinearoperator(A)
+    AT_linear_operator = aslinearoperator(AT)
+    if itmax < 2:
+        raise ValueError('at least two iterations are required')
+    if t < 1:
+        raise ValueError('at least one column is required')
+    n = A.shape[0]
+    if t >= n:
+        raise ValueError('t should be smaller than the order of A')
+    # Track the number of big*small matrix multiplications
+    # and the number of resamplings.
+    nmults = 0
+    nresamples = 0
+    # "We now explain our choice of starting matrix.  We take the first
+    # column of X to be the vector of 1s [...] This has the advantage that
+    # for a matrix with nonnegative elements the algorithm converges
+    # with an exact estimate on the second iteration, and such matrices
+    # arise in applications [...]"
+    X = np.ones((n, t), dtype=float)
+    # "The remaining columns are chosen as rand{-1,1},
+    # with a check for and correction of parallel columns,
+    # exactly as for S in the body of the algorithm."
+    if t > 1:
+        for i in range(1, t):
+            # These are technically initial samples, not resamples,
+            # so the resampling count is not incremented.
+            resample_column(i, X)
+        for i in range(t):
+            while column_needs_resampling(i, X):
+                resample_column(i, X)
+                nresamples += 1
+    # "Choose starting matrix X with columns of unit 1-norm."
+    X /= float(n)
+    # "indices of used unit vectors e_j"
+    ind_hist = np.zeros(0, dtype=np.intp)
+    est_old = 0
+    S = np.zeros((n, t), dtype=float)
+    k = 1
+    ind = None
+    while True:
+        Y = np.asarray(A_linear_operator.matmat(X))
+        nmults += 1
+        mags = _sum_abs_axis0(Y)
+        est = np.max(mags)
+        best_j = np.argmax(mags)
+        if est > est_old or k == 2:
+            if k >= 2:
+                ind_best = ind[best_j]
+            w = Y[:, best_j]
+        # (1)
+        if k >= 2 and est <= est_old:
+            est = est_old
+            break
+        est_old = est
+        S_old = S
+        if k > itmax:
+            break
+        S = sign_round_up(Y)
+        del Y
+        # (2)
+        if every_col_of_X_is_parallel_to_a_col_of_Y(S, S_old):
+            break
+        if t > 1:
+            # "Ensure that no column of S is parallel to another column of S
+            # or to a column of S_old by replacing columns of S by rand{-1,1}."
+            for i in range(t):
+                while column_needs_resampling(i, S, S_old):
+                    resample_column(i, S)
+                    nresamples += 1
+        del S_old
+        # (3)
+        Z = np.asarray(AT_linear_operator.matmat(S))
+        nmults += 1
+        h = _max_abs_axis1(Z)
+        del Z
+        # (4)
+        if k >= 2 and max(h) == h[ind_best]:
+            break
+        # "Sort h so that h_first >= ... >= h_last
+        # and re-order ind correspondingly."
+        #
+        # Later on, we will need at most t+len(ind_hist) largest
+        # entries, so drop the rest
+        ind = np.argsort(h)[::-1][:t+len(ind_hist)].copy()
+        del h
+        if t > 1:
+            # (5)
+            # Break if the most promising t vectors have been visited already.
+            if np.isin(ind[:t], ind_hist).all():
+                break
+            # Put the most promising unvisited vectors at the front of the list
+            # and put the visited vectors at the end of the list.
+            # Preserve the order of the indices induced by the ordering of h.
+            seen = np.isin(ind, ind_hist)
+            ind = np.concatenate((ind[~seen], ind[seen]))
+        for j in range(t):
+            X[:, j] = elementary_vector(n, ind[j])
+
+        new_ind = ind[:t][~np.isin(ind[:t], ind_hist)]
+        ind_hist = np.concatenate((ind_hist, new_ind))
+        k += 1
+    v = elementary_vector(n, ind_best)
+    return est, v, w, nmults, nresamples
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d7415e1ec9a7e03b94dd8893935d46294b4b215
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py
@@ -0,0 +1,948 @@
+import numpy as np
+from scipy.sparse.linalg import LinearOperator
+from scipy.sparse import kron, eye, dia_array
+
+__all__ = ['LaplacianNd']
+# Sakurai and Mikota classes are intended for tests and benchmarks
+# and explicitly not included in the public API of this module.
+
+
+class LaplacianNd(LinearOperator):
+    """
+    The grid Laplacian in ``N`` dimensions and its eigenvalues/eigenvectors.
+
+    Construct Laplacian on a uniform rectangular grid in `N` dimensions
+    and output its eigenvalues and eigenvectors.
+    The Laplacian ``L`` is square, negative definite, real symmetric array
+    with signed integer entries and zeros otherwise.
+
+    Parameters
+    ----------
+    grid_shape : tuple
+        A tuple of integers of length ``N`` (corresponding to the dimension of
+        the Lapacian), where each entry gives the size of that dimension. The
+        Laplacian matrix is square of the size ``np.prod(grid_shape)``.
+    boundary_conditions : {'neumann', 'dirichlet', 'periodic'}, optional
+        The type of the boundary conditions on the boundaries of the grid.
+        Valid values are ``'dirichlet'`` or ``'neumann'``(default) or
+        ``'periodic'``.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.int8``.
+
+    Methods
+    -------
+    toarray()
+        Construct a dense array from Laplacian data
+    tosparse()
+        Construct a sparse array from Laplacian data
+    eigenvalues(m=None)
+        Construct a 1D array of `m` largest (smallest in absolute value)
+        eigenvalues of the Laplacian matrix in ascending order.
+    eigenvectors(m=None):
+        Construct the array with columns made of `m` eigenvectors (``float``)
+        of the ``Nd`` Laplacian corresponding to the `m` ordered eigenvalues.
+
+    .. versionadded:: 1.12.0
+
+    Notes
+    -----
+    Compared to the MATLAB/Octave implementation [1] of 1-, 2-, and 3-D
+    Laplacian, this code allows the arbitrary N-D case and the matrix-free
+    callable option, but is currently limited to pure Dirichlet, Neumann or
+    Periodic boundary conditions only.
+
+    The Laplacian matrix of a graph (`scipy.sparse.csgraph.laplacian`) of a
+    rectangular grid corresponds to the negative Laplacian with the Neumann
+    conditions, i.e., ``boundary_conditions = 'neumann'``.
+
+    All eigenvalues and eigenvectors of the discrete Laplacian operator for
+    an ``N``-dimensional  regular grid of shape `grid_shape` with the grid
+    step size ``h=1`` are analytically known [2].
+
+    References
+    ----------
+    .. [1] https://github.com/lobpcg/blopex/blob/master/blopex_\
+tools/matlab/laplacian/laplacian.m
+    .. [2] "Eigenvalues and eigenvectors of the second derivative", Wikipedia
+           https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors_\
+of_the_second_derivative
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import LaplacianNd
+    >>> from scipy.sparse import diags, csgraph
+    >>> from scipy.linalg import eigvalsh
+
+    The one-dimensional Laplacian demonstrated below for pure Neumann boundary
+    conditions on a regular grid with ``n=6`` grid points is exactly the
+    negative graph Laplacian for the undirected linear graph with ``n``
+    vertices using the sparse adjacency matrix ``G`` represented by the
+    famous tri-diagonal matrix:
+
+    >>> n = 6
+    >>> G = diags(np.ones(n - 1), 1, format='csr')
+    >>> Lf = csgraph.laplacian(G, symmetrized=True, form='function')
+    >>> grid_shape = (n, )
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann')
+    >>> np.array_equal(lap.matmat(np.eye(n)), -Lf(np.eye(n)))
+    True
+
+    Since all matrix entries of the Laplacian are integers, ``'int8'`` is
+    the default dtype for storing matrix representations.
+
+    >>> lap.tosparse()
+    
+    >>> lap.toarray()
+    array([[-1,  1,  0,  0,  0,  0],
+           [ 1, -2,  1,  0,  0,  0],
+           [ 0,  1, -2,  1,  0,  0],
+           [ 0,  0,  1, -2,  1,  0],
+           [ 0,  0,  0,  1, -2,  1],
+           [ 0,  0,  0,  0,  1, -1]], dtype=int8)
+    >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
+    True
+    >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
+    True
+
+    Any number of extreme eigenvalues and/or eigenvectors can be computed.
+    
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic')
+    >>> lap.eigenvalues()
+    array([-4., -3., -3., -1., -1.,  0.])
+    >>> lap.eigenvalues()[-2:]
+    array([-1.,  0.])
+    >>> lap.eigenvalues(2)
+    array([-1.,  0.])
+    >>> lap.eigenvectors(1)
+    array([[0.40824829],
+           [0.40824829],
+           [0.40824829],
+           [0.40824829],
+           [0.40824829],
+           [0.40824829]])
+    >>> lap.eigenvectors(2)
+    array([[ 0.5       ,  0.40824829],
+           [ 0.        ,  0.40824829],
+           [-0.5       ,  0.40824829],
+           [-0.5       ,  0.40824829],
+           [ 0.        ,  0.40824829],
+           [ 0.5       ,  0.40824829]])
+    >>> lap.eigenvectors()
+    array([[ 0.40824829,  0.28867513,  0.28867513,  0.5       ,  0.5       ,
+             0.40824829],
+           [-0.40824829, -0.57735027, -0.57735027,  0.        ,  0.        ,
+             0.40824829],
+           [ 0.40824829,  0.28867513,  0.28867513, -0.5       , -0.5       ,
+             0.40824829],
+           [-0.40824829,  0.28867513,  0.28867513, -0.5       , -0.5       ,
+             0.40824829],
+           [ 0.40824829, -0.57735027, -0.57735027,  0.        ,  0.        ,
+             0.40824829],
+           [-0.40824829,  0.28867513,  0.28867513,  0.5       ,  0.5       ,
+             0.40824829]])
+
+    The two-dimensional Laplacian is illustrated on a regular grid with
+    ``grid_shape = (2, 3)`` points in each dimension.
+
+    >>> grid_shape = (2, 3)
+    >>> n = np.prod(grid_shape)
+
+    Numeration of grid points is as follows:
+
+    >>> np.arange(n).reshape(grid_shape + (-1,))
+    array([[[0],
+            [1],
+            [2]],
+    
+           [[3],
+            [4],
+            [5]]])
+
+    Each of the boundary conditions ``'dirichlet'``, ``'periodic'``, and
+    ``'neumann'`` is illustrated separately; with ``'dirichlet'``
+
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='dirichlet')
+    >>> lap.tosparse()
+    
+    >>> lap.toarray()
+    array([[-4,  1,  0,  1,  0,  0],
+           [ 1, -4,  1,  0,  1,  0],
+           [ 0,  1, -4,  0,  0,  1],
+           [ 1,  0,  0, -4,  1,  0],
+           [ 0,  1,  0,  1, -4,  1],
+           [ 0,  0,  1,  0,  1, -4]], dtype=int8)
+    >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
+    True
+    >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
+    True
+    >>> lap.eigenvalues()
+    array([-6.41421356, -5.        , -4.41421356, -3.58578644, -3.        ,
+           -1.58578644])
+    >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
+    >>> np.allclose(lap.eigenvalues(), eigvals)
+    True
+    >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
+    ...             lap.eigenvectors() @ np.diag(lap.eigenvalues()))
+    True
+
+    with ``'periodic'``
+
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic')
+    >>> lap.tosparse()
+    
+    >>> lap.toarray()
+        array([[-4,  1,  1,  2,  0,  0],
+               [ 1, -4,  1,  0,  2,  0],
+               [ 1,  1, -4,  0,  0,  2],
+               [ 2,  0,  0, -4,  1,  1],
+               [ 0,  2,  0,  1, -4,  1],
+               [ 0,  0,  2,  1,  1, -4]], dtype=int8)
+    >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
+    True
+    >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
+    True
+    >>> lap.eigenvalues()
+    array([-7., -7., -4., -3., -3.,  0.])
+    >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
+    >>> np.allclose(lap.eigenvalues(), eigvals)
+    True
+    >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
+    ...             lap.eigenvectors() @ np.diag(lap.eigenvalues()))
+    True
+
+    and with ``'neumann'``
+
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann')
+    >>> lap.tosparse()
+    
+    >>> lap.toarray()
+    array([[-2,  1,  0,  1,  0,  0],
+           [ 1, -3,  1,  0,  1,  0],
+           [ 0,  1, -2,  0,  0,  1],
+           [ 1,  0,  0, -2,  1,  0],
+           [ 0,  1,  0,  1, -3,  1],
+           [ 0,  0,  1,  0,  1, -2]], dtype=int8)
+    >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
+    True
+    >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
+    True
+    >>> lap.eigenvalues()
+    array([-5., -3., -3., -2., -1.,  0.])
+    >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
+    >>> np.allclose(lap.eigenvalues(), eigvals)
+    True
+    >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
+    ...             lap.eigenvectors() @ np.diag(lap.eigenvalues()))
+    True
+
+    """
+
+    def __init__(self, grid_shape, *,
+                 boundary_conditions='neumann',
+                 dtype=np.int8):
+
+        if boundary_conditions not in ('dirichlet', 'neumann', 'periodic'):
+            raise ValueError(
+                f"Unknown value {boundary_conditions!r} is given for "
+                "'boundary_conditions' parameter. The valid options are "
+                "'dirichlet', 'periodic', and 'neumann' (default)."
+            )
+
+        self.grid_shape = grid_shape
+        self.boundary_conditions = boundary_conditions
+        # LaplacianNd folds all dimensions in `grid_shape` into a single one
+        N = np.prod(grid_shape)
+        super().__init__(dtype=dtype, shape=(N, N))
+
+    def _eigenvalue_ordering(self, m):
+        """Compute `m` largest eigenvalues in each of the ``N`` directions,
+        i.e., up to ``m * N`` total, order them and return `m` largest.
+        """
+        grid_shape = self.grid_shape
+        if m is None:
+            indices = np.indices(grid_shape)
+            Leig = np.zeros(grid_shape)
+        else:
+            grid_shape_min = min(grid_shape,
+                                 tuple(np.ones_like(grid_shape) * m))
+            indices = np.indices(grid_shape_min)
+            Leig = np.zeros(grid_shape_min)
+
+        for j, n in zip(indices, grid_shape):
+            if self.boundary_conditions == 'dirichlet':
+                Leig += -4 * np.sin(np.pi * (j + 1) / (2 * (n + 1))) ** 2
+            elif self.boundary_conditions == 'neumann':
+                Leig += -4 * np.sin(np.pi * j / (2 * n)) ** 2
+            else:  # boundary_conditions == 'periodic'
+                Leig += -4 * np.sin(np.pi * np.floor((j + 1) / 2) / n) ** 2
+
+        Leig_ravel = Leig.ravel()
+        ind = np.argsort(Leig_ravel)
+        eigenvalues = Leig_ravel[ind]
+        if m is not None:
+            eigenvalues = eigenvalues[-m:]
+            ind = ind[-m:]
+
+        return eigenvalues, ind
+
+    def eigenvalues(self, m=None):
+        """Return the requested number of eigenvalues.
+        
+        Parameters
+        ----------
+        m : int, optional
+            The positive number of smallest eigenvalues to return.
+            If not provided, then all eigenvalues will be returned.
+            
+        Returns
+        -------
+        eigenvalues : float array
+            The requested `m` smallest or all eigenvalues, in ascending order.
+        """
+        eigenvalues, _ = self._eigenvalue_ordering(m)
+        return eigenvalues
+
+    def _ev1d(self, j, n):
+        """Return 1 eigenvector in 1d with index `j`
+        and number of grid points `n` where ``j < n``. 
+        """
+        if self.boundary_conditions == 'dirichlet':
+            i = np.pi * (np.arange(n) + 1) / (n + 1)
+            ev = np.sqrt(2. / (n + 1.)) * np.sin(i * (j + 1))
+        elif self.boundary_conditions == 'neumann':
+            i = np.pi * (np.arange(n) + 0.5) / n
+            ev = np.sqrt((1. if j == 0 else 2.) / n) * np.cos(i * j)
+        else:  # boundary_conditions == 'periodic'
+            if j == 0:
+                ev = np.sqrt(1. / n) * np.ones(n)
+            elif j + 1 == n and n % 2 == 0:
+                ev = np.sqrt(1. / n) * np.tile([1, -1], n//2)
+            else:
+                i = 2. * np.pi * (np.arange(n) + 0.5) / n
+                ev = np.sqrt(2. / n) * np.cos(i * np.floor((j + 1) / 2))
+        # make small values exact zeros correcting round-off errors
+        # due to symmetry of eigenvectors the exact 0. is correct 
+        ev[np.abs(ev) < np.finfo(np.float64).eps] = 0.
+        return ev
+
+    def _one_eve(self, k):
+        """Return 1 eigenvector in Nd with multi-index `j`
+        as a tensor product of the corresponding 1d eigenvectors. 
+        """
+        phi = [self._ev1d(j, n) for j, n in zip(k, self.grid_shape)]
+        result = phi[0]
+        for phi in phi[1:]:
+            result = np.tensordot(result, phi, axes=0)
+        return np.asarray(result).ravel()
+
+    def eigenvectors(self, m=None):
+        """Return the requested number of eigenvectors for ordered eigenvalues.
+        
+        Parameters
+        ----------
+        m : int, optional
+            The positive number of eigenvectors to return. If not provided,
+            then all eigenvectors will be returned.
+            
+        Returns
+        -------
+        eigenvectors : float array
+            An array with columns made of the requested `m` or all eigenvectors.
+            The columns are ordered according to the `m` ordered eigenvalues. 
+        """
+        _, ind = self._eigenvalue_ordering(m)
+        if m is None:
+            grid_shape_min = self.grid_shape
+        else:
+            grid_shape_min = min(self.grid_shape,
+                                tuple(np.ones_like(self.grid_shape) * m))
+
+        N_indices = np.unravel_index(ind, grid_shape_min)
+        N_indices = [tuple(x) for x in zip(*N_indices)]
+        eigenvectors_list = [self._one_eve(k) for k in N_indices]
+        return np.column_stack(eigenvectors_list)
+
+    def toarray(self):
+        """
+        Converts the Laplacian data to a dense array.
+
+        Returns
+        -------
+        L : ndarray
+            The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``.
+
+        """
+        grid_shape = self.grid_shape
+        n = np.prod(grid_shape)
+        L = np.zeros([n, n], dtype=np.int8)
+        # Scratch arrays
+        L_i = np.empty_like(L)
+        Ltemp = np.empty_like(L)
+
+        for ind, dim in enumerate(grid_shape):
+            # Start zeroing out L_i
+            L_i[:] = 0
+            # Allocate the top left corner with the kernel of L_i
+            # Einsum returns writable view of arrays
+            np.einsum("ii->i", L_i[:dim, :dim])[:] = -2
+            np.einsum("ii->i", L_i[: dim - 1, 1:dim])[:] = 1
+            np.einsum("ii->i", L_i[1:dim, : dim - 1])[:] = 1
+
+            if self.boundary_conditions == 'neumann':
+                L_i[0, 0] = -1
+                L_i[dim - 1, dim - 1] = -1
+            elif self.boundary_conditions == 'periodic':
+                if dim > 1:
+                    L_i[0, dim - 1] += 1
+                    L_i[dim - 1, 0] += 1
+                else:
+                    L_i[0, 0] += 1
+
+            # kron is too slow for large matrices hence the next two tricks
+            # 1- kron(eye, mat) is block_diag(mat, mat, ...)
+            # 2- kron(mat, eye) can be performed by 4d stride trick
+
+            # 1-
+            new_dim = dim
+            # for block_diag we tile the top left portion on the diagonal
+            if ind > 0:
+                tiles = np.prod(grid_shape[:ind])
+                for j in range(1, tiles):
+                    L_i[j*dim:(j+1)*dim, j*dim:(j+1)*dim] = L_i[:dim, :dim]
+                    new_dim += dim
+            # 2-
+            # we need the keep L_i, but reset the array
+            Ltemp[:new_dim, :new_dim] = L_i[:new_dim, :new_dim]
+            tiles = int(np.prod(grid_shape[ind+1:]))
+            # Zero out the top left, the rest is already 0
+            L_i[:new_dim, :new_dim] = 0
+            idx = [x for x in range(tiles)]
+            L_i.reshape(
+                (new_dim, tiles,
+                 new_dim, tiles)
+                )[:, idx, :, idx] = Ltemp[:new_dim, :new_dim]
+
+            L += L_i
+
+        return L.astype(self.dtype)
+
+    def tosparse(self):
+        """
+        Constructs a sparse array from the Laplacian data. The returned sparse
+        array format is dependent on the selected boundary conditions.
+
+        Returns
+        -------
+        L : scipy.sparse.sparray
+            The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``.
+
+        """
+        N = len(self.grid_shape)
+        p = np.prod(self.grid_shape)
+        L = dia_array((p, p), dtype=np.int8)
+
+        for i in range(N):
+            dim = self.grid_shape[i]
+            data = np.ones([3, dim], dtype=np.int8)
+            data[1, :] *= -2
+
+            if self.boundary_conditions == 'neumann':
+                data[1, 0] = -1
+                data[1, -1] = -1
+
+            L_i = dia_array((data, [-1, 0, 1]), shape=(dim, dim),
+                            dtype=np.int8
+                            )
+
+            if self.boundary_conditions == 'periodic':
+                t = dia_array((dim, dim), dtype=np.int8)
+                t.setdiag([1], k=-dim+1)
+                t.setdiag([1], k=dim-1)
+                L_i += t
+
+            for j in range(i):
+                L_i = kron(eye(self.grid_shape[j], dtype=np.int8), L_i)
+            for j in range(i + 1, N):
+                L_i = kron(L_i, eye(self.grid_shape[j], dtype=np.int8))
+            L += L_i
+        return L.astype(self.dtype)
+
+    def _matvec(self, x):
+        grid_shape = self.grid_shape
+        N = len(grid_shape)
+        X = x.reshape(grid_shape + (-1,))
+        Y = -2 * N * X
+        for i in range(N):
+            Y += np.roll(X, 1, axis=i)
+            Y += np.roll(X, -1, axis=i)
+            if self.boundary_conditions in ('neumann', 'dirichlet'):
+                Y[(slice(None),)*i + (0,) + (slice(None),)*(N-i-1)
+                  ] -= np.roll(X, 1, axis=i)[
+                    (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
+                ]
+                Y[
+                    (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
+                ] -= np.roll(X, -1, axis=i)[
+                    (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
+                ]
+
+                if self.boundary_conditions == 'neumann':
+                    Y[
+                        (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
+                    ] += np.roll(X, 0, axis=i)[
+                        (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
+                    ]
+                    Y[
+                        (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
+                    ] += np.roll(X, 0, axis=i)[
+                        (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
+                    ]
+
+        return Y.reshape(-1, X.shape[-1])
+
+    def _matmat(self, x):
+        return self._matvec(x)
+
+    def _adjoint(self):
+        return self
+
+    def _transpose(self):
+        return self
+
+
+class Sakurai(LinearOperator):
+    """
+    Construct a Sakurai matrix in various formats and its eigenvalues.
+
+    Constructs the "Sakurai" matrix motivated by reference [1]_:
+    square real symmetric positive definite and 5-diagonal
+    with the main diagonal ``[5, 6, 6, ..., 6, 6, 5], the ``+1`` and ``-1``
+    diagonals filled with ``-4``, and the ``+2`` and ``-2`` diagonals
+    made of ``1``. Its eigenvalues are analytically known to be
+    ``16. * np.power(np.cos(0.5 * k * np.pi / (n + 1)), 4)``.
+    The matrix gets ill-conditioned with its size growing.
+    It is useful for testing and benchmarking sparse eigenvalue solvers
+    especially those taking advantage of its banded 5-diagonal structure.
+    See the notes below for details.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrix.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.int8``.
+
+    Methods
+    -------
+    toarray()
+        Construct a dense array from Laplacian data
+    tosparse()
+        Construct a sparse array from Laplacian data
+    tobanded()
+        The Sakurai matrix in the format for banded symmetric matrices,
+        i.e., (3, n) ndarray with 3 upper diagonals
+        placing the main diagonal at the bottom.
+    eigenvalues
+        All eigenvalues of the Sakurai matrix ordered ascending.
+
+    Notes
+    -----
+    Reference [1]_ introduces a generalized eigenproblem for the matrix pair
+    `A` and `B` where `A` is the identity so we turn it into an eigenproblem
+    just for the matrix `B` that this function outputs in various formats
+    together with its eigenvalues.
+    
+    .. versionadded:: 1.12.0
+
+    References
+    ----------
+    .. [1] T. Sakurai, H. Tadano, Y. Inadomi, and U. Nagashima,
+       "A moment-based method for large-scale generalized
+       eigenvalue problems",
+       Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg._special_sparse_arrays import Sakurai
+    >>> from scipy.linalg import eig_banded
+    >>> n = 6
+    >>> sak = Sakurai(n)
+
+    Since all matrix entries are small integers, ``'int8'`` is
+    the default dtype for storing matrix representations.
+
+    >>> sak.toarray()
+    array([[ 5, -4,  1,  0,  0,  0],
+           [-4,  6, -4,  1,  0,  0],
+           [ 1, -4,  6, -4,  1,  0],
+           [ 0,  1, -4,  6, -4,  1],
+           [ 0,  0,  1, -4,  6, -4],
+           [ 0,  0,  0,  1, -4,  5]], dtype=int8)
+    >>> sak.tobanded()
+    array([[ 1,  1,  1,  1,  1,  1],
+           [-4, -4, -4, -4, -4, -4],
+           [ 5,  6,  6,  6,  6,  5]], dtype=int8)
+    >>> sak.tosparse()
+    
+    >>> np.array_equal(sak.dot(np.eye(n)), sak.tosparse().toarray())
+    True
+    >>> sak.eigenvalues()
+    array([0.03922866, 0.56703972, 2.41789479, 5.97822974,
+           10.54287655, 14.45473055])
+    >>> sak.eigenvalues(2)
+    array([0.03922866, 0.56703972])
+
+    The banded form can be used in scipy functions for banded matrices, e.g.,
+
+    >>> e = eig_banded(sak.tobanded(), eigvals_only=True)
+    >>> np.allclose(sak.eigenvalues, e, atol= n * n * n * np.finfo(float).eps)
+    True
+
+    """
+    def __init__(self, n, dtype=np.int8):
+        self.n = n
+        self.dtype = dtype
+        shape = (n, n)
+        super().__init__(dtype, shape)
+
+    def eigenvalues(self, m=None):
+        """Return the requested number of eigenvalues.
+        
+        Parameters
+        ----------
+        m : int, optional
+            The positive number of smallest eigenvalues to return.
+            If not provided, then all eigenvalues will be returned.
+            
+        Returns
+        -------
+        eigenvalues : `np.float64` array
+            The requested `m` smallest or all eigenvalues, in ascending order.
+        """
+        if m is None:
+            m = self.n
+        k = np.arange(self.n + 1 -m, self.n + 1)
+        return np.flip(16. * np.power(np.cos(0.5 * k * np.pi / (self.n + 1)), 4))
+
+    def tobanded(self):
+        """
+        Construct the Sakurai matrix as a banded array.
+        """
+        d0 = np.r_[5, 6 * np.ones(self.n - 2, dtype=self.dtype), 5]
+        d1 = -4 * np.ones(self.n, dtype=self.dtype)
+        d2 = np.ones(self.n, dtype=self.dtype)
+        return np.array([d2, d1, d0]).astype(self.dtype)
+
+    def tosparse(self):
+        """
+        Construct the Sakurai matrix is a sparse format.
+        """
+        from scipy.sparse import spdiags
+        d = self.tobanded()
+        # the banded format has the main diagonal at the bottom
+        # `spdiags` has no `dtype` parameter so inherits dtype from banded
+        return spdiags([d[0], d[1], d[2], d[1], d[0]], [-2, -1, 0, 1, 2],
+                       self.n, self.n)
+
+    def toarray(self):
+        return self.tosparse().toarray()
+    
+    def _matvec(self, x):
+        """
+        Construct matrix-free callable banded-matrix-vector multiplication by
+        the Sakurai matrix without constructing or storing the matrix itself
+        using the knowledge of its entries and the 5-diagonal format.
+        """
+        x = x.reshape(self.n, -1)
+        result_dtype = np.promote_types(x.dtype, self.dtype)
+        sx = np.zeros_like(x, dtype=result_dtype)
+        sx[0, :] = 5 * x[0, :] - 4 * x[1, :] + x[2, :]
+        sx[-1, :] = 5 * x[-1, :] - 4 * x[-2, :] + x[-3, :]
+        sx[1: -1, :] = (6 * x[1: -1, :] - 4 * (x[:-2, :] + x[2:, :])
+                      + np.pad(x[:-3, :], ((1, 0), (0, 0)))
+                      + np.pad(x[3:, :], ((0, 1), (0, 0))))
+        return sx
+
+    def _matmat(self, x):
+        """
+        Construct matrix-free callable matrix-matrix multiplication by
+        the Sakurai matrix without constructing or storing the matrix itself
+        by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
+        """        
+        return self._matvec(x)
+
+    def _adjoint(self):
+        return self
+
+    def _transpose(self):
+        return self
+
+
+class MikotaM(LinearOperator):
+    """
+    Construct a mass matrix in various formats of Mikota pair.
+
+    The mass matrix `M` is square real diagonal
+    positive definite with entries that are reciprocal to integers.
+
+    Parameters
+    ----------
+    shape : tuple of int
+        The shape of the matrix.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.float64``.
+
+    Methods
+    -------
+    toarray()
+        Construct a dense array from Mikota data
+    tosparse()
+        Construct a sparse array from Mikota data
+    tobanded()
+        The format for banded symmetric matrices,
+        i.e., (1, n) ndarray with the main diagonal.
+    """
+    def __init__(self, shape, dtype=np.float64):
+        self.shape = shape
+        self.dtype = dtype
+        super().__init__(dtype, shape)
+
+    def _diag(self):
+        # The matrix is constructed from its diagonal 1 / [1, ..., N+1];
+        # compute in a function to avoid duplicated code & storage footprint
+        return (1. / np.arange(1, self.shape[0] + 1)).astype(self.dtype)
+
+    def tobanded(self):
+        return self._diag()
+
+    def tosparse(self):
+        from scipy.sparse import diags
+        return diags([self._diag()], [0], shape=self.shape, dtype=self.dtype)
+
+    def toarray(self):
+        return np.diag(self._diag()).astype(self.dtype)
+
+    def _matvec(self, x):
+        """
+        Construct matrix-free callable banded-matrix-vector multiplication by
+        the Mikota mass matrix without constructing or storing the matrix itself
+        using the knowledge of its entries and the diagonal format.
+        """
+        x = x.reshape(self.shape[0], -1)
+        return self._diag()[:, np.newaxis] * x
+
+    def _matmat(self, x):
+        """
+        Construct matrix-free callable matrix-matrix multiplication by
+        the Mikota mass matrix without constructing or storing the matrix itself
+        by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
+        """     
+        return self._matvec(x)
+
+    def _adjoint(self):
+        return self
+
+    def _transpose(self):
+        return self
+
+
+class MikotaK(LinearOperator):
+    """
+    Construct a stiffness matrix in various formats of Mikota pair.
+
+    The stiffness matrix `K` is square real tri-diagonal symmetric
+    positive definite with integer entries. 
+
+    Parameters
+    ----------
+    shape : tuple of int
+        The shape of the matrix.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.int32``.
+
+    Methods
+    -------
+    toarray()
+        Construct a dense array from Mikota data
+    tosparse()
+        Construct a sparse array from Mikota data
+    tobanded()
+        The format for banded symmetric matrices,
+        i.e., (2, n) ndarray with 2 upper diagonals
+        placing the main diagonal at the bottom.
+    """
+    def __init__(self, shape, dtype=np.int32):
+        self.shape = shape
+        self.dtype = dtype
+        super().__init__(dtype, shape)
+        # The matrix is constructed from its diagonals;
+        # we precompute these to avoid duplicating the computation
+        n = shape[0]
+        self._diag0 = np.arange(2 * n - 1, 0, -2, dtype=self.dtype)
+        self._diag1 = - np.arange(n - 1, 0, -1, dtype=self.dtype)
+
+    def tobanded(self):
+        return np.array([np.pad(self._diag1, (1, 0), 'constant'), self._diag0])
+
+    def tosparse(self):
+        from scipy.sparse import diags
+        return diags([self._diag1, self._diag0, self._diag1], [-1, 0, 1],
+                     shape=self.shape, dtype=self.dtype)
+
+    def toarray(self):
+        return self.tosparse().toarray()
+
+    def _matvec(self, x):
+        """
+        Construct matrix-free callable banded-matrix-vector multiplication by
+        the Mikota stiffness matrix without constructing or storing the matrix
+        itself using the knowledge of its entries and the 3-diagonal format.
+        """
+        x = x.reshape(self.shape[0], -1)
+        result_dtype = np.promote_types(x.dtype, self.dtype)
+        kx = np.zeros_like(x, dtype=result_dtype)
+        d1 = self._diag1
+        d0 = self._diag0
+        kx[0, :] = d0[0] * x[0, :] + d1[0] * x[1, :]
+        kx[-1, :] = d1[-1] * x[-2, :] + d0[-1] * x[-1, :]
+        kx[1: -1, :] = (d1[:-1, None] * x[: -2, :]
+                        + d0[1: -1, None] * x[1: -1, :]
+                        + d1[1:, None] * x[2:, :])
+        return kx
+
+    def _matmat(self, x):
+        """
+        Construct matrix-free callable matrix-matrix multiplication by
+        the Stiffness mass matrix without constructing or storing the matrix itself
+        by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
+        """  
+        return self._matvec(x)
+
+    def _adjoint(self):
+        return self
+
+    def _transpose(self):
+        return self
+
+
+class MikotaPair:
+    """
+    Construct the Mikota pair of matrices in various formats and
+    eigenvalues of the generalized eigenproblem with them.
+
+    The Mikota pair of matrices [1, 2]_ models a vibration problem
+    of a linear mass-spring system with the ends attached where
+    the stiffness of the springs and the masses increase along
+    the system length such that vibration frequencies are subsequent
+    integers 1, 2, ..., `n` where `n` is the number of the masses. Thus,
+    eigenvalues of the generalized eigenvalue problem for
+    the matrix pair `K` and `M` where `K` is the system stiffness matrix
+    and `M` is the system mass matrix are the squares of the integers,
+    i.e., 1, 4, 9, ..., ``n * n``.
+
+    The stiffness matrix `K` is square real tri-diagonal symmetric
+    positive definite. The mass matrix `M` is diagonal with diagonal
+    entries 1, 1/2, 1/3, ...., ``1/n``. Both matrices get
+    ill-conditioned with `n` growing.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrices of the Mikota pair.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.float64``.
+
+    Attributes
+    ----------
+    eigenvalues : 1D ndarray, ``np.uint64``
+        All eigenvalues of the Mikota pair ordered ascending.
+
+    Methods
+    -------
+    MikotaK()
+        A `LinearOperator` custom object for the stiffness matrix.
+    MikotaM()
+        A `LinearOperator` custom object for the mass matrix.
+    
+    .. versionadded:: 1.12.0
+
+    References
+    ----------
+    .. [1] J. Mikota, "Frequency tuning of chain structure multibody oscillators
+       to place the natural frequencies at omega1 and N-1 integer multiples
+       omega2,..., omegaN", Z. Angew. Math. Mech. 81 (2001), S2, S201-S202.
+       Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004).
+    .. [2] Peter C. Muller and Metin Gurgoze,
+       "Natural frequencies of a multi-degree-of-freedom vibration system",
+       Proc. Appl. Math. Mech. 6, 319-320 (2006).
+       http://dx.doi.org/10.1002/pamm.200610141.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg._special_sparse_arrays import MikotaPair
+    >>> n = 6
+    >>> mik = MikotaPair(n)
+    >>> mik_k = mik.k
+    >>> mik_m = mik.m
+    >>> mik_k.toarray()
+    array([[11., -5.,  0.,  0.,  0.,  0.],
+           [-5.,  9., -4.,  0.,  0.,  0.],
+           [ 0., -4.,  7., -3.,  0.,  0.],
+           [ 0.,  0., -3.,  5., -2.,  0.],
+           [ 0.,  0.,  0., -2.,  3., -1.],
+           [ 0.,  0.,  0.,  0., -1.,  1.]])
+    >>> mik_k.tobanded()
+    array([[ 0., -5., -4., -3., -2., -1.],
+           [11.,  9.,  7.,  5.,  3.,  1.]])
+    >>> mik_m.tobanded()
+    array([1.        , 0.5       , 0.33333333, 0.25      , 0.2       ,
+        0.16666667])
+    >>> mik_k.tosparse()
+    
+    >>> mik_m.tosparse()
+    
+    >>> np.array_equal(mik_k(np.eye(n)), mik_k.toarray())
+    True
+    >>> np.array_equal(mik_m(np.eye(n)), mik_m.toarray())
+    True
+    >>> mik.eigenvalues()
+    array([ 1,  4,  9, 16, 25, 36])  
+    >>> mik.eigenvalues(2)
+    array([ 1,  4])
+
+    """
+    def __init__(self, n, dtype=np.float64):
+        self.n = n
+        self.dtype = dtype
+        self.shape = (n, n)
+        self.m = MikotaM(self.shape, self.dtype)
+        self.k = MikotaK(self.shape, self.dtype)
+
+    def eigenvalues(self, m=None):
+        """Return the requested number of eigenvalues.
+        
+        Parameters
+        ----------
+        m : int, optional
+            The positive number of smallest eigenvalues to return.
+            If not provided, then all eigenvalues will be returned.
+            
+        Returns
+        -------
+        eigenvalues : `np.uint64` array
+            The requested `m` smallest or all eigenvalues, in ascending order.
+        """
+        if m is None:
+            m = self.n
+        arange_plus1 = np.arange(1, m + 1, dtype=np.uint64)
+        return arange_plus1 * arange_plus1
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_svdp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_svdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd64c6d0c3069eceb5a347111f1ac77bea8ea942
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_svdp.py
@@ -0,0 +1,309 @@
+"""
+Python wrapper for PROPACK
+--------------------------
+
+PROPACK is a collection of Fortran routines for iterative computation
+of partial SVDs of large matrices or linear operators.
+
+Based on BSD licensed pypropack project:
+  http://github.com/jakevdp/pypropack
+  Author: Jake Vanderplas 
+
+PROPACK source is BSD licensed, and available at
+  http://soi.stanford.edu/~rmunk/PROPACK/
+"""
+
+__all__ = ['_svdp']
+
+import numpy as np
+
+from scipy.sparse.linalg import aslinearoperator
+from scipy.linalg import LinAlgError
+
+from ._propack import _spropack  # type: ignore[attr-defined]
+from ._propack import _dpropack  # type: ignore[attr-defined]
+from ._propack import _cpropack  # type: ignore[attr-defined]
+from ._propack import _zpropack  # type: ignore[attr-defined]
+
+
+_lansvd_dict = {
+    'f': _spropack.slansvd,
+    'd': _dpropack.dlansvd,
+    'F': _cpropack.clansvd,
+    'D': _zpropack.zlansvd,
+}
+
+
+_lansvd_irl_dict = {
+    'f': _spropack.slansvd_irl,
+    'd': _dpropack.dlansvd_irl,
+    'F': _cpropack.clansvd_irl,
+    'D': _zpropack.zlansvd_irl,
+}
+
+_which_converter = {
+    'LM': 'L',
+    'SM': 'S',
+}
+
+
+class _AProd:
+    """
+    Wrapper class for linear operator
+
+    The call signature of the __call__ method matches the callback of
+    the PROPACK routines.
+    """
+    def __init__(self, A):
+        try:
+            self.A = aslinearoperator(A)
+        except TypeError:
+            self.A = aslinearoperator(np.asarray(A))
+
+    def __call__(self, transa, m, n, x, y, sparm, iparm):
+        if transa == 'n':
+            y[:] = self.A.matvec(x)
+        else:
+            y[:] = self.A.rmatvec(x)
+
+    @property
+    def shape(self):
+        return self.A.shape
+
+    @property
+    def dtype(self):
+        try:
+            return self.A.dtype
+        except AttributeError:
+            return self.A.matvec(np.zeros(self.A.shape[1])).dtype
+
+
+def _svdp(A, k, which='LM', irl_mode=True, kmax=None,
+          compute_u=True, compute_v=True, v0=None, full_output=False, tol=0,
+          delta=None, eta=None, anorm=0, cgs=False, elr=True,
+          min_relgap=0.002, shifts=None, maxiter=None, rng=None):
+    """
+    Compute the singular value decomposition of a linear operator using PROPACK
+
+    Parameters
+    ----------
+    A : array_like, sparse matrix, or LinearOperator
+        Operator for which SVD will be computed.  If `A` is a LinearOperator
+        object, it must define both ``matvec`` and ``rmatvec`` methods.
+    k : int
+        Number of singular values/vectors to compute
+    which : {"LM", "SM"}
+        Which singular triplets to compute:
+        - 'LM': compute triplets corresponding to the `k` largest singular
+                values
+        - 'SM': compute triplets corresponding to the `k` smallest singular
+                values
+        `which='SM'` requires `irl_mode=True`.  Computes largest singular
+        values by default.
+    irl_mode : bool, optional
+        If `True`, then compute SVD using IRL (implicitly restarted Lanczos)
+        mode.  Default is `True`.
+    kmax : int, optional
+        Maximal number of iterations / maximal dimension of the Krylov
+        subspace. Default is ``10 * k``.
+    compute_u : bool, optional
+        If `True` (default) then compute left singular vectors, `u`.
+    compute_v : bool, optional
+        If `True` (default) then compute right singular vectors, `v`.
+    tol : float, optional
+        The desired relative accuracy for computed singular values.
+        If not specified, it will be set based on machine precision.
+    v0 : array_like, optional
+        Starting vector for iterations: must be of length ``A.shape[0]``.
+        If not specified, PROPACK will generate a starting vector.
+    full_output : bool, optional
+        If `True`, then return sigma_bound.  Default is `False`.
+    delta : float, optional
+        Level of orthogonality to maintain between Lanczos vectors.
+        Default is set based on machine precision.
+    eta : float, optional
+        Orthogonality cutoff.  During reorthogonalization, vectors with
+        component larger than `eta` along the Lanczos vector will be purged.
+        Default is set based on machine precision.
+    anorm : float, optional
+        Estimate of ``||A||``.  Default is ``0``.
+    cgs : bool, optional
+        If `True`, reorthogonalization is done using classical Gram-Schmidt.
+        If `False` (default), it is done using modified Gram-Schmidt.
+    elr : bool, optional
+        If `True` (default), then extended local orthogonality is enforced
+        when obtaining singular vectors.
+    min_relgap : float, optional
+        The smallest relative gap allowed between any shift in IRL mode.
+        Default is ``0.001``.  Accessed only if ``irl_mode=True``.
+    shifts : int, optional
+        Number of shifts per restart in IRL mode.  Default is determined
+        to satisfy ``k <= min(kmax-shifts, m, n)``.  Must be
+        >= 0, but choosing 0 might lead to performance degradation.
+        Accessed only if ``irl_mode=True``.
+    maxiter : int, optional
+        Maximum number of restarts in IRL mode.  Default is ``1000``.
+        Accessed only if ``irl_mode=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
+    -------
+    u : ndarray
+        The `k` largest (``which="LM"``) or smallest (``which="SM"``) left
+        singular vectors, ``shape == (A.shape[0], 3)``, returned only if
+        ``compute_u=True``.
+    sigma : ndarray
+        The top `k` singular values, ``shape == (k,)``
+    vt : ndarray
+        The `k` largest (``which="LM"``) or smallest (``which="SM"``) right
+        singular vectors, ``shape == (3, A.shape[1])``, returned only if
+        ``compute_v=True``.
+    sigma_bound : ndarray
+        the error bounds on the singular values sigma, returned only if
+        ``full_output=True``.
+
+    """
+    if rng is None:
+        raise ValueError("`rng` must be a normalized numpy.random.Generator instance")
+
+    which = which.upper()
+    if which not in {'LM', 'SM'}:
+        raise ValueError("`which` must be either 'LM' or 'SM'")
+    if not irl_mode and which == 'SM':
+        raise ValueError("`which`='SM' requires irl_mode=True")
+
+    aprod = _AProd(A)
+    typ = aprod.dtype.char
+
+    try:
+        lansvd_irl = _lansvd_irl_dict[typ]
+        lansvd = _lansvd_dict[typ]
+    except KeyError:
+        # work with non-supported types using native system precision
+        if np.iscomplexobj(np.empty(0, dtype=typ)):
+            typ = np.dtype(complex).char
+        else:
+            typ = np.dtype(float).char
+        lansvd_irl = _lansvd_irl_dict[typ]
+        lansvd = _lansvd_dict[typ]
+
+    m, n = aprod.shape
+    if (k < 1) or (k > min(m, n)):
+        raise ValueError("k must be positive and not greater than m or n")
+
+    if kmax is None:
+        kmax = 10*k
+    if maxiter is None:
+        maxiter = 1000
+
+    # guard against unnecessarily large kmax
+    kmax = min(m + 1, n + 1, kmax)
+    if kmax < k:
+        raise ValueError(
+            "kmax must be greater than or equal to k, "
+            f"but kmax ({kmax}) < k ({k})")
+
+    # convert python args to fortran args
+    jobu = 'y' if compute_u else 'n'
+    jobv = 'y' if compute_v else 'n'
+
+    # these will be the output arrays
+    u = np.zeros((m, kmax + 1), order='F', dtype=typ)
+    v = np.zeros((n, kmax), order='F', dtype=typ)
+
+    # Specify the starting vector.  if v0 is all zero, PROPACK will generate
+    # a random starting vector: the random seed cannot be controlled in that
+    # case, so we'll instead use numpy to generate a random vector
+    if v0 is None:
+        u[:, 0] = rng.uniform(size=m)
+        if np.iscomplexobj(np.empty(0, dtype=typ)):  # complex type
+            u[:, 0] += 1j * rng.uniform(size=m)
+    else:
+        try:
+            u[:, 0] = v0
+        except ValueError:
+            raise ValueError(f"v0 must be of length {m}")
+
+    # process options for the fit
+    if delta is None:
+        delta = np.sqrt(np.finfo(typ).eps)
+    if eta is None:
+        eta = np.finfo(typ).eps ** 0.75
+
+    if irl_mode:
+        doption = np.array((delta, eta, anorm, min_relgap), dtype=typ.lower())
+
+        # validate or find default shifts
+        if shifts is None:
+            shifts = kmax - k
+        if k > min(kmax - shifts, m, n):
+            raise ValueError('shifts must satisfy '
+                             'k <= min(kmax-shifts, m, n)!')
+        elif shifts < 0:
+            raise ValueError('shifts must be >= 0!')
+
+    else:
+        doption = np.array((delta, eta, anorm), dtype=typ.lower())
+
+    ioption = np.array((int(bool(cgs)), int(bool(elr))), dtype='i')
+
+    # If computing `u` or `v` (left and right singular vectors,
+    # respectively), `blocksize` controls how large a fraction of the
+    # work is done via fast BLAS level 3 operations.  A larger blocksize
+    # may lead to faster computation at the expense of greater memory
+    # consumption.  `blocksize` must be ``>= 1``.  Choosing blocksize
+    # of 16, but docs don't specify; it's almost surely a
+    # power of 2.
+    blocksize = 16
+
+    # Determine lwork & liwork:
+    # the required lengths are specified in the PROPACK documentation
+    if compute_u or compute_v:
+        lwork = m + n + 9*kmax + 5*kmax*kmax + 4 + max(
+            3*kmax*kmax + 4*kmax + 4,
+            blocksize*max(m, n))
+        liwork = 8*kmax
+    else:
+        lwork = m + n + 9*kmax + 2*kmax*kmax + 4 + max(m + n, 4*kmax + 4)
+        liwork = 2*kmax + 1
+    work = np.empty(lwork, dtype=typ.lower())
+    iwork = np.empty(liwork, dtype=np.int32)
+
+    # dummy arguments: these are passed to aprod, and not used in this wrapper
+    dparm = np.empty(1, dtype=typ.lower())
+    iparm = np.empty(1, dtype=np.int32)
+
+    if typ.isupper():
+        # PROPACK documentation is unclear on the required length of zwork.
+        # Use the same length Julia's wrapper uses
+        # see https://github.com/JuliaSmoothOptimizers/PROPACK.jl/
+        zwork = np.empty(m + n + 32*m, dtype=typ)
+        works = work, zwork, iwork
+    else:
+        works = work, iwork
+
+    if irl_mode:
+        u, sigma, bnd, v, info = lansvd_irl(_which_converter[which], jobu,
+                                            jobv, m, n, shifts, k, maxiter,
+                                            aprod, u, v, tol, *works, doption,
+                                            ioption, dparm, iparm)
+    else:
+        u, sigma, bnd, v, info = lansvd(jobu, jobv, m, n, k, aprod, u, v, tol,
+                                        *works, doption, ioption, dparm, iparm)
+
+    if info > 0:
+        raise LinAlgError(
+            f"An invariant subspace of dimension {info} was found.")
+    elif info < 0:
+        raise LinAlgError(
+            f"k={k} singular triplets did not converge within "
+            f"kmax={kmax} iterations")
+
+    # info == 0: The K largest (or smallest) singular triplets were computed
+    # successfully!
+
+    return u[:, :k], sigma, v[:, :k].conj().T, bnd
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/eigen.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/eigen.py
new file mode 100644
index 0000000000000000000000000000000000000000..588986d6650aad334e6a9a682ed76cef94295298
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/eigen.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.sparse.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'ArpackError', 'ArpackNoConvergence', 'ArpackError',
+    'eigs', 'eigsh', 'lobpcg', 'svds', 'test'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse.linalg", module="eigen",
+                                   private_modules=["_eigen"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/interface.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..24f40f185b1328b16e7e239e5a165cc6b1ed4317
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/interface.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.sparse.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'LinearOperator', 'aslinearoperator',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse.linalg", module="interface",
+                                   private_modules=["_interface"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/isolve.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/isolve.py
new file mode 100644
index 0000000000000000000000000000000000000000..e032ddd9c673be3bc8790adad3bdae1839127050
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/isolve.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.sparse.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'bicg', 'bicgstab', 'cg', 'cgs', 'gcrotmk', 'gmres',
+    'lgmres', 'lsmr', 'lsqr',
+    'minres', 'qmr', 'tfqmr', 'test'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse.linalg", module="isolve",
+                                   private_modules=["_isolve"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/matfuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ed877ff1aa6f5a5466ce94729b9225dcce37b36
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/matfuncs.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.sparse.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["expm", "inv", "spsolve", "LinearOperator"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse.linalg", module="matfuncs",
+                                   private_modules=["_matfuncs"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_interface.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..13bbcf16dbfc391a7e1b6fab666221d4c21b4c64
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_interface.py
@@ -0,0 +1,561 @@
+"""Test functions for the sparse.linalg._interface module
+"""
+
+from functools import partial
+from itertools import product
+import operator
+import pytest
+from pytest import raises as assert_raises, warns
+from numpy.testing import assert_, assert_equal
+
+import numpy as np
+import scipy.sparse as sparse
+
+import scipy.sparse.linalg._interface as interface
+from scipy.sparse._sputils import matrix
+from scipy._lib._gcutils import assert_deallocated, IS_PYPY
+
+
+class TestLinearOperator:
+    def setup_method(self):
+        self.A = np.array([[1,2,3],
+                           [4,5,6]])
+        self.B = np.array([[1,2],
+                           [3,4],
+                           [5,6]])
+        self.C = np.array([[1,2],
+                           [3,4]])
+
+    def test_matvec(self):
+        def get_matvecs(A):
+            return [{
+                        'shape': A.shape,
+                        'matvec': lambda x: np.dot(A, x).reshape(A.shape[0]),
+                        'rmatvec': lambda x: np.dot(A.T.conj(),
+                                                    x).reshape(A.shape[1])
+                    },
+                    {
+                        'shape': A.shape,
+                        'matvec': lambda x: np.dot(A, x),
+                        'rmatvec': lambda x: np.dot(A.T.conj(), x),
+                        'rmatmat': lambda x: np.dot(A.T.conj(), x),
+                        'matmat': lambda x: np.dot(A, x)
+                    }]
+
+        for matvecs in get_matvecs(self.A):
+            A = interface.LinearOperator(**matvecs)
+
+            assert_(A.args == ())
+
+            assert_equal(A.matvec(np.array([1,2,3])), [14,32])
+            assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]])
+            assert_equal(A @ np.array([1,2,3]), [14,32])
+            assert_equal(A @ np.array([[1],[2],[3]]), [[14],[32]])
+            assert_equal(A.dot(np.array([1,2,3])), [14,32])
+            assert_equal(A.dot(np.array([[1],[2],[3]])), [[14],[32]])
+
+            assert_equal(A.matvec(matrix([[1],[2],[3]])), [[14],[32]])
+            assert_equal(A @ matrix([[1],[2],[3]]), [[14],[32]])
+            assert_equal(A.dot(matrix([[1],[2],[3]])), [[14],[32]])
+
+            assert_equal((2*A)@[1,1,1], [12,30])
+            assert_equal((2 * A).rmatvec([1, 1]), [10, 14, 18])
+            assert_equal((2*A).H.matvec([1,1]), [10, 14, 18])
+            assert_equal((2*A).adjoint().matvec([1,1]), [10, 14, 18])
+            assert_equal((2*A)@[[1],[1],[1]], [[12],[30]])
+            assert_equal((2 * A).matmat([[1], [1], [1]]), [[12], [30]])
+            assert_equal((A*2)@[1,1,1], [12,30])
+            assert_equal((A*2)@[[1],[1],[1]], [[12],[30]])
+            assert_equal((2j*A)@[1,1,1], [12j,30j])
+            assert_equal((A+A)@[1,1,1], [12, 30])
+            assert_equal((A + A).rmatvec([1, 1]), [10, 14, 18])
+            assert_equal((A+A).H.matvec([1,1]), [10, 14, 18])
+            assert_equal((A+A).adjoint().matvec([1,1]), [10, 14, 18])
+            assert_equal((A+A)@[[1],[1],[1]], [[12], [30]])
+            assert_equal((A+A).matmat([[1],[1],[1]]), [[12], [30]])
+            assert_equal((-A)@[1,1,1], [-6,-15])
+            assert_equal((-A)@[[1],[1],[1]], [[-6],[-15]])
+            assert_equal((A-A)@[1,1,1], [0,0])
+            assert_equal((A - A) @ [[1], [1], [1]], [[0], [0]])
+
+            X = np.array([[1, 2], [3, 4]])
+            # A_asarray = np.array([[1, 2, 3], [4, 5, 6]])
+            assert_equal((2 * A).rmatmat(X), np.dot((2 * self.A).T, X))
+            assert_equal((A * 2).rmatmat(X), np.dot((self.A * 2).T, X))
+            assert_equal((2j * A).rmatmat(X),
+                         np.dot((2j * self.A).T.conj(), X))
+            assert_equal((A * 2j).rmatmat(X),
+                         np.dot((self.A * 2j).T.conj(), X))
+            assert_equal((A + A).rmatmat(X),
+                         np.dot((self.A + self.A).T, X))
+            assert_equal((A + 2j * A).rmatmat(X),
+                         np.dot((self.A + 2j * self.A).T.conj(), X))
+            assert_equal((-A).rmatmat(X), np.dot((-self.A).T, X))
+            assert_equal((A - A).rmatmat(X),
+                         np.dot((self.A - self.A).T, X))
+            assert_equal((2j * A).rmatmat(2j * X),
+                         np.dot((2j * self.A).T.conj(), 2j * X))
+
+            z = A+A
+            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is A)
+            z = 2*A
+            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] == 2)
+
+            assert_(isinstance(A.matvec([1, 2, 3]), np.ndarray))
+            assert_(isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray))
+            assert_(isinstance(A @ np.array([1,2,3]), np.ndarray))
+            assert_(isinstance(A @ np.array([[1],[2],[3]]), np.ndarray))
+            assert_(isinstance(A.dot(np.array([1,2,3])), np.ndarray))
+            assert_(isinstance(A.dot(np.array([[1],[2],[3]])), np.ndarray))
+
+            assert_(isinstance(A.matvec(matrix([[1],[2],[3]])), np.ndarray))
+            assert_(isinstance(A @ matrix([[1],[2],[3]]), np.ndarray))
+            assert_(isinstance(A.dot(matrix([[1],[2],[3]])), np.ndarray))
+
+            assert_(isinstance(2*A, interface._ScaledLinearOperator))
+            assert_(isinstance(2j*A, interface._ScaledLinearOperator))
+            assert_(isinstance(A+A, interface._SumLinearOperator))
+            assert_(isinstance(-A, interface._ScaledLinearOperator))
+            assert_(isinstance(A-A, interface._SumLinearOperator))
+            assert_(isinstance(A/2, interface._ScaledLinearOperator))
+            assert_(isinstance(A/2j, interface._ScaledLinearOperator))
+            assert_(((A * 3) / 3).args[0] is A)  # check for simplification
+
+            # Test that prefactor is of _ScaledLinearOperator is not mutated
+            # when the operator is multiplied by a number
+            result = A @ np.array([1, 2, 3])
+            B = A * 3
+            C = A / 5
+            assert_equal(A @ np.array([1, 2, 3]), result)
+
+            assert_((2j*A).dtype == np.complex128)
+
+            # Test division by non-scalar
+            msg = "Can only divide a linear operator by a scalar."
+            with assert_raises(ValueError, match=msg):
+                A / np.array([1, 2])
+
+            assert_raises(ValueError, A.matvec, np.array([1,2]))
+            assert_raises(ValueError, A.matvec, np.array([1,2,3,4]))
+            assert_raises(ValueError, A.matvec, np.array([[1],[2]]))
+            assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]]))
+
+            assert_raises(ValueError, lambda: A@A)
+            assert_raises(ValueError, lambda: A**2)
+
+        for matvecsA, matvecsB in product(get_matvecs(self.A),
+                                          get_matvecs(self.B)):
+            A = interface.LinearOperator(**matvecsA)
+            B = interface.LinearOperator(**matvecsB)
+            # AtimesB = np.array([[22, 28], [49, 64]])
+            AtimesB = self.A.dot(self.B)
+            X = np.array([[1, 2], [3, 4]])
+
+            assert_equal((A @ B).rmatmat(X), np.dot((AtimesB).T, X))
+            assert_equal((2j * A @ B).rmatmat(X),
+                         np.dot((2j * AtimesB).T.conj(), X))
+
+            assert_equal((A@B)@[1,1], [50,113])
+            assert_equal((A@B)@[[1],[1]], [[50],[113]])
+            assert_equal((A@B).matmat([[1],[1]]), [[50],[113]])
+
+            assert_equal((A @ B).rmatvec([1, 1]), [71, 92])
+            assert_equal((A @ B).H.matvec([1, 1]), [71, 92])
+            assert_equal((A @ B).adjoint().matvec([1, 1]), [71, 92])
+
+            assert_(isinstance(A@B, interface._ProductLinearOperator))
+
+            assert_raises(ValueError, lambda: A+B)
+            assert_raises(ValueError, lambda: A**2)
+
+            z = A@B
+            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is B)
+
+        for matvecsC in get_matvecs(self.C):
+            C = interface.LinearOperator(**matvecsC)
+            X = np.array([[1, 2], [3, 4]])
+
+            assert_equal(C.rmatmat(X), np.dot((self.C).T, X))
+            assert_equal((C**2).rmatmat(X),
+                         np.dot((np.dot(self.C, self.C)).T, X))
+
+            assert_equal((C**2)@[1,1], [17,37])
+            assert_equal((C**2).rmatvec([1, 1]), [22, 32])
+            assert_equal((C**2).H.matvec([1, 1]), [22, 32])
+            assert_equal((C**2).adjoint().matvec([1, 1]), [22, 32])
+            assert_equal((C**2).matmat([[1],[1]]), [[17],[37]])
+
+            assert_(isinstance(C**2, interface._PowerLinearOperator))
+
+    def test_matmul(self):
+        D = {'shape': self.A.shape,
+             'matvec': lambda x: np.dot(self.A, x).reshape(self.A.shape[0]),
+             'rmatvec': lambda x: np.dot(self.A.T.conj(),
+                                         x).reshape(self.A.shape[1]),
+             'rmatmat': lambda x: np.dot(self.A.T.conj(), x),
+             'matmat': lambda x: np.dot(self.A, x)}
+        A = interface.LinearOperator(**D)
+        B = np.array([[1 + 1j, 2, 3],
+                      [4, 5, 6],
+                      [7, 8, 9]])
+        b = B[0]
+
+        assert_equal(operator.matmul(A, b), A * b)
+        assert_equal(operator.matmul(A, b.reshape(-1, 1)), A * b.reshape(-1, 1))
+        assert_equal(operator.matmul(A, B), A @ B)
+        assert_equal(operator.matmul(b, A.H), b * A.H)
+        assert_equal(operator.matmul(b, A.adjoint()), b * A.adjoint())
+        assert_equal(operator.matmul(b.reshape(1, -1), A.H), b.reshape(1, -1) * A.H)
+        assert_equal(operator.matmul(b.reshape(1, -1), A.adjoint()),
+                     b.reshape(1, -1) * A.adjoint())
+        assert_equal(operator.matmul(B, A.H), B @ A.H)
+        assert_equal(operator.matmul(B, A.adjoint()), B @ A.adjoint())
+        assert_raises(ValueError, operator.matmul, A, 2)
+        assert_raises(ValueError, operator.matmul, 2, A)
+
+
+class TestAsLinearOperator:
+    def setup_method(self):
+        self.cases = []
+
+        def make_cases(original, dtype):
+            cases = []
+
+            cases.append((matrix(original, dtype=dtype), original))
+            cases.append((np.array(original, dtype=dtype), original))
+            cases.append((sparse.csr_array(original, dtype=dtype), original))
+
+            # Test default implementations of _adjoint and _rmatvec, which
+            # refer to each other.
+            def mv(x, dtype):
+                y = original.dot(x)
+                if len(x.shape) == 2:
+                    y = y.reshape(-1, 1)
+                return y
+
+            def rmv(x, dtype):
+                return original.T.conj().dot(x)
+
+            class BaseMatlike(interface.LinearOperator):
+                args = ()
+
+                def __init__(self, dtype):
+                    self.dtype = np.dtype(dtype)
+                    self.shape = original.shape
+
+                def _matvec(self, x):
+                    return mv(x, self.dtype)
+
+            class HasRmatvec(BaseMatlike):
+                args = ()
+
+                def _rmatvec(self,x):
+                    return rmv(x, self.dtype)
+
+            class HasAdjoint(BaseMatlike):
+                args = ()
+
+                def _adjoint(self):
+                    shape = self.shape[1], self.shape[0]
+                    matvec = partial(rmv, dtype=self.dtype)
+                    rmatvec = partial(mv, dtype=self.dtype)
+                    return interface.LinearOperator(matvec=matvec,
+                                                    rmatvec=rmatvec,
+                                                    dtype=self.dtype,
+                                                    shape=shape)
+
+            class HasRmatmat(HasRmatvec):
+                def _matmat(self, x):
+                    return original.dot(x)
+
+                def _rmatmat(self, x):
+                    return original.T.conj().dot(x)
+
+            cases.append((HasRmatvec(dtype), original))
+            cases.append((HasAdjoint(dtype), original))
+            cases.append((HasRmatmat(dtype), original))
+            return cases
+
+        original = np.array([[1,2,3], [4,5,6]])
+        self.cases += make_cases(original, np.int32)
+        self.cases += make_cases(original, np.float32)
+        self.cases += make_cases(original, np.float64)
+        self.cases += [(interface.aslinearoperator(M).T, A.T)
+                       for M, A in make_cases(original.T, np.float64)]
+        self.cases += [(interface.aslinearoperator(M).H, A.T.conj())
+                       for M, A in make_cases(original.T, np.float64)]
+        self.cases += [(interface.aslinearoperator(M).adjoint(), A.T.conj())
+                       for M, A in make_cases(original.T, np.float64)]
+
+        original = np.array([[1, 2j, 3j], [4j, 5j, 6]])
+        self.cases += make_cases(original, np.complex128)
+        self.cases += [(interface.aslinearoperator(M).T, A.T)
+                       for M, A in make_cases(original.T, np.complex128)]
+        self.cases += [(interface.aslinearoperator(M).H, A.T.conj())
+                       for M, A in make_cases(original.T, np.complex128)]
+        self.cases += [(interface.aslinearoperator(M).adjoint(), A.T.conj())
+                       for M, A in make_cases(original.T, np.complex128)]
+
+    def test_basic(self):
+
+        for M, A_array in self.cases:
+            A = interface.aslinearoperator(M)
+            M,N = A.shape
+
+            xs = [np.array([1, 2, 3]),
+                  np.array([[1], [2], [3]])]
+            ys = [np.array([1, 2]), np.array([[1], [2]])]
+
+            if A.dtype == np.complex128:
+                xs += [np.array([1, 2j, 3j]),
+                       np.array([[1], [2j], [3j]])]
+                ys += [np.array([1, 2j]), np.array([[1], [2j]])]
+
+            x2 = np.array([[1, 4], [2, 5], [3, 6]])
+
+            for x in xs:
+                assert_equal(A.matvec(x), A_array.dot(x))
+                assert_equal(A @ x, A_array.dot(x))
+
+            assert_equal(A.matmat(x2), A_array.dot(x2))
+            assert_equal(A @ x2, A_array.dot(x2))
+
+            for y in ys:
+                assert_equal(A.rmatvec(y), A_array.T.conj().dot(y))
+                assert_equal(A.T.matvec(y), A_array.T.dot(y))
+                assert_equal(A.H.matvec(y), A_array.T.conj().dot(y))
+                assert_equal(A.adjoint().matvec(y), A_array.T.conj().dot(y))
+
+            for y in ys:
+                if y.ndim < 2:
+                    continue
+                assert_equal(A.rmatmat(y), A_array.T.conj().dot(y))
+                assert_equal(A.T.matmat(y), A_array.T.dot(y))
+                assert_equal(A.H.matmat(y), A_array.T.conj().dot(y))
+                assert_equal(A.adjoint().matmat(y), A_array.T.conj().dot(y))
+
+            if hasattr(M,'dtype'):
+                assert_equal(A.dtype, M.dtype)
+
+            assert_(hasattr(A, 'args'))
+
+    def test_dot(self):
+
+        for M, A_array in self.cases:
+            A = interface.aslinearoperator(M)
+            M,N = A.shape
+
+            x0 = np.array([1, 2, 3])
+            x1 = np.array([[1], [2], [3]])
+            x2 = np.array([[1, 4], [2, 5], [3, 6]])
+
+            assert_equal(A.dot(x0), A_array.dot(x0))
+            assert_equal(A.dot(x1), A_array.dot(x1))
+            assert_equal(A.dot(x2), A_array.dot(x2))
+
+
+def test_repr():
+    A = interface.LinearOperator(shape=(1, 1), matvec=lambda x: 1)
+    repr_A = repr(A)
+    assert_('unspecified dtype' not in repr_A, repr_A)
+
+
+def test_identity():
+    ident = interface.IdentityOperator((3, 3))
+    assert_equal(ident @ [1, 2, 3], [1, 2, 3])
+    assert_equal(ident.dot(np.arange(9).reshape(3, 3)).ravel(), np.arange(9))
+
+    assert_raises(ValueError, ident.matvec, [1, 2, 3, 4])
+
+
+def test_attributes():
+    A = interface.aslinearoperator(np.arange(16).reshape(4, 4))
+
+    def always_four_ones(x):
+        x = np.asarray(x)
+        assert_(x.shape == (3,) or x.shape == (3, 1))
+        return np.ones(4)
+
+    B = interface.LinearOperator(shape=(4, 3), matvec=always_four_ones)
+
+    ops = [A, B, A * B, A @ B, A.H, A.adjoint(), A + A, B + B, A**4]
+    for op in ops:
+        assert_(hasattr(op, "dtype"))
+        assert_(hasattr(op, "shape"))
+        assert_(hasattr(op, "_matvec"))
+
+def matvec(x):
+    """ Needed for test_pickle as local functions are not pickleable """
+    return np.zeros(3)
+
+def test_pickle():
+    import pickle
+
+    for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+        A = interface.LinearOperator((3, 3), matvec)
+        s = pickle.dumps(A, protocol=protocol)
+        B = pickle.loads(s)
+
+        for k in A.__dict__:
+            assert_equal(getattr(A, k), getattr(B, k))
+
+
+@pytest.mark.thread_unsafe
+def test_inheritance():
+    class Empty(interface.LinearOperator):
+        pass
+
+    with warns(RuntimeWarning, match="should implement at least"):
+        assert_raises(TypeError, Empty)
+
+    class Identity(interface.LinearOperator):
+        def __init__(self, n):
+            super().__init__(dtype=None, shape=(n, n))
+
+        def _matvec(self, x):
+            return x
+
+    id3 = Identity(3)
+    assert_equal(id3.matvec([1, 2, 3]), [1, 2, 3])
+    assert_raises(NotImplementedError, id3.rmatvec, [4, 5, 6])
+
+    class MatmatOnly(interface.LinearOperator):
+        def __init__(self, A):
+            super().__init__(A.dtype, A.shape)
+            self.A = A
+
+        def _matmat(self, x):
+            return self.A.dot(x)
+
+    mm = MatmatOnly(np.random.randn(5, 3))
+    assert_equal(mm.matvec(np.random.randn(3)).shape, (5,))
+
+def test_dtypes_of_operator_sum():
+    # gh-6078
+
+    mat_complex = np.random.rand(2,2) + 1j * np.random.rand(2,2)
+    mat_real = np.random.rand(2,2)
+
+    complex_operator = interface.aslinearoperator(mat_complex)
+    real_operator = interface.aslinearoperator(mat_real)
+
+    sum_complex = complex_operator + complex_operator
+    sum_real = real_operator + real_operator
+
+    assert_equal(sum_real.dtype, np.float64)
+    assert_equal(sum_complex.dtype, np.complex128)
+
+def test_no_double_init():
+    call_count = [0]
+
+    def matvec(v):
+        call_count[0] += 1
+        return v
+
+    # It should call matvec exactly once (in order to determine the
+    # operator dtype)
+    interface.LinearOperator((2, 2), matvec=matvec)
+    assert_equal(call_count[0], 1)
+
+INT_DTYPES = (np.int8, np.int16, np.int32, np.int64)
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+INEXACTDTYPES = REAL_DTYPES + COMPLEX_DTYPES
+ALLDTYPES = INT_DTYPES + INEXACTDTYPES
+
+
+@pytest.mark.parametrize("test_dtype", ALLDTYPES)
+def test_determine_lo_dtype_from_matvec(test_dtype):
+    # gh-19209
+    scalar = np.array(1, dtype=test_dtype)
+    def mv(v):
+        return np.array([scalar * v[0], v[1]])
+
+    lo = interface.LinearOperator((2, 2), matvec=mv)
+    assert lo.dtype == np.dtype(test_dtype)
+
+def test_determine_lo_dtype_for_int():
+    # gh-19209
+    # test Python int larger than int8 max cast to some int
+    def mv(v):
+        return np.array([128 * v[0], v[1]])
+
+    lo = interface.LinearOperator((2, 2), matvec=mv)
+    assert lo.dtype in INT_DTYPES
+
+def test_adjoint_conjugate():
+    X = np.array([[1j]])
+    A = interface.aslinearoperator(X)
+
+    B = 1j * A
+    Y = 1j * X
+
+    v = np.array([1])
+
+    assert_equal(B.dot(v), Y.dot(v))
+    assert_equal(B.H.dot(v), Y.T.conj().dot(v))
+    assert_equal(B.adjoint().dot(v), Y.T.conj().dot(v))
+
+def test_ndim():
+    X = np.array([[1]])
+    A = interface.aslinearoperator(X)
+    assert_equal(A.ndim, 2)
+
+def test_transpose_noconjugate():
+    X = np.array([[1j]])
+    A = interface.aslinearoperator(X)
+
+    B = 1j * A
+    Y = 1j * X
+
+    v = np.array([1])
+
+    assert_equal(B.dot(v), Y.dot(v))
+    assert_equal(B.T.dot(v), Y.T.dot(v))
+
+def test_transpose_multiplication():
+    class MyMatrix(interface.LinearOperator):
+        def __init__(self, A):
+            super().__init__(A.dtype, A.shape)
+            self.A = A
+        def _matmat(self, other): return self.A @ other
+        def _rmatmat(self, other): return self.A.T @ other
+
+    A = MyMatrix(np.array([[1, 2], [3, 4]]))
+    X = np.array([1, 2])
+    B = np.array([[10, 20], [30, 40]])
+    X2 = X.reshape(-1, 1)
+    Y = np.array([[1, 2], [3, 4]])
+
+    assert_equal(A @ B, Y @ B)
+    assert_equal(B.T @ A, B.T @ Y)
+    assert_equal(A.T @ B, Y.T @ B)
+    assert_equal(A @ X, Y @ X)
+    assert_equal(X.T @ A, X.T @ Y)
+    assert_equal(A.T @ X, Y.T @ X)
+    assert_equal(A @ X2, Y @ X2)
+    assert_equal(X2.T @ A, X2.T @ Y)
+    assert_equal(A.T @ X2, Y.T @ X2)
+
+def test_sparse_matmat_exception():
+    A = interface.LinearOperator((2, 2), matvec=lambda x: x)
+    B = sparse.eye_array(2)
+    msg = "Unable to multiply a LinearOperator with a sparse matrix."
+    with assert_raises(TypeError, match=msg):
+        A @ B
+    with assert_raises(TypeError, match=msg):
+        B @ A
+    with assert_raises(ValueError):
+        A @ np.identity(4)
+    with assert_raises(ValueError):
+        np.identity(4) @ A
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_MatrixLinearOperator_refcycle():
+    # gh-10634
+    # Test that MatrixLinearOperator can be automatically garbage collected
+    A = np.eye(2)
+    with assert_deallocated(interface.MatrixLinearOperator, A) as op:
+        op.adjoint()
+        del op
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_matfuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a468c39cad30f6f852cc6df64b98588fa70b5ff
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_matfuncs.py
@@ -0,0 +1,592 @@
+#
+# Created by: Pearu Peterson, March 2002
+#
+""" Test functions for scipy.linalg._matfuncs module
+
+"""
+import math
+
+import numpy as np
+from numpy import array, eye, exp, random
+from numpy.testing import (
+        assert_allclose, assert_, assert_array_almost_equal, assert_equal,
+        assert_array_almost_equal_nulp, suppress_warnings)
+
+from scipy.sparse import csc_array, SparseEfficiencyWarning
+from scipy.sparse._construct import eye_array
+from scipy.sparse.linalg._matfuncs import (expm, _expm,
+        ProductOperator, MatrixPowerOperator,
+        _onenorm_matrix_power_nnm, matrix_power)
+from scipy.sparse._sputils import matrix
+from scipy.linalg import logm
+from scipy.special import factorial, binom
+import scipy.sparse
+import scipy.sparse.linalg
+
+
+def _burkardt_13_power(n, p):
+    """
+    A helper function for testing matrix functions.
+
+    Parameters
+    ----------
+    n : integer greater than 1
+        Order of the square matrix to be returned.
+    p : non-negative integer
+        Power of the matrix.
+
+    Returns
+    -------
+    out : ndarray representing a square matrix
+        A Forsythe matrix of order n, raised to the power p.
+
+    """
+    # Input validation.
+    if n != int(n) or n < 2:
+        raise ValueError('n must be an integer greater than 1')
+    n = int(n)
+    if p != int(p) or p < 0:
+        raise ValueError('p must be a non-negative integer')
+    p = int(p)
+
+    # Construct the matrix explicitly.
+    a, b = divmod(p, n)
+    large = np.power(10.0, -n*a)
+    small = large * np.power(10.0, -n)
+    return np.diag([large]*(n-b), b) + np.diag([small]*b, b-n)
+
+
+def test_onenorm_matrix_power_nnm():
+    np.random.seed(1234)
+    for n in range(1, 5):
+        for p in range(5):
+            M = np.random.random((n, n))
+            Mp = np.linalg.matrix_power(M, p)
+            observed = _onenorm_matrix_power_nnm(M, p)
+            expected = np.linalg.norm(Mp, 1)
+            assert_allclose(observed, expected)
+
+def test_matrix_power():
+    np.random.seed(1234)
+    row, col = np.random.randint(0, 4, size=(2, 6))
+    data = np.random.random(size=(6,))
+    Amat = csc_array((data, (row, col)), shape=(4, 4))
+    A = csc_array((data, (row, col)), shape=(4, 4))
+    Adense = A.toarray()
+    for power in (2, 5, 6):
+        Apow = matrix_power(A, power).toarray()
+        Amat_pow = matrix_power(Amat, power).toarray()
+        Adense_pow = np.linalg.matrix_power(Adense, power)
+        assert_allclose(Apow, Adense_pow)
+        assert_allclose(Apow, Amat_pow)
+
+
+class TestExpM:
+    def test_zero_ndarray(self):
+        a = array([[0.,0],[0,0]])
+        assert_array_almost_equal(expm(a),[[1,0],[0,1]])
+
+    def test_zero_sparse(self):
+        a = csc_array([[0.,0],[0,0]])
+        assert_array_almost_equal(expm(a).toarray(),[[1,0],[0,1]])
+
+    def test_zero_matrix(self):
+        a = matrix([[0.,0],[0,0]])
+        assert_array_almost_equal(expm(a),[[1,0],[0,1]])
+
+    def test_misc_types(self):
+        A = expm(np.array([[1]]))
+        assert_allclose(expm(((1,),)), A)
+        assert_allclose(expm([[1]]), A)
+        assert_allclose(expm(matrix([[1]])), A)
+        assert_allclose(expm(np.array([[1]])), A)
+        assert_allclose(expm(csc_array([[1]])).toarray(), A)
+        B = expm(np.array([[1j]]))
+        assert_allclose(expm(((1j,),)), B)
+        assert_allclose(expm([[1j]]), B)
+        assert_allclose(expm(matrix([[1j]])), B)
+        assert_allclose(expm(csc_array([[1j]])).toarray(), B)
+
+    def test_bidiagonal_sparse(self):
+        A = csc_array([
+            [1, 3, 0],
+            [0, 1, 5],
+            [0, 0, 2]], dtype=float)
+        e1 = math.exp(1)
+        e2 = math.exp(2)
+        expected = np.array([
+            [e1, 3*e1, 15*(e2 - 2*e1)],
+            [0, e1, 5*(e2 - e1)],
+            [0, 0, e2]], dtype=float)
+        observed = expm(A).toarray()
+        assert_array_almost_equal(observed, expected)
+
+    def test_padecases_dtype_float(self):
+        for dtype in [np.float32, np.float64]:
+            for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
+                A = scale * eye(3, dtype=dtype)
+                observed = expm(A)
+                expected = exp(scale, dtype=dtype) * eye(3, dtype=dtype)
+                assert_array_almost_equal_nulp(observed, expected, nulp=100)
+
+    def test_padecases_dtype_complex(self):
+        for dtype in [np.complex64, np.complex128]:
+            for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
+                A = scale * eye(3, dtype=dtype)
+                observed = expm(A)
+                expected = exp(scale, dtype=dtype) * eye(3, dtype=dtype)
+                assert_array_almost_equal_nulp(observed, expected, nulp=100)
+
+    def test_padecases_dtype_sparse_float(self):
+        # float32 and complex64 lead to errors in spsolve/UMFpack
+        dtype = np.float64
+        for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
+            a = scale * eye_array(3, 3, dtype=dtype, format='csc')
+            e = exp(scale, dtype=dtype) * eye(3, dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                exact_onenorm = _expm(a, use_exact_onenorm=True).toarray()
+                inexact_onenorm = _expm(a, use_exact_onenorm=False).toarray()
+            assert_array_almost_equal_nulp(exact_onenorm, e, nulp=100)
+            assert_array_almost_equal_nulp(inexact_onenorm, e, nulp=100)
+
+    def test_padecases_dtype_sparse_complex(self):
+        # float32 and complex64 lead to errors in spsolve/UMFpack
+        dtype = np.complex128
+        for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
+            a = scale * eye_array(3, 3, dtype=dtype, format='csc')
+            e = exp(scale) * eye(3, dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
+
+    def test_logm_consistency(self):
+        random.seed(1234)
+        for dtype in [np.float64, np.complex128]:
+            for n in range(1, 10):
+                for scale in [1e-4, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2]:
+                    # make logm(A) be of a given scale
+                    A = (eye(n) + random.rand(n, n) * scale).astype(dtype)
+                    if np.iscomplexobj(A):
+                        A = A + 1j * random.rand(n, n) * scale
+                    assert_array_almost_equal(expm(logm(A)), A)
+
+    def test_integer_matrix(self):
+        Q = np.array([
+            [-3, 1, 1, 1],
+            [1, -3, 1, 1],
+            [1, 1, -3, 1],
+            [1, 1, 1, -3]])
+        assert_allclose(expm(Q), expm(1.0 * Q))
+
+    def test_integer_matrix_2(self):
+        # Check for integer overflows
+        Q = np.array([[-500, 500, 0, 0],
+                      [0, -550, 360, 190],
+                      [0, 630, -630, 0],
+                      [0, 0, 0, 0]], dtype=np.int16)
+        assert_allclose(expm(Q), expm(1.0 * Q))
+
+        Q = csc_array(Q)
+        assert_allclose(expm(Q).toarray(), expm(1.0 * Q).toarray())
+
+    def test_triangularity_perturbation(self):
+        # Experiment (1) of
+        # Awad H. Al-Mohy and Nicholas J. Higham (2012)
+        # Improved Inverse Scaling and Squaring Algorithms
+        # for the Matrix Logarithm.
+        A = np.array([
+            [3.2346e-1, 3e4, 3e4, 3e4],
+            [0, 3.0089e-1, 3e4, 3e4],
+            [0, 0, 3.221e-1, 3e4],
+            [0, 0, 0, 3.0744e-1]],
+            dtype=float)
+        A_logm = np.array([
+            [-1.12867982029050462e+00, 9.61418377142025565e+04,
+             -4.52485573953179264e+09, 2.92496941103871812e+14],
+            [0.00000000000000000e+00, -1.20101052953082288e+00,
+             9.63469687211303099e+04, -4.68104828911105442e+09],
+            [0.00000000000000000e+00, 0.00000000000000000e+00,
+             -1.13289322264498393e+00, 9.53249183094775653e+04],
+            [0.00000000000000000e+00, 0.00000000000000000e+00,
+             0.00000000000000000e+00, -1.17947533272554850e+00]],
+            dtype=float)
+        assert_allclose(expm(A_logm), A, rtol=1e-4)
+
+        # Perturb the upper triangular matrix by tiny amounts,
+        # so that it becomes technically not upper triangular.
+        random.seed(1234)
+        tiny = 1e-17
+        A_logm_perturbed = A_logm.copy()
+        A_logm_perturbed[1, 0] = tiny
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "Ill-conditioned.*")
+            A_expm_logm_perturbed = expm(A_logm_perturbed)
+        rtol = 1e-4
+        atol = 100 * tiny
+        assert_(not np.allclose(A_expm_logm_perturbed, A, rtol=rtol, atol=atol))
+
+    def test_burkardt_1(self):
+        # This matrix is diagonal.
+        # The calculation of the matrix exponential is simple.
+        #
+        # This is the first of a series of matrix exponential tests
+        # collected by John Burkardt from the following sources.
+        #
+        # Alan Laub,
+        # Review of "Linear System Theory" by Joao Hespanha,
+        # SIAM Review,
+        # Volume 52, Number 4, December 2010, pages 779--781.
+        #
+        # Cleve Moler and Charles Van Loan,
+        # Nineteen Dubious Ways to Compute the Exponential of a Matrix,
+        # Twenty-Five Years Later,
+        # SIAM Review,
+        # Volume 45, Number 1, March 2003, pages 3--49.
+        #
+        # Cleve Moler,
+        # Cleve's Corner: A Balancing Act for the Matrix Exponential,
+        # 23 July 2012.
+        #
+        # Robert Ward,
+        # Numerical computation of the matrix exponential
+        # with accuracy estimate,
+        # SIAM Journal on Numerical Analysis,
+        # Volume 14, Number 4, September 1977, pages 600--610.
+        exp1 = np.exp(1)
+        exp2 = np.exp(2)
+        A = np.array([
+            [1, 0],
+            [0, 2],
+            ], dtype=float)
+        desired = np.array([
+            [exp1, 0],
+            [0, exp2],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_2(self):
+        # This matrix is symmetric.
+        # The calculation of the matrix exponential is straightforward.
+        A = np.array([
+            [1, 3],
+            [3, 2],
+            ], dtype=float)
+        desired = np.array([
+            [39.322809708033859, 46.166301438885753],
+            [46.166301438885768, 54.711576854329110],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_3(self):
+        # This example is due to Laub.
+        # This matrix is ill-suited for the Taylor series approach.
+        # As powers of A are computed, the entries blow up too quickly.
+        exp1 = np.exp(1)
+        exp39 = np.exp(39)
+        A = np.array([
+            [0, 1],
+            [-39, -40],
+            ], dtype=float)
+        desired = np.array([
+            [
+                39/(38*exp1) - 1/(38*exp39),
+                -np.expm1(-38) / (38*exp1)],
+            [
+                39*np.expm1(-38) / (38*exp1),
+                -1/(38*exp1) + 39/(38*exp39)],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_4(self):
+        # This example is due to Moler and Van Loan.
+        # The example will cause problems for the series summation approach,
+        # as well as for diagonal Pade approximations.
+        A = np.array([
+            [-49, 24],
+            [-64, 31],
+            ], dtype=float)
+        U = np.array([[3, 1], [4, 2]], dtype=float)
+        V = np.array([[1, -1/2], [-2, 3/2]], dtype=float)
+        w = np.array([-17, -1], dtype=float)
+        desired = np.dot(U * np.exp(w), V)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_5(self):
+        # This example is due to Moler and Van Loan.
+        # This matrix is strictly upper triangular
+        # All powers of A are zero beyond some (low) limit.
+        # This example will cause problems for Pade approximations.
+        A = np.array([
+            [0, 6, 0, 0],
+            [0, 0, 6, 0],
+            [0, 0, 0, 6],
+            [0, 0, 0, 0],
+            ], dtype=float)
+        desired = np.array([
+            [1, 6, 18, 36],
+            [0, 1, 6, 18],
+            [0, 0, 1, 6],
+            [0, 0, 0, 1],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_6(self):
+        # This example is due to Moler and Van Loan.
+        # This matrix does not have a complete set of eigenvectors.
+        # That means the eigenvector approach will fail.
+        exp1 = np.exp(1)
+        A = np.array([
+            [1, 1],
+            [0, 1],
+            ], dtype=float)
+        desired = np.array([
+            [exp1, exp1],
+            [0, exp1],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_7(self):
+        # This example is due to Moler and Van Loan.
+        # This matrix is very close to example 5.
+        # Mathematically, it has a complete set of eigenvectors.
+        # Numerically, however, the calculation will be suspect.
+        exp1 = np.exp(1)
+        eps = np.spacing(1)
+        A = np.array([
+            [1 + eps, 1],
+            [0, 1 - eps],
+            ], dtype=float)
+        desired = np.array([
+            [exp1, exp1],
+            [0, exp1],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_8(self):
+        # This matrix was an example in Wikipedia.
+        exp4 = np.exp(4)
+        exp16 = np.exp(16)
+        A = np.array([
+            [21, 17, 6],
+            [-5, -1, -6],
+            [4, 4, 16],
+            ], dtype=float)
+        desired = np.array([
+            [13*exp16 - exp4, 13*exp16 - 5*exp4, 2*exp16 - 2*exp4],
+            [-9*exp16 + exp4, -9*exp16 + 5*exp4, -2*exp16 + 2*exp4],
+            [16*exp16, 16*exp16, 4*exp16],
+            ], dtype=float) * 0.25
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_9(self):
+        # This matrix is due to the NAG Library.
+        # It is an example for function F01ECF.
+        A = np.array([
+            [1, 2, 2, 2],
+            [3, 1, 1, 2],
+            [3, 2, 1, 2],
+            [3, 3, 3, 1],
+            ], dtype=float)
+        desired = np.array([
+            [740.7038, 610.8500, 542.2743, 549.1753],
+            [731.2510, 603.5524, 535.0884, 542.2743],
+            [823.7630, 679.4257, 603.5524, 610.8500],
+            [998.4355, 823.7630, 731.2510, 740.7038],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_10(self):
+        # This is Ward's example #1.
+        # It is defective and nonderogatory.
+        A = np.array([
+            [4, 2, 0],
+            [1, 4, 1],
+            [1, 1, 4],
+            ], dtype=float)
+        assert_allclose(sorted(scipy.linalg.eigvals(A)), (3, 3, 6))
+        desired = np.array([
+            [147.8666224463699, 183.7651386463682, 71.79703239999647],
+            [127.7810855231823, 183.7651386463682, 91.88256932318415],
+            [127.7810855231824, 163.6796017231806, 111.9681062463718],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_11(self):
+        # This is Ward's example #2.
+        # It is a symmetric matrix.
+        A = np.array([
+            [29.87942128909879, 0.7815750847907159, -2.289519314033932],
+            [0.7815750847907159, 25.72656945571064, 8.680737820540137],
+            [-2.289519314033932, 8.680737820540137, 34.39400925519054],
+            ], dtype=float)
+        assert_allclose(scipy.linalg.eigvalsh(A), (20, 30, 40))
+        desired = np.array([
+             [
+                 5.496313853692378E+15,
+                 -1.823188097200898E+16,
+                 -3.047577080858001E+16],
+             [
+                -1.823188097200899E+16,
+                6.060522870222108E+16,
+                1.012918429302482E+17],
+             [
+                -3.047577080858001E+16,
+                1.012918429302482E+17,
+                1.692944112408493E+17],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_12(self):
+        # This is Ward's example #3.
+        # Ward's algorithm has difficulty estimating the accuracy
+        # of its results.
+        A = np.array([
+            [-131, 19, 18],
+            [-390, 56, 54],
+            [-387, 57, 52],
+            ], dtype=float)
+        assert_allclose(sorted(scipy.linalg.eigvals(A)), (-20, -2, -1))
+        desired = np.array([
+            [-1.509644158793135, 0.3678794391096522, 0.1353352811751005],
+            [-5.632570799891469, 1.471517758499875, 0.4060058435250609],
+            [-4.934938326088363, 1.103638317328798, 0.5413411267617766],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_13(self):
+        # This is Ward's example #4.
+        # This is a version of the Forsythe matrix.
+        # The eigenvector problem is badly conditioned.
+        # Ward's algorithm has difficulty estimating the accuracy
+        # of its results for this problem.
+        #
+        # Check the construction of one instance of this family of matrices.
+        A4_actual = _burkardt_13_power(4, 1)
+        A4_desired = [[0, 1, 0, 0],
+                      [0, 0, 1, 0],
+                      [0, 0, 0, 1],
+                      [1e-4, 0, 0, 0]]
+        assert_allclose(A4_actual, A4_desired)
+        # Check the expm for a few instances.
+        for n in (2, 3, 4, 10):
+            # Approximate expm using Taylor series.
+            # This works well for this matrix family
+            # because each matrix in the summation,
+            # even before dividing by the factorial,
+            # is entrywise positive with max entry 10**(-floor(p/n)*n).
+            k = max(1, int(np.ceil(16/n)))
+            desired = np.zeros((n, n), dtype=float)
+            for p in range(n*k):
+                Ap = _burkardt_13_power(n, p)
+                assert_equal(np.min(Ap), 0)
+                assert_allclose(np.max(Ap), np.power(10, -np.floor(p/n)*n))
+                desired += Ap / factorial(p)
+            actual = expm(_burkardt_13_power(n, 1))
+            assert_allclose(actual, desired)
+
+    def test_burkardt_14(self):
+        # This is Moler's example.
+        # This badly scaled matrix caused problems for MATLAB's expm().
+        A = np.array([
+            [0, 1e-8, 0],
+            [-(2e10 + 4e8/6.), -3, 2e10],
+            [200./3., 0, -200./3.],
+            ], dtype=float)
+        desired = np.array([
+            [0.446849468283175, 1.54044157383952e-09, 0.462811453558774],
+            [-5743067.77947947, -0.0152830038686819, -4526542.71278401],
+            [0.447722977849494, 1.54270484519591e-09, 0.463480648837651],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_pascal(self):
+        # Test pascal triangle.
+        # Nilpotent exponential, used to trigger a failure (gh-8029)
+
+        for scale in [1.0, 1e-3, 1e-6]:
+            for n in range(0, 80, 3):
+                sc = scale ** np.arange(n, -1, -1)
+                if np.any(sc < 1e-300):
+                    break
+
+                A = np.diag(np.arange(1, n + 1), -1) * scale
+                B = expm(A)
+
+                got = B
+                expected = binom(np.arange(n + 1)[:,None],
+                                 np.arange(n + 1)[None,:]) * sc[None,:] / sc[:,None]
+                atol = 1e-13 * abs(expected).max()
+                assert_allclose(got, expected, atol=atol)
+
+    def test_matrix_input(self):
+        # Large np.matrix inputs should work, gh-5546
+        A = np.zeros((200, 200))
+        A[-1,0] = 1
+        B0 = expm(A)
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, "the matrix subclass.*")
+            sup.filter(PendingDeprecationWarning, "the matrix subclass.*")
+            B = expm(np.matrix(A))
+        assert_allclose(B, B0)
+
+    def test_exp_sinch_overflow(self):
+        # Check overflow in intermediate steps is fixed (gh-11839)
+        L = np.array([[1.0, -0.5, -0.5, 0.0, 0.0, 0.0, 0.0],
+                      [0.0, 1.0, 0.0, -0.5, -0.5, 0.0, 0.0],
+                      [0.0, 0.0, 1.0, 0.0, 0.0, -0.5, -0.5],
+                      [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]])
+
+        E0 = expm(-L)
+        E1 = expm(-2**11 * L)
+        E2 = E0
+        for j in range(11):
+            E2 = E2 @ E2
+
+        assert_allclose(E1, E2)
+
+
+class TestOperators:
+
+    def test_product_operator(self):
+        random.seed(1234)
+        n = 5
+        k = 2
+        nsamples = 10
+        for i in range(nsamples):
+            A = np.random.randn(n, n)
+            B = np.random.randn(n, n)
+            C = np.random.randn(n, n)
+            D = np.random.randn(n, k)
+            op = ProductOperator(A, B, C)
+            assert_allclose(op.matmat(D), A.dot(B).dot(C).dot(D))
+            assert_allclose(op.T.matmat(D), (A.dot(B).dot(C)).T.dot(D))
+
+    def test_matrix_power_operator(self):
+        random.seed(1234)
+        n = 5
+        k = 2
+        p = 3
+        nsamples = 10
+        for i in range(nsamples):
+            A = np.random.randn(n, n)
+            B = np.random.randn(n, k)
+            op = MatrixPowerOperator(A, p)
+            assert_allclose(op.matmat(B), np.linalg.matrix_power(A, p).dot(B))
+            assert_allclose(op.T.matmat(B), np.linalg.matrix_power(A, p).T.dot(B))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_pydata_sparse.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_pydata_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6b855271063ee769c70095c62dd8a09bd05bd95
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_pydata_sparse.py
@@ -0,0 +1,258 @@
+import pytest
+
+import numpy as np
+import scipy.sparse as sp
+import scipy.sparse.linalg as splin
+
+from numpy.testing import assert_allclose, assert_equal
+
+try:
+    import sparse
+except Exception:
+    sparse = None
+
+pytestmark = pytest.mark.skipif(sparse is None,
+                                reason="pydata/sparse not installed")
+
+
+msg = "pydata/sparse (0.15.1) does not implement necessary operations"
+
+
+sparse_params = (pytest.param("COO"),
+                 pytest.param("DOK", marks=[pytest.mark.xfail(reason=msg)]))
+
+scipy_sparse_classes = [
+    sp.bsr_array,
+    sp.csr_array,
+    sp.coo_array,
+    sp.csc_array,
+    sp.dia_array,
+    sp.dok_array
+]
+
+
+@pytest.fixture(params=sparse_params)
+def sparse_cls(request):
+    return getattr(sparse, request.param)
+
+
+@pytest.fixture(params=scipy_sparse_classes)
+def sp_sparse_cls(request):
+    return request.param
+
+
+@pytest.fixture
+def same_matrix(sparse_cls, sp_sparse_cls):
+    np.random.seed(1234)
+    A_dense = np.random.rand(9, 9)
+    return sp_sparse_cls(A_dense), sparse_cls(A_dense)
+
+
+@pytest.fixture
+def matrices(sparse_cls):
+    np.random.seed(1234)
+    A_dense = np.random.rand(9, 9)
+    A_dense = A_dense @ A_dense.T
+    A_sparse = sparse_cls(A_dense)
+    b = np.random.rand(9)
+    return A_dense, A_sparse, b
+
+
+def test_isolve_gmres(matrices):
+    # Several of the iterative solvers use the same
+    # isolve.utils.make_system wrapper code, so test just one of them.
+    A_dense, A_sparse, b = matrices
+    x, info = splin.gmres(A_sparse, b, atol=1e-15)
+    assert info == 0
+    assert isinstance(x, np.ndarray)
+    assert_allclose(A_sparse @ x, b)
+
+
+def test_lsmr(matrices):
+    A_dense, A_sparse, b = matrices
+    res0 = splin.lsmr(A_dense, b)
+    res = splin.lsmr(A_sparse, b)
+    assert_allclose(res[0], res0[0], atol=1e-3)
+
+
+# test issue 17012
+def test_lsmr_output_shape():
+    x = splin.lsmr(A=np.ones((10, 1)), b=np.zeros(10), x0=np.ones(1))[0]
+    assert_equal(x.shape, (1,))
+
+
+def test_lsqr(matrices):
+    A_dense, A_sparse, b = matrices
+    res0 = splin.lsqr(A_dense, b)
+    res = splin.lsqr(A_sparse, b)
+    assert_allclose(res[0], res0[0], atol=1e-5)
+
+
+def test_eigs(matrices):
+    A_dense, A_sparse, v0 = matrices
+
+    M_dense = np.diag(v0**2)
+    M_sparse = A_sparse.__class__(M_dense)
+
+    w_dense, v_dense = splin.eigs(A_dense, k=3, v0=v0)
+    w, v = splin.eigs(A_sparse, k=3, v0=v0)
+
+    assert_allclose(w, w_dense)
+    assert_allclose(v, v_dense)
+
+    for M in [M_sparse, M_dense]:
+        w_dense, v_dense = splin.eigs(A_dense, M=M_dense, k=3, v0=v0)
+        w, v = splin.eigs(A_sparse, M=M, k=3, v0=v0)
+
+        assert_allclose(w, w_dense)
+        assert_allclose(v, v_dense)
+
+        w_dense, v_dense = splin.eigsh(A_dense, M=M_dense, k=3, v0=v0)
+        w, v = splin.eigsh(A_sparse, M=M, k=3, v0=v0)
+
+        assert_allclose(w, w_dense)
+        assert_allclose(v, v_dense)
+
+
+def test_svds(matrices):
+    A_dense, A_sparse, v0 = matrices
+
+    u0, s0, vt0 = splin.svds(A_dense, k=2, v0=v0)
+    u, s, vt = splin.svds(A_sparse, k=2, v0=v0)
+
+    assert_allclose(s, s0)
+    assert_allclose(np.abs(u), np.abs(u0))
+    assert_allclose(np.abs(vt), np.abs(vt0))
+
+
+def test_lobpcg(matrices):
+    A_dense, A_sparse, x = matrices
+    X = x[:,None]
+
+    w_dense, v_dense = splin.lobpcg(A_dense, X)
+    w, v = splin.lobpcg(A_sparse, X)
+
+    assert_allclose(w, w_dense)
+    assert_allclose(v, v_dense)
+
+
+def test_spsolve(matrices):
+    A_dense, A_sparse, b = matrices
+    b2 = np.random.rand(len(b), 3)
+
+    x0 = splin.spsolve(sp.csc_array(A_dense), b)
+    x = splin.spsolve(A_sparse, b)
+    assert isinstance(x, np.ndarray)
+    assert_allclose(x, x0)
+
+    x0 = splin.spsolve(sp.csc_array(A_dense), b)
+    x = splin.spsolve(A_sparse, b, use_umfpack=True)
+    assert isinstance(x, np.ndarray)
+    assert_allclose(x, x0)
+
+    x0 = splin.spsolve(sp.csc_array(A_dense), b2)
+    x = splin.spsolve(A_sparse, b2)
+    assert isinstance(x, np.ndarray)
+    assert_allclose(x, x0)
+
+    x0 = splin.spsolve(sp.csc_array(A_dense),
+                       sp.csc_array(A_dense))
+    x = splin.spsolve(A_sparse, A_sparse)
+    assert isinstance(x, type(A_sparse))
+    assert_allclose(x.todense(), x0.todense())
+
+
+def test_splu(matrices):
+    A_dense, A_sparse, b = matrices
+    n = len(b)
+    sparse_cls = type(A_sparse)
+
+    lu = splin.splu(A_sparse)
+
+    assert isinstance(lu.L, sparse_cls)
+    assert isinstance(lu.U, sparse_cls)
+
+    _Pr_scipy = sp.csc_array((np.ones(n), (lu.perm_r, np.arange(n))))
+    _Pc_scipy = sp.csc_array((np.ones(n), (np.arange(n), lu.perm_c)))
+    Pr = sparse_cls.from_scipy_sparse(_Pr_scipy)
+    Pc = sparse_cls.from_scipy_sparse(_Pc_scipy)
+    A2 = Pr.T @ lu.L @ lu.U @ Pc.T
+
+    assert_allclose(A2.todense(), A_sparse.todense())
+
+    z = lu.solve(A_sparse.todense())
+    assert_allclose(z, np.eye(n), atol=1e-10)
+
+
+def test_spilu(matrices):
+    A_dense, A_sparse, b = matrices
+    sparse_cls = type(A_sparse)
+
+    lu = splin.spilu(A_sparse)
+
+    assert isinstance(lu.L, sparse_cls)
+    assert isinstance(lu.U, sparse_cls)
+
+    z = lu.solve(A_sparse.todense())
+    assert_allclose(z, np.eye(len(b)), atol=1e-3)
+
+
+def test_spsolve_triangular(matrices):
+    A_dense, A_sparse, b = matrices
+    A_sparse = sparse.tril(A_sparse)
+
+    x = splin.spsolve_triangular(A_sparse, b)
+    assert_allclose(A_sparse @ x, b)
+
+
+def test_onenormest(matrices):
+    A_dense, A_sparse, b = matrices
+    est0 = splin.onenormest(A_dense)
+    est = splin.onenormest(A_sparse)
+    assert_allclose(est, est0)
+
+
+def test_norm(matrices):
+    A_dense, A_sparse, b = matrices
+    norm0 = splin.norm(sp.csr_array(A_dense))
+    norm = splin.norm(A_sparse)
+    assert_allclose(norm, norm0)
+
+
+def test_inv(matrices):
+    A_dense, A_sparse, b = matrices
+    x0 = splin.inv(sp.csc_array(A_dense))
+    x = splin.inv(A_sparse)
+    assert_allclose(x.todense(), x0.todense())
+
+
+def test_expm(matrices):
+    A_dense, A_sparse, b = matrices
+    x0 = splin.expm(sp.csc_array(A_dense))
+    x = splin.expm(A_sparse)
+    assert_allclose(x.todense(), x0.todense())
+
+
+def test_expm_multiply(matrices):
+    A_dense, A_sparse, b = matrices
+    x0 = splin.expm_multiply(A_dense, b)
+    x = splin.expm_multiply(A_sparse, b)
+    assert_allclose(x, x0)
+
+    x0 = splin.expm_multiply(A_dense, A_dense)
+    x = splin.expm_multiply(A_sparse, A_sparse)
+    assert_allclose(x.todense(), x0)
+
+
+def test_eq(same_matrix):
+    sp_sparse, pd_sparse = same_matrix
+    # temporary splint until pydata sparse support sparray equality
+    sp_sparse = sp.coo_matrix(sp_sparse).asformat(sp_sparse.format)
+    assert (sp_sparse == pd_sparse).all()
+
+
+def test_ne(same_matrix):
+    sp_sparse, pd_sparse = same_matrix
+    # temporary splint until pydata sparse support sparray equality
+    sp_sparse = sp.coo_matrix(sp_sparse).asformat(sp_sparse.format)
+    assert not (sp_sparse != pd_sparse).any()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/sparsetools.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/sparsetools.py
new file mode 100644
index 0000000000000000000000000000000000000000..404e431d89d479520d2198ae73b9eab7b23a80f7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/sparsetools.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.sparse` 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="sparse", module="sparsetools",
+                                   private_modules=["_sparsetools"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/spfuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..911969e414d4a1d3888900ad8392b5fc2177c850
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/spfuncs.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.sparse` 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="sparse", module="spfuncs",
+                                   private_modules=["_spfuncs"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/sputils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/sputils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ddd27a43889609b0642bd7579e13c8e3c460a8b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/sputils.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.sparse` 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="sparse", module="sputils",
+                                   private_modules=["_sputils"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d5d2ee2f1bc2c3fef03c71fc0206cd06f3f8618
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py
@@ -0,0 +1,338 @@
+"""Test of 1D arithmetic operations"""
+
+import pytest
+
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+
+from scipy.sparse import coo_array, csr_array
+from scipy.sparse._sputils import isscalarlike
+
+
+spcreators = [coo_array, csr_array]
+math_dtypes = [np.int64, np.float64, np.complex128]
+
+
+def toarray(a):
+    if isinstance(a, np.ndarray) or isscalarlike(a):
+        return a
+    return a.toarray()
+
+@pytest.fixture
+def dat1d():
+    return np.array([3, 0, 1, 0], 'd')
+
+
+@pytest.fixture
+def datsp_math_dtypes(dat1d):
+    dat_dtypes = {dtype: dat1d.astype(dtype) for dtype in math_dtypes}
+    return {
+        sp: [(dtype, dat, sp(dat)) for dtype, dat in dat_dtypes.items()]
+        for sp in spcreators
+    }
+
+
+@pytest.mark.parametrize("spcreator", spcreators)
+class TestArithmetic1D:
+    def test_empty_arithmetic(self, spcreator):
+        shape = (5,)
+        for mytype in [
+            np.dtype('int32'),
+            np.dtype('float32'),
+            np.dtype('float64'),
+            np.dtype('complex64'),
+            np.dtype('complex128'),
+        ]:
+            a = spcreator(shape, dtype=mytype)
+            b = a + a
+            c = 2 * a
+            assert isinstance(a @ a.tocsr(), np.ndarray)
+            assert isinstance(a @ a.tocoo(), np.ndarray)
+            for m in [a, b, c]:
+                assert m @ m == a.toarray() @ a.toarray()
+                assert m.dtype == mytype
+                assert toarray(m).dtype == mytype
+
+    def test_abs(self, spcreator):
+        A = np.array([-1, 0, 17, 0, -5, 0, 1, -4, 0, 0, 0, 0], 'd')
+        assert_equal(abs(A), abs(spcreator(A)).toarray())
+
+    def test_round(self, spcreator):
+        A = np.array([-1.35, 0.56, 17.25, -5.98], 'd')
+        Asp = spcreator(A)
+        assert_equal(np.around(A, decimals=1), round(Asp, ndigits=1).toarray())
+
+    def test_elementwise_power(self, spcreator):
+        A = np.array([-4, -3, -2, -1, 0, 1, 2, 3, 4], 'd')
+        Asp = spcreator(A)
+        assert_equal(np.power(A, 2), Asp.power(2).toarray())
+
+        # element-wise power function needs a scalar power
+        with pytest.raises(NotImplementedError, match='input is not scalar'):
+            spcreator(A).power(A)
+
+    def test_real(self, spcreator):
+        D = np.array([1 + 3j, 2 - 4j])
+        A = spcreator(D)
+        assert_equal(A.real.toarray(), D.real)
+
+    def test_imag(self, spcreator):
+        D = np.array([1 + 3j, 2 - 4j])
+        A = spcreator(D)
+        assert_equal(A.imag.toarray(), D.imag)
+
+    def test_mul_scalar(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            assert_equal(dat * 2, (datsp * 2).toarray())
+            assert_equal(dat * 17.3, (datsp * 17.3).toarray())
+
+    def test_rmul_scalar(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            assert_equal(2 * dat, (2 * datsp).toarray())
+            assert_equal(17.3 * dat, (17.3 * datsp).toarray())
+
+    def test_sub(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            assert_equal((datsp - datsp).toarray(), np.zeros(4))
+            assert_equal((datsp - 0).toarray(), dat)
+
+            A = spcreator([1, -4, 0, 2], dtype='d')
+            assert_equal((datsp - A).toarray(), dat - A.toarray())
+            assert_equal((A - datsp).toarray(), A.toarray() - dat)
+
+            # test broadcasting
+            assert_equal(datsp.toarray() - dat[0], dat - dat[0])
+
+    def test_add0(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            # Adding 0 to a sparse matrix
+            assert_equal((datsp + 0).toarray(), dat)
+            # use sum (which takes 0 as a starting value)
+            sumS = sum([k * datsp for k in range(1, 3)])
+            sumD = sum([k * dat for k in range(1, 3)])
+            assert_allclose(sumS.toarray(), sumD)
+
+    def test_elementwise_multiply(self, spcreator):
+        # real/real
+        A = np.array([4, 0, 9])
+        B = np.array([0, 7, -1])
+        Asp = spcreator(A)
+        Bsp = spcreator(B)
+        assert_allclose(Asp.multiply(Bsp).toarray(), A * B)  # sparse/sparse
+        assert_allclose(Asp.multiply(B).toarray(), A * B)  # sparse/dense
+
+        # complex/complex
+        C = np.array([1 - 2j, 0 + 5j, -1 + 0j])
+        D = np.array([5 + 2j, 7 - 3j, -2 + 1j])
+        Csp = spcreator(C)
+        Dsp = spcreator(D)
+        assert_allclose(Csp.multiply(Dsp).toarray(), C * D)  # sparse/sparse
+        assert_allclose(Csp.multiply(D).toarray(), C * D)  # sparse/dense
+
+        # real/complex
+        assert_allclose(Asp.multiply(Dsp).toarray(), A * D)  # sparse/sparse
+        assert_allclose(Asp.multiply(D).toarray(), A * D)  # sparse/dense
+
+    def test_elementwise_multiply_broadcast(self, spcreator):
+        A = np.array([4])
+        B = np.array([[-9]])
+        C = np.array([1, -1, 0])
+        D = np.array([[7, 9, -9]])
+        E = np.array([[3], [2], [1]])
+        F = np.array([[8, 6, 3], [-4, 3, 2], [6, 6, 6]])
+        G = [1, 2, 3]
+        H = np.ones((3, 4))
+        J = H.T
+        K = np.array([[0]])
+        L = np.array([[[1, 2], [0, 1]]])
+
+        # Some arrays can't be cast as spmatrices (A, C, L) so leave
+        # them out.
+        Asp = spcreator(A)
+        Csp = spcreator(C)
+        Gsp = spcreator(G)
+        # 2d arrays
+        Bsp = spcreator(B)
+        Dsp = spcreator(D)
+        Esp = spcreator(E)
+        Fsp = spcreator(F)
+        Hsp = spcreator(H)
+        Hspp = spcreator(H[0, None])
+        Jsp = spcreator(J)
+        Jspp = spcreator(J[:, 0, None])
+        Ksp = spcreator(K)
+
+        matrices = [A, B, C, D, E, F, G, H, J, K, L]
+        spmatrices = [Asp, Bsp, Csp, Dsp, Esp, Fsp, Gsp, Hsp, Hspp, Jsp, Jspp, Ksp]
+        sp1dmatrices = [Asp, Csp, Gsp]
+
+        # sparse/sparse
+        for i in sp1dmatrices:
+            for j in spmatrices:
+                try:
+                    dense_mult = i.toarray() * j.toarray()
+                except ValueError:
+                    with pytest.raises(ValueError, match='inconsistent shapes'):
+                        i.multiply(j)
+                    continue
+                sp_mult = i.multiply(j)
+                assert_allclose(sp_mult.toarray(), dense_mult)
+
+        # sparse/dense
+        for i in sp1dmatrices:
+            for j in matrices:
+                try:
+                    dense_mult = i.toarray() * j
+                except TypeError:
+                    continue
+                except ValueError:
+                    matchme = 'broadcast together|inconsistent shapes'
+                    with pytest.raises(ValueError, match=matchme):
+                        i.multiply(j)
+                    continue
+                sp_mult = i.multiply(j)
+                assert_allclose(toarray(sp_mult), dense_mult)
+
+    def test_elementwise_divide(self, spcreator, dat1d):
+        datsp = spcreator(dat1d)
+        expected = np.array([1, np.nan, 1, np.nan])
+        actual = datsp / datsp
+        # need assert_array_equal to handle nan values
+        np.testing.assert_array_equal(actual, expected)
+
+        denom = spcreator([1, 0, 0, 4], dtype='d')
+        expected = [3, np.nan, np.inf, 0]
+        np.testing.assert_array_equal(datsp / denom, expected)
+
+        # complex
+        A = np.array([1 - 2j, 0 + 5j, -1 + 0j])
+        B = np.array([5 + 2j, 7 - 3j, -2 + 1j])
+        Asp = spcreator(A)
+        Bsp = spcreator(B)
+        assert_allclose(Asp / Bsp, A / B)
+
+        # integer
+        A = np.array([1, 2, 3])
+        B = np.array([0, 1, 2])
+        Asp = spcreator(A)
+        Bsp = spcreator(B)
+        with np.errstate(divide='ignore'):
+            assert_equal(Asp / Bsp, A / B)
+
+        # mismatching sparsity patterns
+        A = np.array([0, 1])
+        B = np.array([1, 0])
+        Asp = spcreator(A)
+        Bsp = spcreator(B)
+        with np.errstate(divide='ignore', invalid='ignore'):
+            assert_equal(Asp / Bsp, A / B)
+
+    def test_pow(self, spcreator):
+        A = np.array([1, 0, 2, 0])
+        B = spcreator(A)
+
+        # unusual exponents
+        with pytest.raises(ValueError, match='negative integer powers'):
+            B**-1
+        with pytest.raises(NotImplementedError, match='zero power'):
+            B**0
+
+        for exponent in [1, 2, 3, 2.2]:
+            ret_sp = B**exponent
+            ret_np = A**exponent
+            assert_equal(ret_sp.toarray(), ret_np)
+            assert_equal(ret_sp.dtype, ret_np.dtype)
+
+    def test_dot_scalar(self, spcreator, dat1d):
+        A = spcreator(dat1d)
+        scalar = 10
+        actual = A.dot(scalar)
+        expected = A * scalar
+
+        assert_allclose(actual.toarray(), expected.toarray())
+
+    def test_matmul(self, spcreator):
+        Msp = spcreator([2, 0, 3.0])
+        B = spcreator(np.array([[0, 1], [1, 0], [0, 2]], 'd'))
+        col = np.array([[1, 2, 3]]).T
+
+        # check sparse @ dense 2d column
+        assert_allclose(Msp @ col, Msp.toarray() @ col)
+
+        # check sparse1d @ sparse2d, sparse1d @ dense2d, dense1d @ sparse2d
+        assert_allclose((Msp @ B).toarray(), (Msp @ B).toarray())
+        assert_allclose(Msp.toarray() @ B, (Msp @ B).toarray())
+        assert_allclose(Msp @ B.toarray(), (Msp @ B).toarray())
+
+        # check sparse1d @ dense1d, sparse1d @ sparse1d
+        V = np.array([0, 0, 1])
+        assert_allclose(Msp @ V, Msp.toarray() @ V)
+
+        Vsp = spcreator(V)
+        Msp_Vsp = Msp @ Vsp
+        assert isinstance(Msp_Vsp, np.ndarray)
+        assert Msp_Vsp.shape == ()
+
+        # output is 0-dim ndarray
+        assert_allclose(np.array(3), Msp_Vsp)
+        assert_allclose(np.array(3), Msp.toarray() @ Vsp)
+        assert_allclose(np.array(3), Msp @ Vsp.toarray())
+        assert_allclose(np.array(3), Msp.toarray() @ Vsp.toarray())
+
+        # check error on matrix-scalar
+        with pytest.raises(ValueError, match='Scalar operands are not allowed'):
+            Msp @ 1
+        with pytest.raises(ValueError, match='Scalar operands are not allowed'):
+            1 @ Msp
+
+    def test_sub_dense(self, spcreator, datsp_math_dtypes):
+        # subtracting a dense matrix to/from a sparse matrix
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            # Manually add to avoid upcasting from scalar
+            # multiplication.
+            sum1 = (dat + dat + dat) - datsp
+            assert_equal(sum1, dat + dat)
+            sum2 = (datsp + datsp + datsp) - dat
+            assert_equal(sum2, dat + dat)
+
+    def test_size_zero_matrix_arithmetic(self, spcreator):
+        # Test basic matrix arithmetic with shapes like 0, (1, 0), (0, 3), etc.
+        mat = np.array([])
+        a = mat.reshape(0)
+        d = mat.reshape((1, 0))
+        f = np.ones([5, 5])
+
+        asp = spcreator(a)
+        dsp = spcreator(d)
+        # bad shape for addition
+        with pytest.raises(ValueError, match='inconsistent shapes'):
+            asp.__add__(dsp)
+
+        # matrix product.
+        assert_equal(asp.dot(asp), np.dot(a, a))
+
+        # bad matrix products
+        with pytest.raises(ValueError, match='dimension mismatch'):
+            asp.dot(f)
+
+        # elemente-wise multiplication
+        assert_equal(asp.multiply(asp).toarray(), np.multiply(a, a))
+
+        assert_equal(asp.multiply(a).toarray(), np.multiply(a, a))
+
+        assert_equal(asp.multiply(6).toarray(), np.multiply(a, 6))
+
+        # bad element-wise multiplication
+        with pytest.raises(ValueError, match='inconsistent shapes'):
+            asp.multiply(f)
+
+        # Addition
+        assert_equal(asp.__add__(asp).toarray(), a.__add__(a))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..96ca22939df371c0d11b06fb06f2920c705f4578
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py
@@ -0,0 +1,561 @@
+import pytest
+import numpy as np
+import numpy.testing as npt
+import scipy.sparse
+import scipy.sparse.linalg as spla
+
+
+sparray_types = ('bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil')
+
+sparray_classes = [
+    getattr(scipy.sparse, f'{T}_array') for T in sparray_types
+]
+
+A = np.array([
+    [0, 1, 2, 0],
+    [2, 0, 0, 3],
+    [1, 4, 0, 0]
+])
+
+B = np.array([
+    [0, 1],
+    [2, 0]
+])
+
+X = np.array([
+    [1, 0, 0, 1],
+    [2, 1, 2, 0],
+    [0, 2, 1, 0],
+    [0, 0, 1, 2]
+], dtype=float)
+
+
+sparrays = [sparray(A) for sparray in sparray_classes]
+square_sparrays = [sparray(B) for sparray in sparray_classes]
+eig_sparrays = [sparray(X) for sparray in sparray_classes]
+
+parametrize_sparrays = pytest.mark.parametrize(
+    "A", sparrays, ids=sparray_types
+)
+parametrize_square_sparrays = pytest.mark.parametrize(
+    "B", square_sparrays, ids=sparray_types
+)
+parametrize_eig_sparrays = pytest.mark.parametrize(
+    "X", eig_sparrays, ids=sparray_types
+)
+
+
+@parametrize_sparrays
+def test_sum(A):
+    assert not isinstance(A.sum(axis=0), np.matrix), \
+        "Expected array, got matrix"
+    assert A.sum(axis=0).shape == (4,)
+    assert A.sum(axis=1).shape == (3,)
+
+
+@parametrize_sparrays
+def test_mean(A):
+    assert not isinstance(A.mean(axis=1), np.matrix), \
+        "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_min_max(A):
+    # Some formats don't support min/max operations, so we skip those here.
+    if hasattr(A, 'min'):
+        assert not isinstance(A.min(axis=1), np.matrix), \
+            "Expected array, got matrix"
+    if hasattr(A, 'max'):
+        assert not isinstance(A.max(axis=1), np.matrix), \
+            "Expected array, got matrix"
+    if hasattr(A, 'argmin'):
+        assert not isinstance(A.argmin(axis=1), np.matrix), \
+            "Expected array, got matrix"
+    if hasattr(A, 'argmax'):
+        assert not isinstance(A.argmax(axis=1), np.matrix), \
+            "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_todense(A):
+    assert not isinstance(A.todense(), np.matrix), \
+        "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_indexing(A):
+    if A.__class__.__name__[:3] in ('dia', 'coo', 'bsr'):
+        return
+
+    all_res = (
+        A[1, :],
+        A[:, 1],
+        A[1, [1, 2]],
+        A[[1, 2], 1],
+        A[[0]],
+        A[:, [1, 2]],
+        A[[1, 2], :],
+        A[1, [[1, 2]]],
+        A[[[1, 2]], 1],
+    )
+
+    for res in all_res:
+        assert isinstance(res, scipy.sparse.sparray), \
+            f"Expected sparse array, got {res._class__.__name__}"
+
+
+@parametrize_sparrays
+def test_dense_addition(A):
+    X = np.random.random(A.shape)
+    assert not isinstance(A + X, np.matrix), "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_sparse_addition(A):
+    assert isinstance((A + A), scipy.sparse.sparray), "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_elementwise_mul(A):
+    assert np.all((A * A).todense() == A.power(2).todense())
+
+
+@parametrize_sparrays
+def test_elementwise_rmul(A):
+    with pytest.raises(TypeError):
+        None * A
+
+    with pytest.raises(ValueError):
+        np.eye(3) * scipy.sparse.csr_array(np.arange(6).reshape(2, 3))
+
+    assert np.all((2 * A) == (A.todense() * 2))
+
+    assert np.all((A.todense() * A) == (A.todense() ** 2))
+
+
+@parametrize_sparrays
+def test_matmul(A):
+    assert np.all((A @ A.T).todense() == A.dot(A.T).todense())
+
+
+@parametrize_sparrays
+def test_power_operator(A):
+    assert isinstance((A**2), scipy.sparse.sparray), "Expected array, got matrix"
+
+    # https://github.com/scipy/scipy/issues/15948
+    npt.assert_equal((A**2).todense(), (A.todense())**2)
+
+    # power of zero is all ones (dense) so helpful msg exception
+    with pytest.raises(NotImplementedError, match="zero power"):
+        A**0
+
+
+@parametrize_sparrays
+def test_sparse_divide(A):
+    assert isinstance(A / A, np.ndarray)
+
+@parametrize_sparrays
+@pytest.mark.thread_unsafe
+def test_sparse_dense_divide(A):
+    with pytest.warns(RuntimeWarning):
+        assert isinstance((A / A.todense()), scipy.sparse.sparray)
+
+@parametrize_sparrays
+def test_dense_divide(A):
+    assert isinstance((A / 2), scipy.sparse.sparray), "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_no_A_attr(A):
+    with pytest.raises(AttributeError):
+        A.A
+
+
+@parametrize_sparrays
+def test_no_H_attr(A):
+    with pytest.raises(AttributeError):
+        A.H
+
+
+@parametrize_sparrays
+def test_getrow_getcol(A):
+    assert isinstance(A._getcol(0), scipy.sparse.sparray)
+    assert isinstance(A._getrow(0), scipy.sparse.sparray)
+
+
+# -- linalg --
+
+@parametrize_sparrays
+def test_as_linearoperator(A):
+    L = spla.aslinearoperator(A)
+    npt.assert_allclose(L * [1, 2, 3, 4], A @ [1, 2, 3, 4])
+
+
+@parametrize_square_sparrays
+def test_inv(B):
+    if B.__class__.__name__[:3] != 'csc':
+        return
+
+    C = spla.inv(B)
+
+    assert isinstance(C, scipy.sparse.sparray)
+    npt.assert_allclose(C.todense(), np.linalg.inv(B.todense()))
+
+
+@parametrize_square_sparrays
+def test_expm(B):
+    if B.__class__.__name__[:3] != 'csc':
+        return
+
+    Bmat = scipy.sparse.csc_matrix(B)
+
+    C = spla.expm(B)
+
+    assert isinstance(C, scipy.sparse.sparray)
+    npt.assert_allclose(
+        C.todense(),
+        spla.expm(Bmat).todense()
+    )
+
+
+@parametrize_square_sparrays
+def test_expm_multiply(B):
+    if B.__class__.__name__[:3] != 'csc':
+        return
+
+    npt.assert_allclose(
+        spla.expm_multiply(B, np.array([1, 2])),
+        spla.expm(B) @ [1, 2]
+    )
+
+
+@parametrize_sparrays
+def test_norm(A):
+    C = spla.norm(A)
+    npt.assert_allclose(C, np.linalg.norm(A.todense()))
+
+
+@parametrize_square_sparrays
+def test_onenormest(B):
+    C = spla.onenormest(B)
+    npt.assert_allclose(C, np.linalg.norm(B.todense(), 1))
+
+
+@parametrize_square_sparrays
+def test_spsolve(B):
+    if B.__class__.__name__[:3] not in ('csc', 'csr'):
+        return
+
+    npt.assert_allclose(
+        spla.spsolve(B, [1, 2]),
+        np.linalg.solve(B.todense(), [1, 2])
+    )
+
+
+@pytest.mark.parametrize("fmt",["csr","csc"])
+def test_spsolve_triangular(fmt):
+    arr = [
+        [1, 0, 0, 0],
+        [2, 1, 0, 0],
+        [3, 2, 1, 0],
+        [4, 3, 2, 1],
+    ]
+    if fmt == "csr":
+      X = scipy.sparse.csr_array(arr)
+    else:
+      X = scipy.sparse.csc_array(arr)
+    spla.spsolve_triangular(X, [1, 2, 3, 4])
+
+
+@parametrize_square_sparrays
+def test_factorized(B):
+    if B.__class__.__name__[:3] != 'csc':
+        return
+
+    LU = spla.factorized(B)
+    npt.assert_allclose(
+        LU(np.array([1, 2])),
+        np.linalg.solve(B.todense(), [1, 2])
+    )
+
+
+@parametrize_square_sparrays
+@pytest.mark.parametrize(
+    "solver",
+    ["bicg", "bicgstab", "cg", "cgs", "gmres", "lgmres", "minres", "qmr",
+     "gcrotmk", "tfqmr"]
+)
+def test_solvers(B, solver):
+    if solver == "minres":
+        kwargs = {}
+    else:
+        kwargs = {'atol': 1e-5}
+
+    x, info = getattr(spla, solver)(B, np.array([1, 2]), **kwargs)
+    assert info >= 0  # no errors, even if perhaps did not converge fully
+    npt.assert_allclose(x, [1, 1], atol=1e-1)
+
+
+@parametrize_sparrays
+@pytest.mark.parametrize(
+    "solver",
+    ["lsqr", "lsmr"]
+)
+def test_lstsqr(A, solver):
+    x, *_ = getattr(spla, solver)(A, [1, 2, 3])
+    npt.assert_allclose(A @ x, [1, 2, 3])
+
+
+@parametrize_eig_sparrays
+def test_eigs(X):
+    e, v = spla.eigs(X, k=1)
+    npt.assert_allclose(
+        X @ v,
+        e[0] * v
+    )
+
+
+@parametrize_eig_sparrays
+def test_eigsh(X):
+    X = X + X.T
+    e, v = spla.eigsh(X, k=1)
+    npt.assert_allclose(
+        X @ v,
+        e[0] * v
+    )
+
+
+@parametrize_eig_sparrays
+def test_svds(X):
+    u, s, vh = spla.svds(X, k=3)
+    u2, s2, vh2 = np.linalg.svd(X.todense())
+    s = np.sort(s)
+    s2 = np.sort(s2[:3])
+    npt.assert_allclose(s, s2, atol=1e-3)
+
+
+def test_splu():
+    X = scipy.sparse.csc_array([
+        [1, 0, 0, 0],
+        [2, 1, 0, 0],
+        [3, 2, 1, 0],
+        [4, 3, 2, 1],
+    ])
+    LU = spla.splu(X)
+    npt.assert_allclose(
+        LU.solve(np.array([1, 2, 3, 4])),
+        np.asarray([1, 0, 0, 0], dtype=np.float64),
+        rtol=1e-14, atol=3e-16
+    )
+
+
+def test_spilu():
+    X = scipy.sparse.csc_array([
+        [1, 0, 0, 0],
+        [2, 1, 0, 0],
+        [3, 2, 1, 0],
+        [4, 3, 2, 1],
+    ])
+    LU = spla.spilu(X)
+    npt.assert_allclose(
+        LU.solve(np.array([1, 2, 3, 4])),
+        np.asarray([1, 0, 0, 0], dtype=np.float64),
+        rtol=1e-14, atol=3e-16
+    )
+
+
+@pytest.mark.parametrize(
+    "cls,indices_attrs",
+    [
+        (
+            scipy.sparse.csr_array,
+            ["indices", "indptr"],
+        ),
+        (
+            scipy.sparse.csc_array,
+            ["indices", "indptr"],
+        ),
+        (
+            scipy.sparse.coo_array,
+            ["row", "col"],
+        ),
+    ]
+)
+@pytest.mark.parametrize("expected_dtype", [np.int64, np.int32])
+def test_index_dtype_compressed(cls, indices_attrs, expected_dtype):
+    input_array = scipy.sparse.coo_array(np.arange(9).reshape(3, 3))
+    coo_tuple = (
+        input_array.data,
+        (
+            input_array.row.astype(expected_dtype),
+            input_array.col.astype(expected_dtype),
+        )
+    )
+
+    result = cls(coo_tuple)
+    for attr in indices_attrs:
+        assert getattr(result, attr).dtype == expected_dtype
+
+    result = cls(coo_tuple, shape=(3, 3))
+    for attr in indices_attrs:
+        assert getattr(result, attr).dtype == expected_dtype
+
+    if issubclass(cls, scipy.sparse._compressed._cs_matrix):
+        input_array_csr = input_array.tocsr()
+        csr_tuple = (
+            input_array_csr.data,
+            input_array_csr.indices.astype(expected_dtype),
+            input_array_csr.indptr.astype(expected_dtype),
+        )
+
+        result = cls(csr_tuple)
+        for attr in indices_attrs:
+            assert getattr(result, attr).dtype == expected_dtype
+
+        result = cls(csr_tuple, shape=(3, 3))
+        for attr in indices_attrs:
+            assert getattr(result, attr).dtype == expected_dtype
+
+
+def test_default_is_matrix_diags():
+    m = scipy.sparse.diags([0, 1, 2])
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_eye():
+    m = scipy.sparse.eye(3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_spdiags():
+    m = scipy.sparse.spdiags([1, 2, 3], 0, 3, 3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_identity():
+    m = scipy.sparse.identity(3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_kron_dense():
+    m = scipy.sparse.kron(
+        np.array([[1, 2], [3, 4]]), np.array([[4, 3], [2, 1]])
+    )
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_kron_sparse():
+    m = scipy.sparse.kron(
+        np.array([[1, 2], [3, 4]]), np.array([[1, 0], [0, 0]])
+    )
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_kronsum():
+    m = scipy.sparse.kronsum(
+        np.array([[1, 0], [0, 1]]), np.array([[0, 1], [1, 0]])
+    )
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_random():
+    m = scipy.sparse.random(3, 3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_rand():
+    m = scipy.sparse.rand(3, 3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+@pytest.mark.parametrize("fn", (scipy.sparse.hstack, scipy.sparse.vstack))
+def test_default_is_matrix_stacks(fn):
+    """Same idea as `test_default_construction_fn_matrices`, but for the
+    stacking creation functions."""
+    A = scipy.sparse.coo_matrix(np.eye(2))
+    B = scipy.sparse.coo_matrix([[0, 1], [1, 0]])
+    m = fn([A, B])
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_blocks_default_construction_fn_matrices():
+    """Same idea as `test_default_construction_fn_matrices`, but for the block
+    creation function"""
+    A = scipy.sparse.coo_matrix(np.eye(2))
+    B = scipy.sparse.coo_matrix([[2], [0]])
+    C = scipy.sparse.coo_matrix([[3]])
+
+    # block diag
+    m = scipy.sparse.block_diag((A, B, C))
+    assert not isinstance(m, scipy.sparse.sparray)
+
+    # bmat
+    m = scipy.sparse.bmat([[A, None], [None, C]])
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_format_property():
+    for fmt in sparray_types:
+        arr_cls = getattr(scipy.sparse, f"{fmt}_array")
+        M = arr_cls([[1, 2]])
+        assert M.format == fmt
+        assert M._format == fmt
+        with pytest.raises(AttributeError):
+            M.format = "qqq"
+
+
+def test_issparse():
+    m = scipy.sparse.eye(3)
+    a = scipy.sparse.csr_array(m)
+    assert not isinstance(m, scipy.sparse.sparray)
+    assert isinstance(a, scipy.sparse.sparray)
+
+    # Both sparse arrays and sparse matrices should be sparse
+    assert scipy.sparse.issparse(a)
+    assert scipy.sparse.issparse(m)
+
+    # ndarray and array_likes are not sparse
+    assert not scipy.sparse.issparse(a.todense())
+    assert not scipy.sparse.issparse(m.todense())
+
+
+def test_isspmatrix():
+    m = scipy.sparse.eye(3)
+    a = scipy.sparse.csr_array(m)
+    assert not isinstance(m, scipy.sparse.sparray)
+    assert isinstance(a, scipy.sparse.sparray)
+
+    # Should only be true for sparse matrices, not sparse arrays
+    assert not scipy.sparse.isspmatrix(a)
+    assert scipy.sparse.isspmatrix(m)
+
+    # ndarray and array_likes are not sparse
+    assert not scipy.sparse.isspmatrix(a.todense())
+    assert not scipy.sparse.isspmatrix(m.todense())
+
+
+@pytest.mark.parametrize(
+    ("fmt", "fn"),
+    (
+        ("bsr", scipy.sparse.isspmatrix_bsr),
+        ("coo", scipy.sparse.isspmatrix_coo),
+        ("csc", scipy.sparse.isspmatrix_csc),
+        ("csr", scipy.sparse.isspmatrix_csr),
+        ("dia", scipy.sparse.isspmatrix_dia),
+        ("dok", scipy.sparse.isspmatrix_dok),
+        ("lil", scipy.sparse.isspmatrix_lil),
+    ),
+)
+def test_isspmatrix_format(fmt, fn):
+    m = scipy.sparse.eye(3, format=fmt)
+    a = scipy.sparse.csr_array(m).asformat(fmt)
+    assert not isinstance(m, scipy.sparse.sparray)
+    assert isinstance(a, scipy.sparse.sparray)
+
+    # Should only be true for sparse matrices, not sparse arrays
+    assert not fn(a)
+    assert fn(m)
+
+    # ndarray and array_likes are not sparse
+    assert not fn(a.todense())
+    assert not fn(m.todense())
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f7ead8b134dc2e09bb0cef8441cb2b75a5aee8b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py
@@ -0,0 +1,5695 @@
+#
+# Authors: Travis Oliphant, Ed Schofield, Robert Cimrman, Nathan Bell, and others
+
+""" Test functions for sparse matrices. Each class in the "Matrix class
+based tests" section become subclasses of the classes in the "Generic
+tests" section. This is done by the functions in the "Tailored base
+class for generic tests" section.
+
+"""
+
+
+import contextlib
+import functools
+import operator
+import platform
+import itertools
+import sys
+
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from numpy import (arange, zeros, array, dot, asarray,
+                   vstack, ndarray, transpose, diag, kron, inf, conjugate,
+                   int8)
+
+import random
+from numpy.testing import (assert_equal, assert_array_equal,
+        assert_array_almost_equal, assert_almost_equal, assert_,
+        assert_allclose, suppress_warnings)
+
+import scipy.linalg
+
+import scipy.sparse as sparse
+from scipy.sparse import (csc_matrix, csr_matrix, dok_matrix,
+        coo_matrix, lil_matrix, dia_matrix, bsr_matrix,
+        csc_array, csr_array, dok_array,
+        coo_array, lil_array, dia_array, bsr_array,
+        eye, issparse, SparseEfficiencyWarning, sparray)
+from scipy.sparse._base import _formats
+from scipy.sparse._sputils import (supported_dtypes, isscalarlike,
+                                   get_index_dtype, asmatrix, matrix)
+from scipy.sparse.linalg import splu, expm, inv
+
+from scipy._lib.decorator import decorator
+from scipy._lib._util import ComplexWarning
+
+IS_COLAB = ('google.colab' in sys.modules)
+
+
+def assert_in(member, collection, msg=None):
+    message = msg if msg is not None else f"{member!r} not found in {collection!r}"
+    assert_(member in collection, msg=message)
+
+
+def assert_array_equal_dtype(x, y, **kwargs):
+    assert_(x.dtype == y.dtype)
+    assert_array_equal(x, y, **kwargs)
+
+
+NON_ARRAY_BACKED_FORMATS = frozenset(['dok'])
+
+def sparse_may_share_memory(A, B):
+    # Checks if A and B have any numpy array sharing memory.
+
+    def _underlying_arrays(x):
+        # Given any object (e.g. a sparse array), returns all numpy arrays
+        # stored in any attribute.
+
+        arrays = []
+        for a in x.__dict__.values():
+            if isinstance(a, np.ndarray | np.generic):
+                arrays.append(a)
+        return arrays
+
+    for a in _underlying_arrays(A):
+        for b in _underlying_arrays(B):
+            if np.may_share_memory(a, b):
+                return True
+    return False
+
+
+sup_complex = suppress_warnings()
+sup_complex.filter(ComplexWarning)
+
+
+def with_64bit_maxval_limit(maxval_limit=None, random=False, fixed_dtype=None,
+                            downcast_maxval=None, assert_32bit=False):
+    """
+    Monkeypatch the maxval threshold at which scipy.sparse switches to
+    64-bit index arrays, or make it (pseudo-)random.
+
+    """
+    if maxval_limit is None:
+        maxval_limit = np.int64(10)
+    else:
+        # Ensure we use numpy scalars rather than Python scalars (matters for
+        # NEP 50 casting rule changes)
+        maxval_limit = np.int64(maxval_limit)
+
+    if assert_32bit:
+        def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
+            tp = get_index_dtype(arrays, maxval, check_contents)
+            assert_equal(np.iinfo(tp).max, np.iinfo(np.int32).max)
+            assert_(tp == np.int32 or tp == np.intc)
+            return tp
+    elif fixed_dtype is not None:
+        def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
+            return fixed_dtype
+    elif random:
+        counter = np.random.RandomState(seed=1234)
+
+        def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
+            return (np.int32, np.int64)[counter.randint(2)]
+    else:
+        def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
+            dtype = np.int32
+            if maxval is not None:
+                if maxval > maxval_limit:
+                    dtype = np.int64
+            for arr in arrays:
+                arr = np.asarray(arr)
+                if arr.dtype > np.int32:
+                    if check_contents:
+                        if arr.size == 0:
+                            # a bigger type not needed
+                            continue
+                        elif np.issubdtype(arr.dtype, np.integer):
+                            maxval = arr.max()
+                            minval = arr.min()
+                            if minval >= -maxval_limit and maxval <= maxval_limit:
+                                # a bigger type not needed
+                                continue
+                    dtype = np.int64
+            return dtype
+
+    if downcast_maxval is not None:
+        def new_downcast_intp_index(arr):
+            if arr.max() > downcast_maxval:
+                raise AssertionError("downcast limited")
+            return arr.astype(np.intp)
+
+    @decorator
+    def deco(func, *a, **kw):
+        backup = []
+        modules = [scipy.sparse._bsr, scipy.sparse._coo, scipy.sparse._csc,
+                   scipy.sparse._csr, scipy.sparse._dia, scipy.sparse._dok,
+                   scipy.sparse._lil, scipy.sparse._sputils,
+                   scipy.sparse._compressed, scipy.sparse._construct]
+        try:
+            for mod in modules:
+                backup.append((mod, 'get_index_dtype',
+                               getattr(mod, 'get_index_dtype', None)))
+                setattr(mod, 'get_index_dtype', new_get_index_dtype)
+                if downcast_maxval is not None:
+                    backup.append((mod, 'downcast_intp_index',
+                                   getattr(mod, 'downcast_intp_index', None)))
+                    setattr(mod, 'downcast_intp_index', new_downcast_intp_index)
+            return func(*a, **kw)
+        finally:
+            for mod, name, oldfunc in backup:
+                if oldfunc is not None:
+                    setattr(mod, name, oldfunc)
+
+    return deco
+
+
+def toarray(a):
+    if isinstance(a, np.ndarray) or isscalarlike(a):
+        return a
+    return a.toarray()
+
+
+class BinopTester:
+    # Custom type to test binary operations on sparse matrices.
+
+    def __add__(self, mat):
+        return "matrix on the right"
+
+    def __mul__(self, mat):
+        return "matrix on the right"
+
+    def __sub__(self, mat):
+        return "matrix on the right"
+
+    def __radd__(self, mat):
+        return "matrix on the left"
+
+    def __rmul__(self, mat):
+        return "matrix on the left"
+
+    def __rsub__(self, mat):
+        return "matrix on the left"
+
+    def __matmul__(self, mat):
+        return "matrix on the right"
+
+    def __rmatmul__(self, mat):
+        return "matrix on the left"
+
+class BinopTester_with_shape:
+    # Custom type to test binary operations on sparse matrices
+    # with object which has shape attribute.
+    def __init__(self,shape):
+        self._shape = shape
+
+    def shape(self):
+        return self._shape
+
+    def ndim(self):
+        return len(self._shape)
+
+    def __add__(self, mat):
+        return "matrix on the right"
+
+    def __mul__(self, mat):
+        return "matrix on the right"
+
+    def __sub__(self, mat):
+        return "matrix on the right"
+
+    def __radd__(self, mat):
+        return "matrix on the left"
+
+    def __rmul__(self, mat):
+        return "matrix on the left"
+
+    def __rsub__(self, mat):
+        return "matrix on the left"
+
+    def __matmul__(self, mat):
+        return "matrix on the right"
+
+    def __rmatmul__(self, mat):
+        return "matrix on the left"
+
+class ComparisonTester:
+    # Custom type to test comparison operations on sparse matrices.
+    def __eq__(self, other):
+        return "eq"
+
+    def __ne__(self, other):
+        return "ne"
+
+    def __lt__(self, other):
+        return "lt"
+
+    def __le__(self, other):
+        return "le"
+
+    def __gt__(self, other):
+        return "gt"
+
+    def __ge__(self, other):
+        return "ge"
+
+
+#------------------------------------------------------------------------------
+# Generic tests
+#------------------------------------------------------------------------------
+
+
+class _MatrixMixin:
+    """mixin to easily allow tests of both sparray and spmatrix"""
+    bsr_container = bsr_matrix
+    coo_container = coo_matrix
+    csc_container = csc_matrix
+    csr_container = csr_matrix
+    dia_container = dia_matrix
+    dok_container = dok_matrix
+    lil_container = lil_matrix
+    asdense = staticmethod(asmatrix)
+
+    def test_getrow(self):
+        assert_array_equal(self.datsp.getrow(1).toarray(), self.dat[[1], :])
+        assert_array_equal(self.datsp.getrow(-1).toarray(), self.dat[[-1], :])
+
+    def test_getcol(self):
+        assert_array_equal(self.datsp.getcol(1).toarray(), self.dat[:, [1]])
+        assert_array_equal(self.datsp.getcol(-1).toarray(), self.dat[:, [-1]])
+
+    def test_asfptype(self):
+        A = self.spcreator(arange(6,dtype='int32').reshape(2,3))
+
+        assert_equal(A.asfptype().dtype, np.dtype('float64'))
+        assert_equal(A.asfptype().format, A.format)
+        assert_equal(A.astype('int16').asfptype().dtype, np.dtype('float32'))
+        assert_equal(A.astype('complex128').asfptype().dtype, np.dtype('complex128'))
+
+        B = A.asfptype()
+        C = B.asfptype()
+        assert_(B is C)
+
+
+# TODO test prune
+# TODO test has_sorted_indices
+class _TestCommon:
+    """test common functionality shared by all sparse formats"""
+    math_dtypes = supported_dtypes
+
+    bsr_container = bsr_array
+    coo_container = coo_array
+    csc_container = csc_array
+    csr_container = csr_array
+    dia_container = dia_array
+    dok_container = dok_array
+    lil_container = lil_array
+    asdense = array
+
+    @classmethod
+    def init_class(cls):
+        # Canonical data.
+        cls.dat = array([[1, 0, 0, 2], [3, 0, 1, 0], [0, 2, 0, 0]], 'd')
+        cls.datsp = cls.spcreator(cls.dat)
+
+        # Some sparse and dense matrices with data for every supported dtype.
+        # This set union is a workaround for numpy#6295, which means that
+        # two np.int64 dtypes don't hash to the same value.
+        cls.checked_dtypes = set(supported_dtypes).union(cls.math_dtypes)
+        cls.dat_dtypes = {}
+        cls.datsp_dtypes = {}
+        for dtype in cls.checked_dtypes:
+            cls.dat_dtypes[dtype] = cls.dat.astype(dtype)
+            cls.datsp_dtypes[dtype] = cls.spcreator(cls.dat.astype(dtype))
+
+        # Check that the original data is equivalent to the
+        # corresponding dat_dtypes & datsp_dtypes.
+        assert_equal(cls.dat, cls.dat_dtypes[np.float64])
+        assert_equal(cls.datsp.toarray(),
+                     cls.datsp_dtypes[np.float64].toarray())
+
+        cls.is_array_test = isinstance(cls.datsp, sparray)
+
+    def test_bool(self):
+        def check(dtype):
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_raises(ValueError, bool, datsp)
+            assert_(self.spcreator([[1]]))
+            assert_(not self.spcreator([[0]]))
+
+        if isinstance(self, TestDOK):
+            pytest.skip("Cannot create a rank <= 2 DOK matrix.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_bool_rollover(self):
+        # bool's underlying dtype is 1 byte, check that it does not
+        # rollover True -> False at 256.
+        dat = array([[True, False]])
+        datsp = self.spcreator(dat)
+
+        for _ in range(10):
+            datsp = datsp + datsp
+            dat = dat + dat
+        assert_array_equal(dat, datsp.toarray())
+
+    def test_eq(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datbsr = self.bsr_container(dat)
+            datcsr = self.csr_container(dat)
+            datcsc = self.csc_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat == dat2, (datsp == datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype(dat == dat2, (datbsr == datsp2).toarray())
+            assert_array_equal_dtype(dat == dat2, (datcsr == datsp2).toarray())
+            assert_array_equal_dtype(dat == dat2, (datcsc == datsp2).toarray())
+            assert_array_equal_dtype(dat == dat2, (datlil == datsp2).toarray())
+            # sparse/dense
+            assert_array_equal_dtype(dat == datsp2, datsp2 == dat)
+            # sparse/scalar
+            assert_array_equal_dtype(dat == 0, (datsp == 0).toarray())
+            assert_array_equal_dtype(dat == 1, (datsp == 1).toarray())
+            assert_array_equal_dtype(dat == np.nan,
+                                     (datsp == np.nan).toarray())
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_ne(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat != dat2, (datsp != datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype(dat != dat2, (datbsr != datsp2).toarray())
+            assert_array_equal_dtype(dat != dat2, (datcsc != datsp2).toarray())
+            assert_array_equal_dtype(dat != dat2, (datcsr != datsp2).toarray())
+            assert_array_equal_dtype(dat != dat2, (datlil != datsp2).toarray())
+            # sparse/dense
+            assert_array_equal_dtype(dat != datsp2, datsp2 != dat)
+            # sparse/scalar
+            assert_array_equal_dtype(dat != 0, (datsp != 0).toarray())
+            assert_array_equal_dtype(dat != 1, (datsp != 1).toarray())
+            assert_array_equal_dtype(0 != dat, (0 != datsp).toarray())
+            assert_array_equal_dtype(1 != dat, (1 != datsp).toarray())
+            assert_array_equal_dtype(dat != np.nan,
+                                     (datsp != np.nan).toarray())
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_lt(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            # data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datcomplex = dat.astype(complex)
+            datcomplex[:,0] = 1 + 1j
+            datspcomplex = self.spcreator(datcomplex)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat < dat2, (datsp < datsp2).toarray())
+            assert_array_equal_dtype(datcomplex < dat2,
+                                     (datspcomplex < datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype(dat < dat2, (datbsr < datsp2).toarray())
+            assert_array_equal_dtype(dat < dat2, (datcsc < datsp2).toarray())
+            assert_array_equal_dtype(dat < dat2, (datcsr < datsp2).toarray())
+            assert_array_equal_dtype(dat < dat2, (datlil < datsp2).toarray())
+
+            assert_array_equal_dtype(dat2 < dat, (datsp2 < datbsr).toarray())
+            assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsc).toarray())
+            assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsr).toarray())
+            assert_array_equal_dtype(dat2 < dat, (datsp2 < datlil).toarray())
+            # sparse/dense
+            assert_array_equal_dtype(dat < dat2, datsp < dat2)
+            assert_array_equal_dtype(datcomplex < dat2, datspcomplex < dat2)
+            # sparse/scalar
+            for val in [2, 1, 0, -1, -2]:
+                val = np.int64(val)  # avoid Python scalar (due to NEP 50 changes)
+                assert_array_equal_dtype((datsp < val).toarray(), dat < val)
+                assert_array_equal_dtype((val < datsp).toarray(), val < dat)
+
+            with np.errstate(invalid='ignore'):
+                assert_array_equal_dtype((datsp < np.nan).toarray(),
+                                         dat < np.nan)
+
+            # data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+
+            # dense rhs
+            assert_array_equal_dtype(dat < datsp2, datsp < dat2)
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_gt(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datcomplex = dat.astype(complex)
+            datcomplex[:,0] = 1 + 1j
+            datspcomplex = self.spcreator(datcomplex)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat > dat2, (datsp > datsp2).toarray())
+            assert_array_equal_dtype(datcomplex > dat2,
+                                     (datspcomplex > datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype(dat > dat2, (datbsr > datsp2).toarray())
+            assert_array_equal_dtype(dat > dat2, (datcsc > datsp2).toarray())
+            assert_array_equal_dtype(dat > dat2, (datcsr > datsp2).toarray())
+            assert_array_equal_dtype(dat > dat2, (datlil > datsp2).toarray())
+
+            assert_array_equal_dtype(dat2 > dat, (datsp2 > datbsr).toarray())
+            assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsc).toarray())
+            assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsr).toarray())
+            assert_array_equal_dtype(dat2 > dat, (datsp2 > datlil).toarray())
+            # sparse/dense
+            assert_array_equal_dtype(dat > dat2, datsp > dat2)
+            assert_array_equal_dtype(datcomplex > dat2, datspcomplex > dat2)
+            # sparse/scalar
+            for val in [2, 1, 0, -1, -2]:
+                val = np.int64(val)  # avoid Python scalar (due to NEP 50 changes)
+                assert_array_equal_dtype((datsp > val).toarray(), dat > val)
+                assert_array_equal_dtype((val > datsp).toarray(), val > dat)
+
+            with np.errstate(invalid='ignore'):
+                assert_array_equal_dtype((datsp > np.nan).toarray(),
+                                         dat > np.nan)
+
+            # data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+
+            # dense rhs
+            assert_array_equal_dtype(dat > datsp2, datsp > dat2)
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_le(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datcomplex = dat.astype(complex)
+            datcomplex[:,0] = 1 + 1j
+            datspcomplex = self.spcreator(datcomplex)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat <= dat2, (datsp <= datsp2).toarray())
+            assert_array_equal_dtype(datcomplex <= dat2,
+                                     (datspcomplex <= datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype((datbsr <= datsp2).toarray(), dat <= dat2)
+            assert_array_equal_dtype((datcsc <= datsp2).toarray(), dat <= dat2)
+            assert_array_equal_dtype((datcsr <= datsp2).toarray(), dat <= dat2)
+            assert_array_equal_dtype((datlil <= datsp2).toarray(), dat <= dat2)
+
+            assert_array_equal_dtype((datsp2 <= datbsr).toarray(), dat2 <= dat)
+            assert_array_equal_dtype((datsp2 <= datcsc).toarray(), dat2 <= dat)
+            assert_array_equal_dtype((datsp2 <= datcsr).toarray(), dat2 <= dat)
+            assert_array_equal_dtype((datsp2 <= datlil).toarray(), dat2 <= dat)
+            # sparse/dense
+            assert_array_equal_dtype(datsp <= dat2, dat <= dat2)
+            assert_array_equal_dtype(datspcomplex <= dat2, datcomplex <= dat2)
+            # sparse/scalar
+            for val in [2, 1, -1, -2]:
+                val = np.int64(val)  # avoid Python scalar (due to NEP 50 changes)
+                assert_array_equal_dtype((datsp <= val).toarray(), dat <= val)
+                assert_array_equal_dtype((val <= datsp).toarray(), val <= dat)
+
+            # data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+
+            # dense rhs
+            assert_array_equal_dtype(dat <= datsp2, datsp <= dat2)
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_ge(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datcomplex = dat.astype(complex)
+            datcomplex[:,0] = 1 + 1j
+            datspcomplex = self.spcreator(datcomplex)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat >= dat2, (datsp >= datsp2).toarray())
+            assert_array_equal_dtype(datcomplex >= dat2,
+                                     (datspcomplex >= datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype((datbsr >= datsp2).toarray(), dat >= dat2)
+            assert_array_equal_dtype((datcsc >= datsp2).toarray(), dat >= dat2)
+            assert_array_equal_dtype((datcsr >= datsp2).toarray(), dat >= dat2)
+            assert_array_equal_dtype((datlil >= datsp2).toarray(), dat >= dat2)
+
+            assert_array_equal_dtype((datsp2 >= datbsr).toarray(), dat2 >= dat)
+            assert_array_equal_dtype((datsp2 >= datcsc).toarray(), dat2 >= dat)
+            assert_array_equal_dtype((datsp2 >= datcsr).toarray(), dat2 >= dat)
+            assert_array_equal_dtype((datsp2 >= datlil).toarray(), dat2 >= dat)
+            # sparse/dense
+            assert_array_equal_dtype(datsp >= dat2, dat >= dat2)
+            assert_array_equal_dtype(datspcomplex >= dat2, datcomplex >= dat2)
+            # sparse/scalar
+            for val in [2, 1, -1, -2]:
+                val = np.int64(val)  # avoid Python scalar (due to NEP 50 changes)
+                assert_array_equal_dtype((datsp >= val).toarray(), dat >= val)
+                assert_array_equal_dtype((val >= datsp).toarray(), val >= dat)
+
+            # dense data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+
+            # dense rhs
+            assert_array_equal_dtype(dat >= datsp2, datsp >= dat2)
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_empty(self):
+        # create empty matrices
+        assert_equal(self.spcreator((3, 3)).toarray(), zeros((3, 3)))
+        assert_equal(self.spcreator((3, 3)).nnz, 0)
+        assert_equal(self.spcreator((3, 3)).count_nonzero(), 0)
+        if self.datsp.format in ["coo", "csr", "csc", "lil"]:
+            assert_equal(self.spcreator((3, 3)).count_nonzero(axis=0), array([0, 0, 0]))
+
+    def test_count_nonzero(self):
+        axis_support = self.datsp.format in ["coo", "csr", "csc", "lil"]
+        axes = [None, 0, 1, -1, -2] if axis_support else [None]
+
+        for A in (self.datsp, self.datsp.T):
+            for ax in axes:
+                expected = np.count_nonzero(A.toarray(), axis=ax)
+                assert_equal(A.count_nonzero(axis=ax), expected)
+
+        if not axis_support:
+            with assert_raises(NotImplementedError, match="not implemented .* format"):
+                self.datsp.count_nonzero(axis=0)
+
+    def test_invalid_shapes(self):
+        assert_raises(ValueError, self.spcreator, (-1,3))
+        assert_raises(ValueError, self.spcreator, (3,-1))
+        assert_raises(ValueError, self.spcreator, (-1,-1))
+
+    def test_repr(self):
+        datsp = self.spcreator([[1, 0, 0], [0, 0, 0], [0, 0, -2]])
+        extra = (
+            "(1 diagonals) " if datsp.format == "dia"
+            else "(blocksize=1x1) " if datsp.format == "bsr"
+            else ""
+        )
+        _, fmt = _formats[datsp.format]
+        sparse_cls = "array" if self.is_array_test else "matrix"
+        expected = (
+            f"<{fmt} sparse {sparse_cls} of dtype '{datsp.dtype}'\n"
+            f"\twith {datsp.nnz} stored elements {extra}and shape {datsp.shape}>"
+        )
+        assert repr(datsp) == expected
+
+    def test_str_maxprint(self):
+        datsp = self.spcreator(np.arange(75).reshape(5, 15))
+        assert datsp.maxprint == 50
+        assert len(str(datsp).split('\n')) == 51 + 3
+
+        dat = np.arange(15).reshape(5,3)
+        datsp = self.spcreator(dat)
+        # format dia reports nnz=15, but we want 14
+        nnz_small = 14 if datsp.format == 'dia' else datsp.nnz
+        datsp_mp6 = self.spcreator(dat, maxprint=6)
+
+        assert len(str(datsp).split('\n')) == nnz_small + 3
+        assert len(str(datsp_mp6).split('\n')) == 6 + 4
+
+        # Check parameter `maxprint` is keyword only
+        datsp = self.spcreator(dat, shape=(5, 3), dtype='i', copy=False, maxprint=4)
+        datsp = self.spcreator(dat, (5, 3), 'i', False, maxprint=4)
+        with pytest.raises(TypeError, match="positional argument|unpack non-iterable"):
+            self.spcreator(dat, (5, 3), 'i', False, 4)
+
+    def test_str(self):
+        datsp = self.spcreator([[1, 0, 0], [0, 0, 0], [0, 0, -2]])
+        if datsp.nnz != 2:
+            return
+        extra = (
+            "(1 diagonals) " if datsp.format == "dia"
+            else "(blocksize=1x1) " if datsp.format == "bsr"
+            else ""
+        )
+        _, fmt = _formats[datsp.format]
+        sparse_cls = "array" if self.is_array_test else "matrix"
+        expected = (
+            f"<{fmt} sparse {sparse_cls} of dtype '{datsp.dtype}'\n"
+            f"\twith {datsp.nnz} stored elements {extra}and shape {datsp.shape}>"
+            "\n  Coords\tValues"
+            "\n  (0, 0)\t1"
+            "\n  (2, 2)\t-2"
+        )
+        assert str(datsp) == expected
+
+    def test_empty_arithmetic(self):
+        # Test manipulating empty matrices. Fails in SciPy SVN <= r1768
+        shape = (5, 5)
+        for mytype in [np.dtype('int32'), np.dtype('float32'),
+                np.dtype('float64'), np.dtype('complex64'),
+                np.dtype('complex128')]:
+            a = self.spcreator(shape, dtype=mytype)
+            b = a + a
+            c = 2 * a
+            d = a @ a.tocsc()
+            e = a @ a.tocsr()
+            f = a @ a.tocoo()
+            for m in [a,b,c,d,e,f]:
+                assert_equal(m.toarray(), a.toarray()@a.toarray())
+                # These fail in all revisions <= r1768:
+                assert_equal(m.dtype,mytype)
+                assert_equal(m.toarray().dtype,mytype)
+
+    def test_abs(self):
+        A = array([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd')
+        assert_equal(abs(A), abs(self.spcreator(A)).toarray())
+
+    def test_round(self):
+        decimal = 1
+        A = array([[-1.35, 0.56], [17.25, -5.98]], 'd')
+        assert_equal(np.around(A, decimals=decimal),
+                     round(self.spcreator(A), ndigits=decimal).toarray())
+
+    def test_elementwise_power(self):
+        A = array([[-4, -3, -2], [-1, 0, 1], [2, 3, 4]], 'd')
+        assert_equal(np.power(A, 2), self.spcreator(A).power(2).toarray())
+
+        #it's element-wise power function, input has to be a scalar
+        assert_raises(NotImplementedError, self.spcreator(A).power, A)
+
+    def test_neg(self):
+        A = array([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd')
+        assert_equal(-A, (-self.spcreator(A)).toarray())
+
+        # see gh-5843
+        A = array([[True, False, False], [False, False, True]])
+        assert_raises(NotImplementedError, self.spcreator(A).__neg__)
+
+    def test_real(self):
+        D = array([[1 + 3j, 2 - 4j]])
+        A = self.spcreator(D)
+        assert_equal(A.real.toarray(), D.real)
+
+    def test_imag(self):
+        D = array([[1 + 3j, 2 - 4j]])
+        A = self.spcreator(D)
+        assert_equal(A.imag.toarray(), D.imag)
+
+    def test_diagonal(self):
+        # Does the matrix's .diagonal() method work?
+        mats = []
+        mats.append([[1,0,2]])
+        mats.append([[1],[0],[2]])
+        mats.append([[0,1],[0,2],[0,3]])
+        mats.append([[0,0,1],[0,0,2],[0,3,0]])
+        mats.append([[1,0],[0,0]])
+
+        mats.append(kron(mats[0],[[1,2]]))
+        mats.append(kron(mats[0],[[1],[2]]))
+        mats.append(kron(mats[1],[[1,2],[3,4]]))
+        mats.append(kron(mats[2],[[1,2],[3,4]]))
+        mats.append(kron(mats[3],[[1,2],[3,4]]))
+        mats.append(kron(mats[3],[[1,2,3,4]]))
+
+        for m in mats:
+            rows, cols = array(m).shape
+            sparse_mat = self.spcreator(m)
+            for k in range(-rows-1, cols+2):
+                assert_equal(sparse_mat.diagonal(k=k), diag(m, k=k))
+            # Test for k beyond boundaries(issue #11949)
+            assert_equal(sparse_mat.diagonal(k=10), diag(m, k=10))
+            assert_equal(sparse_mat.diagonal(k=-99), diag(m, k=-99))
+
+        # Test all-zero matrix.
+        assert_equal(self.spcreator((40, 16130)).diagonal(), np.zeros(40))
+        # Test empty matrix
+        # https://github.com/scipy/scipy/issues/11949
+        assert_equal(self.spcreator((0, 0)).diagonal(), np.empty(0))
+        assert_equal(self.spcreator((15, 0)).diagonal(), np.empty(0))
+        assert_equal(self.spcreator((0, 5)).diagonal(10), np.empty(0))
+
+    def test_trace(self):
+        # For square matrix
+        A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+        B = self.spcreator(A)
+        for k in range(-2, 3):
+            assert_equal(A.trace(offset=k), B.trace(offset=k))
+
+        # For rectangular matrix
+        A = np.array([[1, 2, 3], [4, 5, 6]])
+        B = self.spcreator(A)
+        for k in range(-1, 3):
+            assert_equal(A.trace(offset=k), B.trace(offset=k))
+
+    def test_reshape(self):
+        x = self.spcreator([[1, 0, 7], [0, 0, 0], [0, 3, 0], [0, 0, 5]])
+        for order in ['C', 'F']:
+            for s in [(12, 1), (1, 12)]:
+                assert_array_equal(x.reshape(s, order=order).toarray(),
+                                   x.toarray().reshape(s, order=order))
+
+        # This example is taken from the stackoverflow answer at
+        # https://stackoverflow.com/q/16511879
+        x = self.spcreator([[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]])
+        y = x.reshape((2, 6))  # Default order is 'C'
+        desired = [[0, 10, 0, 0, 0, 0], [0, 0, 0, 20, 30, 40]]
+        assert_array_equal(y.toarray(), desired)
+
+        # Reshape with negative indexes
+        y = x.reshape((2, -1))
+        assert_array_equal(y.toarray(), desired)
+        y = x.reshape((-1, 6))
+        assert_array_equal(y.toarray(), desired)
+        assert_raises(ValueError, x.reshape, (-1, -1))
+
+        # Reshape with star args
+        y = x.reshape(2, 6)
+        assert_array_equal(y.toarray(), desired)
+        assert_raises(TypeError, x.reshape, 2, 6, not_an_arg=1)
+
+        # Reshape with same size is noop unless copy=True
+        y = x.reshape((3, 4))
+        assert_(y is x)
+        y = x.reshape((3, 4), copy=True)
+        assert_(y is not x)
+
+        # Ensure reshape did not alter original size
+        assert_array_equal(x.shape, (3, 4))
+
+        if self.is_array_test:
+            with assert_raises(AttributeError, match="has no setter|n't set attribute"):
+                x.shape = (2, 6)
+        else:  # spmatrix test
+            # Reshape in place
+            x.shape = (2, 6)
+            assert_array_equal(x.toarray(), desired)
+
+        # Reshape to bad ndim
+        assert_raises(ValueError, x.reshape, (x.size,))
+        assert_raises(ValueError, x.reshape, (1, x.size, 1))
+
+    @pytest.mark.slow
+    def test_setdiag_comprehensive(self):
+        def dense_setdiag(a, v, k):
+            v = np.asarray(v)
+            if k >= 0:
+                n = min(a.shape[0], a.shape[1] - k)
+                if v.ndim != 0:
+                    n = min(n, len(v))
+                    v = v[:n]
+                i = np.arange(0, n)
+                j = np.arange(k, k + n)
+                a[i,j] = v
+            elif k < 0:
+                dense_setdiag(a.T, v, -k)
+
+        def check_setdiag(a, b, k):
+            # Check setting diagonal using a scalar, a vector of
+            # correct length, and too short or too long vectors
+            for r in [-1, len(np.diag(a, k)), 2, 30]:
+                if r < 0:
+                    v = np.random.choice(range(1, 20))
+                else:
+                    v = np.random.randint(1, 20, size=r)
+
+                dense_setdiag(a, v, k)
+                with suppress_warnings() as sup:
+                    sup.filter(SparseEfficiencyWarning, "Changing the sparsity structu")
+                    b.setdiag(v, k)
+
+                # check that dense_setdiag worked
+                d = np.diag(a, k)
+                if np.asarray(v).ndim == 0:
+                    assert_array_equal(d, v, err_msg="{msg} {r}")
+                else:
+                    n = min(len(d), len(v))
+                    assert_array_equal(d[:n], v[:n], err_msg="{msg} {r}")
+                # check that sparse setdiag worked
+                assert_array_equal(b.toarray(), a, err_msg="{msg} {r}")
+
+        # comprehensive test
+        np.random.seed(1234)
+        shapes = [(0,5), (5,0), (1,5), (5,1), (5,5)]
+        for dtype in [np.int8, np.float64]:
+            for m,n in shapes:
+                ks = np.arange(-m+1, n-1)
+                for k in ks:
+                    a = np.zeros((m, n), dtype=dtype)
+                    b = self.spcreator((m, n), dtype=dtype)
+
+                    check_setdiag(a, b, k)
+
+                    # check overwriting etc
+                    for k2 in np.random.choice(ks, size=min(len(ks), 5)):
+                        check_setdiag(a, b, k2)
+
+    def test_setdiag(self):
+        # simple test cases
+        m = self.spcreator(np.eye(3))
+        m2 = self.spcreator((4, 4))
+        values = [3, 2, 1]
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            assert_raises(ValueError, m.setdiag, values, k=4)
+            m.setdiag(values)
+            assert_array_equal(m.diagonal(), values)
+            m.setdiag(values, k=1)
+            assert_array_equal(m.toarray(), np.array([[3, 3, 0],
+                                                      [0, 2, 2],
+                                                      [0, 0, 1]]))
+            m.setdiag(values, k=-2)
+            assert_array_equal(m.toarray(), np.array([[3, 3, 0],
+                                                      [0, 2, 2],
+                                                      [3, 0, 1]]))
+            m.setdiag((9,), k=2)
+            assert_array_equal(m.toarray()[0,2], 9)
+            m.setdiag((9,), k=-2)
+            assert_array_equal(m.toarray()[2,0], 9)
+            # test short values on an empty matrix
+            m2.setdiag([1], k=2)
+            assert_array_equal(m2.toarray()[0], [0, 0, 1, 0])
+            # test overwriting that same diagonal
+            m2.setdiag([1, 1], k=2)
+            assert_array_equal(m2.toarray()[:2], [[0, 0, 1, 0],
+                                                  [0, 0, 0, 1]])
+
+    def test_nonzero(self):
+        A = array([[1, 0, 1],[0, 1, 1],[0, 0, 1]])
+        Asp = self.spcreator(A)
+
+        A_nz = {tuple(ij) for ij in transpose(A.nonzero())}
+        Asp_nz = {tuple(ij) for ij in transpose(Asp.nonzero())}
+
+        assert_equal(A_nz, Asp_nz)
+
+    def test_numpy_nonzero(self):
+        # See gh-5987
+        A = array([[1, 0, 1], [0, 1, 1], [0, 0, 1]])
+        Asp = self.spcreator(A)
+
+        A_nz = {tuple(ij) for ij in transpose(np.nonzero(A))}
+        Asp_nz = {tuple(ij) for ij in transpose(np.nonzero(Asp))}
+
+        assert_equal(A_nz, Asp_nz)
+
+    def test_sum(self):
+        np.random.seed(1234)
+        dat_1 = np.array([[0, 1, 2],
+                        [3, -4, 5],
+                        [-6, 7, 9]])
+        dat_2 = np.random.rand(5, 5)
+        dat_3 = np.array([[]])
+        dat_4 = np.zeros((40, 40))
+        dat_5 = sparse.rand(5, 5, density=1e-2).toarray()
+        matrices = [dat_1, dat_2, dat_3, dat_4, dat_5]
+
+        def check(dtype, j):
+            dat = self.asdense(matrices[j], dtype=dtype)
+            datsp = self.spcreator(dat, dtype=dtype)
+            with np.errstate(over='ignore'):
+                assert_array_almost_equal(dat.sum(), datsp.sum())
+                assert_equal(dat.sum().dtype, datsp.sum().dtype)
+                assert_(np.isscalar(datsp.sum(axis=None)))
+                assert_array_almost_equal(dat.sum(axis=None),
+                                          datsp.sum(axis=None))
+                assert_equal(dat.sum(axis=None).dtype,
+                             datsp.sum(axis=None).dtype)
+                assert_array_almost_equal(dat.sum(axis=0), datsp.sum(axis=0))
+                assert_equal(dat.sum(axis=0).dtype, datsp.sum(axis=0).dtype)
+                assert_array_almost_equal(dat.sum(axis=1), datsp.sum(axis=1))
+                assert_equal(dat.sum(axis=1).dtype, datsp.sum(axis=1).dtype)
+                assert_array_almost_equal(dat.sum(axis=-2), datsp.sum(axis=-2))
+                assert_equal(dat.sum(axis=-2).dtype, datsp.sum(axis=-2).dtype)
+                assert_array_almost_equal(dat.sum(axis=-1), datsp.sum(axis=-1))
+                assert_equal(dat.sum(axis=-1).dtype, datsp.sum(axis=-1).dtype)
+
+        for dtype in self.checked_dtypes:
+            for j in range(len(matrices)):
+                check(dtype, j)
+
+    def test_sum_invalid_params(self):
+        out = np.zeros((1, 3))
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        assert_raises(ValueError, datsp.sum, axis=3)
+        assert_raises(TypeError, datsp.sum, axis=(0, 1))
+        assert_raises(TypeError, datsp.sum, axis=1.5)
+        assert_raises(ValueError, datsp.sum, axis=1, out=out)
+
+    def test_sum_dtype(self):
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        def check(dtype):
+            dat_sum = dat.sum(dtype=dtype)
+            datsp_sum = datsp.sum(dtype=dtype)
+
+            assert_array_almost_equal(dat_sum, datsp_sum)
+            assert_equal(dat_sum.dtype, datsp_sum.dtype)
+
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_sum_out(self):
+        keep = not self.is_array_test
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        dat_out = array(0) if self.is_array_test else array([[0]])
+        datsp_out = array(0) if self.is_array_test else matrix([[0]])
+
+        dat.sum(out=dat_out, keepdims=keep)
+        datsp.sum(out=datsp_out)
+        assert_array_almost_equal(dat_out, datsp_out)
+
+        dat_out = np.zeros((3,)) if self.is_array_test else np.zeros((3, 1))
+        datsp_out = np.zeros((3,)) if self.is_array_test else matrix(np.zeros((3, 1)))
+
+        dat.sum(axis=1, out=dat_out, keepdims=keep)
+        datsp.sum(axis=1, out=datsp_out)
+        assert_array_almost_equal(dat_out, datsp_out)
+
+        # check that wrong shape out parameter raises
+        with assert_raises(ValueError, match="output parameter.*wrong.*dimension"):
+            datsp.sum(out=array([0]))
+        with assert_raises(ValueError, match="output parameter.*wrong.*dimension"):
+            datsp.sum(out=array([[0]] if self.is_array_test else 0))
+
+    def test_numpy_sum(self):
+        # See gh-5987
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        dat_sum = np.sum(dat)
+        datsp_sum = np.sum(datsp)
+
+        assert_array_almost_equal(dat_sum, datsp_sum)
+        assert_equal(dat_sum.dtype, datsp_sum.dtype)
+
+    def test_mean(self):
+        keep = not self.is_array_test
+        def check(dtype):
+            dat = array([[0, 1, 2],
+                         [3, 4, 5],
+                         [6, 7, 9]], dtype=dtype)
+            datsp = self.spcreator(dat, dtype=dtype)
+
+            assert_array_almost_equal(dat.mean(), datsp.mean())
+            assert_equal(dat.mean().dtype, datsp.mean().dtype)
+            assert_(np.isscalar(datsp.mean(axis=None)))
+            assert_array_almost_equal(
+                dat.mean(axis=None, keepdims=keep), datsp.mean(axis=None)
+            )
+            assert_equal(dat.mean(axis=None).dtype, datsp.mean(axis=None).dtype)
+            assert_array_almost_equal(
+                dat.mean(axis=0, keepdims=keep), datsp.mean(axis=0)
+            )
+            assert_equal(dat.mean(axis=0).dtype, datsp.mean(axis=0).dtype)
+            assert_array_almost_equal(
+                dat.mean(axis=1, keepdims=keep), datsp.mean(axis=1)
+            )
+            assert_equal(dat.mean(axis=1).dtype, datsp.mean(axis=1).dtype)
+            assert_array_almost_equal(
+                dat.mean(axis=-2, keepdims=keep), datsp.mean(axis=-2)
+            )
+            assert_equal(dat.mean(axis=-2).dtype, datsp.mean(axis=-2).dtype)
+            assert_array_almost_equal(
+                dat.mean(axis=-1, keepdims=keep), datsp.mean(axis=-1)
+            )
+            assert_equal(dat.mean(axis=-1).dtype, datsp.mean(axis=-1).dtype)
+
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_mean_invalid_params(self):
+        out = self.asdense(np.zeros((1, 3)))
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        assert_raises(ValueError, datsp.mean, axis=3)
+        assert_raises(TypeError, datsp.mean, axis=(0, 1))
+        assert_raises(TypeError, datsp.mean, axis=1.5)
+        assert_raises(ValueError, datsp.mean, axis=1, out=out)
+
+    def test_mean_dtype(self):
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        def check(dtype):
+            dat_mean = dat.mean(dtype=dtype)
+            datsp_mean = datsp.mean(dtype=dtype)
+
+            assert_array_almost_equal(dat_mean, datsp_mean)
+            assert_equal(dat_mean.dtype, datsp_mean.dtype)
+
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_mean_out(self):
+        keep = not self.is_array_test
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        dat_out = array(0) if self.is_array_test else array([[0]])
+        datsp_out = array(0) if self.is_array_test else matrix([[0]])
+
+        dat.mean(out=dat_out, keepdims=keep)
+        datsp.mean(out=datsp_out)
+        assert_array_almost_equal(dat_out, datsp_out)
+
+        dat_out = np.zeros((3,)) if self.is_array_test else np.zeros((3, 1))
+        datsp_out = np.zeros((3,)) if self.is_array_test else matrix(np.zeros((3, 1)))
+
+        dat.mean(axis=1, out=dat_out, keepdims=keep)
+        datsp.mean(axis=1, out=datsp_out)
+        assert_array_almost_equal(dat_out, datsp_out)
+
+        # check that wrong shape out parameter raises
+        with assert_raises(ValueError, match="output parameter.*wrong.*dimension"):
+            datsp.mean(out=array([0]))
+        with assert_raises(ValueError, match="output parameter.*wrong.*dimension"):
+            datsp.mean(out=array([[0]] if self.is_array_test else 0))
+
+    def test_numpy_mean(self):
+        # See gh-5987
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        dat_mean = np.mean(dat)
+        datsp_mean = np.mean(datsp)
+
+        assert_array_almost_equal(dat_mean, datsp_mean)
+        assert_equal(dat_mean.dtype, datsp_mean.dtype)
+
+    def test_expm(self):
+        M = array([[1, 0, 2], [0, 0, 3], [-4, 5, 6]], float)
+        sM = self.spcreator(M, shape=(3,3), dtype=float)
+        Mexp = scipy.linalg.expm(M)
+
+        N = array([[3., 0., 1.], [0., 2., 0.], [0., 0., 0.]])
+        sN = self.spcreator(N, shape=(3,3), dtype=float)
+        Nexp = scipy.linalg.expm(N)
+
+        with suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "splu converted its input to CSC format",
+            )
+            sup.filter(
+                SparseEfficiencyWarning,
+                "spsolve is more efficient when sparse b is in the CSC matrix format",
+            )
+            sup.filter(
+                SparseEfficiencyWarning,
+                "spsolve requires A be CSC or CSR matrix format",
+            )
+            sMexp = expm(sM).toarray()
+            sNexp = expm(sN).toarray()
+
+        assert_array_almost_equal((sMexp - Mexp), zeros((3, 3)))
+        assert_array_almost_equal((sNexp - Nexp), zeros((3, 3)))
+
+    def test_inv(self):
+        def check(dtype):
+            M = array([[1, 0, 2], [0, 0, 3], [-4, 5, 6]], dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning,
+                           "spsolve requires A be CSC or CSR matrix format",)
+                sup.filter(SparseEfficiencyWarning,
+                           "spsolve is more efficient when sparse b "
+                           "is in the CSC matrix format",)
+                sup.filter(SparseEfficiencyWarning,
+                           "splu converted its input to CSC format",)
+                sM = self.spcreator(M, shape=(3,3), dtype=dtype)
+                sMinv = inv(sM)
+            assert_array_almost_equal(sMinv.dot(sM).toarray(), np.eye(3))
+            assert_raises(TypeError, inv, M)
+        for dtype in [float]:
+            check(dtype)
+
+    @sup_complex
+    def test_from_array(self):
+        A = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]])
+        assert_array_equal(self.spcreator(A).toarray(), A)
+
+        A = array([[1.0 + 3j, 0, 0],
+                   [0, 2.0 + 5, 0],
+                   [0, 0, 0]])
+        assert_array_equal(self.spcreator(A).toarray(), A)
+        assert_array_equal(self.spcreator(A, dtype='int16').toarray(),A.astype('int16'))
+
+    @sup_complex
+    def test_from_matrix(self):
+        A = self.asdense([[1, 0, 0], [2, 3, 4], [0, 5, 0], [0, 0, 0]])
+        assert_array_equal(self.spcreator(A).todense(), A)
+
+        A = self.asdense([[1.0 + 3j, 0, 0],
+                          [0, 2.0 + 5, 0],
+                          [0, 0, 0]])
+        assert_array_equal(self.spcreator(A).todense(), A)
+        assert_array_equal(
+            self.spcreator(A, dtype='int16').todense(), A.astype('int16')
+        )
+
+    @sup_complex
+    def test_from_list(self):
+        A = [[1,0,0],[2,3,4],[0,5,0],[0,0,0]]
+        assert_array_equal(self.spcreator(A).toarray(), A)
+
+        A = [[1.0 + 3j, 0, 0],
+             [0, 2.0 + 5, 0],
+             [0, 0, 0]]
+        assert_array_equal(self.spcreator(A).toarray(), array(A))
+        assert_array_equal(
+            self.spcreator(A, dtype='int16').toarray(), array(A).astype('int16')
+        )
+
+    @sup_complex
+    def test_from_sparse(self):
+        D = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]])
+        S = self.csr_container(D)
+        assert_array_equal(self.spcreator(S).toarray(), D)
+        S = self.spcreator(D)
+        assert_array_equal(self.spcreator(S).toarray(), D)
+
+        D = array([[1.0 + 3j, 0, 0],
+                   [0, 2.0 + 5, 0],
+                   [0, 0, 0]])
+        S = self.csr_container(D)
+        assert_array_equal(self.spcreator(S).toarray(), D)
+        assert_array_equal(self.spcreator(S, dtype='int16').toarray(),
+                           D.astype('int16'))
+        S = self.spcreator(D)
+        assert_array_equal(self.spcreator(S).toarray(), D)
+        assert_array_equal(self.spcreator(S, dtype='int16').toarray(),
+                           D.astype('int16'))
+
+    # def test_array(self):
+    #    """test array(A) where A is in sparse format"""
+    #    assert_equal( array(self.datsp), self.dat )
+
+    def test_todense(self):
+        # Check C- or F-contiguous (default).
+        chk = self.datsp.todense()
+        assert isinstance(chk, np.ndarray if self.is_array_test else np.matrix)
+        assert_array_equal(chk, self.dat)
+        assert_(chk.flags.c_contiguous != chk.flags.f_contiguous)
+        # Check C-contiguous (with arg).
+        chk = self.datsp.todense(order='C')
+        assert_array_equal(chk, self.dat)
+        assert_(chk.flags.c_contiguous)
+        assert_(not chk.flags.f_contiguous)
+        # Check F-contiguous (with arg).
+        chk = self.datsp.todense(order='F')
+        assert_array_equal(chk, self.dat)
+        assert_(not chk.flags.c_contiguous)
+        assert_(chk.flags.f_contiguous)
+        # Check with out argument (array).
+        out = np.zeros(self.datsp.shape, dtype=self.datsp.dtype)
+        chk = self.datsp.todense(out=out)
+        assert_array_equal(self.dat, out)
+        assert_array_equal(self.dat, chk)
+        assert np.may_share_memory(chk, out)
+        # Check with out array (matrix).
+        out = self.asdense(np.zeros(self.datsp.shape, dtype=self.datsp.dtype))
+        chk = self.datsp.todense(out=out)
+        assert_array_equal(self.dat, out)
+        assert_array_equal(self.dat, chk)
+        assert np.may_share_memory(chk, out)
+        a = array([[1.,2.,3.]])
+        dense_dot_dense = a @ self.dat
+        check = a @ self.datsp.todense()
+        assert_array_equal(dense_dot_dense, check)
+        b = array([[1.,2.,3.,4.]]).T
+        dense_dot_dense = self.dat @ b
+        check2 = self.datsp.todense() @ b
+        assert_array_equal(dense_dot_dense, check2)
+        # Check bool data works.
+        spbool = self.spcreator(self.dat, dtype=bool)
+        matbool = self.dat.astype(bool)
+        assert_array_equal(spbool.todense(), matbool)
+
+    def test_toarray(self):
+        # Check C- or F-contiguous (default).
+        dat = asarray(self.dat)
+        chk = self.datsp.toarray()
+        assert_array_equal(chk, dat)
+        assert_(chk.flags.c_contiguous != chk.flags.f_contiguous)
+        # Check C-contiguous (with arg).
+        chk = self.datsp.toarray(order='C')
+        assert_array_equal(chk, dat)
+        assert_(chk.flags.c_contiguous)
+        assert_(not chk.flags.f_contiguous)
+        # Check F-contiguous (with arg).
+        chk = self.datsp.toarray(order='F')
+        assert_array_equal(chk, dat)
+        assert_(not chk.flags.c_contiguous)
+        assert_(chk.flags.f_contiguous)
+        # Check with output arg.
+        out = np.zeros(self.datsp.shape, dtype=self.datsp.dtype)
+        self.datsp.toarray(out=out)
+        assert_array_equal(chk, dat)
+        # Check that things are fine when we don't initialize with zeros.
+        out[...] = 1.
+        self.datsp.toarray(out=out)
+        assert_array_equal(chk, dat)
+        a = array([1.,2.,3.])
+        dense_dot_dense = dot(a, dat)
+        check = dot(a, self.datsp.toarray())
+        assert_array_equal(dense_dot_dense, check)
+        b = array([1.,2.,3.,4.])
+        dense_dot_dense = dot(dat, b)
+        check2 = dot(self.datsp.toarray(), b)
+        assert_array_equal(dense_dot_dense, check2)
+        # Check bool data works.
+        spbool = self.spcreator(self.dat, dtype=bool)
+        arrbool = dat.astype(bool)
+        assert_array_equal(spbool.toarray(), arrbool)
+
+    @sup_complex
+    def test_astype(self):
+        D = array([[2.0 + 3j, 0, 0],
+                   [0, 4.0 + 5j, 0],
+                   [0, 0, 0]])
+        S = self.spcreator(D)
+
+        for x in supported_dtypes:
+            # Check correctly casted
+            D_casted = D.astype(x)
+            for copy in (True, False):
+                S_casted = S.astype(x, copy=copy)
+                assert_equal(S_casted.dtype, D_casted.dtype)  # correct type
+                assert_equal(S_casted.toarray(), D_casted)    # correct values
+                assert_equal(S_casted.format, S.format)       # format preserved
+            # Check correctly copied
+            assert_(S_casted.astype(x, copy=False) is S_casted)
+            S_copied = S_casted.astype(x, copy=True)
+            assert_(S_copied is not S_casted)
+
+            def check_equal_but_not_same_array_attribute(attribute):
+                a = getattr(S_casted, attribute)
+                b = getattr(S_copied, attribute)
+                assert_array_equal(a, b)
+                assert_(a is not b)
+                i = (0,) * b.ndim
+                b_i = b[i]
+                b[i] = not b[i]
+                assert_(a[i] != b[i])
+                b[i] = b_i
+
+            if S_casted.format in ('csr', 'csc', 'bsr'):
+                for attribute in ('indices', 'indptr', 'data'):
+                    check_equal_but_not_same_array_attribute(attribute)
+            elif S_casted.format == 'coo':
+                for attribute in ('row', 'col', 'data'):
+                    check_equal_but_not_same_array_attribute(attribute)
+            elif S_casted.format == 'dia':
+                for attribute in ('offsets', 'data'):
+                    check_equal_but_not_same_array_attribute(attribute)
+
+    @sup_complex
+    def test_astype_immutable(self):
+        D = array([[2.0 + 3j, 0, 0],
+                   [0, 4.0 + 5j, 0],
+                   [0, 0, 0]])
+        S = self.spcreator(D)
+        if hasattr(S, 'data'):
+            S.data.flags.writeable = False
+        if S.format in ('csr', 'csc', 'bsr'):
+            S.indptr.flags.writeable = False
+            S.indices.flags.writeable = False
+        for x in supported_dtypes:
+            D_casted = D.astype(x)
+            S_casted = S.astype(x)
+            assert_equal(S_casted.dtype, D_casted.dtype)
+
+    def test_mul_scalar(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_array_equal(dat*2, (datsp*2).toarray())
+            assert_array_equal(dat*17.3, (datsp*17.3).toarray())
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_rmul_scalar(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_array_equal(2*dat, (2*datsp).toarray())
+            assert_array_equal(17.3*dat, (17.3*datsp).toarray())
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    # GitHub issue #15210
+    def test_rmul_scalar_type_error(self):
+        datsp = self.datsp_dtypes[np.float64]
+        with assert_raises(TypeError):
+            None * datsp
+
+    def test_add(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            a = dat.copy()
+            a[0,2] = 2.0
+            b = datsp
+            c = b + a
+            assert_array_equal(c, b.toarray() + a)
+
+            c = b + b.tocsr()
+            assert_array_equal(c.toarray(),
+                               b.toarray() + b.toarray())
+
+            # test broadcasting
+            c = b + a[0]
+            assert_array_equal(c, b.toarray() + a[0])
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_radd(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            a = dat.copy()
+            a[0,2] = 2.0
+            b = datsp
+            c = a + b
+            assert_array_equal(c, a + b.toarray())
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_sub(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_array_equal((datsp - datsp).toarray(), np.zeros((3, 4)))
+            assert_array_equal((datsp - 0).toarray(), dat)
+
+            A = self.spcreator(
+                np.array([[1, 0, 0, 4], [-1, 0, 0, 0], [0, 8, 0, -5]], 'd')
+            )
+            assert_array_equal((datsp - A).toarray(), dat - A.toarray())
+            assert_array_equal((A - datsp).toarray(), A.toarray() - dat)
+
+            # test broadcasting
+            assert_array_equal(datsp - dat[0], dat - dat[0])
+
+        for dtype in self.math_dtypes:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            check(dtype)
+
+    def test_rsub(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_array_equal((dat - datsp),[[0,0,0,0],[0,0,0,0],[0,0,0,0]])
+            assert_array_equal((datsp - dat),[[0,0,0,0],[0,0,0,0],[0,0,0,0]])
+            assert_array_equal((0 - datsp).toarray(), -dat)
+
+            A = self.spcreator([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],dtype='d')
+            assert_array_equal((dat - A), dat - A.toarray())
+            assert_array_equal((A - dat), A.toarray() - dat)
+            assert_array_equal(A.toarray() - datsp, A.toarray() - dat)
+            assert_array_equal(datsp - A.toarray(), dat - A.toarray())
+
+            # test broadcasting
+            assert_array_equal(dat[0] - datsp, dat[0] - dat)
+
+        for dtype in self.math_dtypes:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            check(dtype)
+
+    def test_add0(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            # Adding 0 to a sparse matrix
+            assert_array_equal((datsp + 0).toarray(), dat)
+            # use sum (which takes 0 as a starting value)
+            sumS = sum([k * datsp for k in range(1, 3)])
+            sumD = sum([k * dat for k in range(1, 3)])
+            assert_almost_equal(sumS.toarray(), sumD)
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_elementwise_multiply(self):
+        # real/real
+        A = array([[4,0,9],[2,-3,5]])
+        B = array([[0,7,0],[0,-4,0]])
+        Asp = self.spcreator(A)
+        Bsp = self.spcreator(B)
+        assert_almost_equal(Asp.multiply(Bsp).toarray(), A*B)  # sparse/sparse
+        assert_almost_equal(Asp.multiply(B).toarray(), A*B)  # sparse/dense
+
+        # complex/complex
+        C = array([[1-2j,0+5j,-1+0j],[4-3j,-3+6j,5]])
+        D = array([[5+2j,7-3j,-2+1j],[0-1j,-4+2j,9]])
+        Csp = self.spcreator(C)
+        Dsp = self.spcreator(D)
+        assert_almost_equal(Csp.multiply(Dsp).toarray(), C*D)  # sparse/sparse
+        assert_almost_equal(Csp.multiply(D).toarray(), C*D)  # sparse/dense
+
+        # real/complex
+        assert_almost_equal(Asp.multiply(Dsp).toarray(), A*D)  # sparse/sparse
+        assert_almost_equal(Asp.multiply(D).toarray(), A*D)  # sparse/dense
+
+    def test_elementwise_multiply_broadcast(self):
+        A = array([4])
+        B = array([[-9]])
+        C = array([1,-1,0])
+        D = array([[7,9,-9]])
+        E = array([[3],[2],[1]])
+        F = array([[8,6,3],[-4,3,2],[6,6,6]])
+        G = [1, 2, 3]
+        H = np.ones((3, 4))
+        J = H.T
+        K = array([[0]])
+        L = array([[[1,2],[0,1]]])
+
+        # Some arrays can't be cast as spmatrices (A,C,L) so leave
+        # them out.
+        Bsp = self.spcreator(B)
+        Dsp = self.spcreator(D)
+        Esp = self.spcreator(E)
+        Fsp = self.spcreator(F)
+        Hsp = self.spcreator(H)
+        Hspp = self.spcreator(H[0,None])
+        Jsp = self.spcreator(J)
+        Jspp = self.spcreator(J[:,0,None])
+        Ksp = self.spcreator(K)
+
+        matrices = [A, B, C, D, E, F, G, H, J, K, L]
+        spmatrices = [Bsp, Dsp, Esp, Fsp, Hsp, Hspp, Jsp, Jspp, Ksp]
+
+        # sparse/sparse
+        for i in spmatrices:
+            for j in spmatrices:
+                try:
+                    dense_mult = i.toarray() * j.toarray()
+                except ValueError:
+                    assert_raises(ValueError, i.multiply, j)
+                    continue
+                sp_mult = i.multiply(j)
+                assert_almost_equal(sp_mult.toarray(), dense_mult)
+
+        # sparse/dense
+        for i in spmatrices:
+            for j in matrices:
+                try:
+                    dense_mult = i.toarray() * j
+                except TypeError:
+                    continue
+                except ValueError:
+                    assert_raises(ValueError, i.multiply, j)
+                    continue
+                sp_mult = i.multiply(j)
+                if issparse(sp_mult):
+                    assert_almost_equal(sp_mult.toarray(), dense_mult)
+                else:
+                    assert_almost_equal(sp_mult, dense_mult)
+
+    def test_elementwise_divide(self):
+        expected = [[1,np.nan,np.nan,1],
+                    [1,np.nan,1,np.nan],
+                    [np.nan,1,np.nan,np.nan]]
+        assert_array_equal(toarray(self.datsp / self.datsp), expected)
+
+        denom = self.spcreator([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],dtype='d')
+        expected = [[1,np.nan,np.nan,0.5],
+                    [-3,np.nan,inf,np.nan],
+                    [np.nan,0.25,np.nan,0]]
+        assert_array_equal(toarray(self.datsp / denom), expected)
+
+        # complex
+        A = array([[1-2j,0+5j,-1+0j],[4-3j,-3+6j,5]])
+        B = array([[5+2j,7-3j,-2+1j],[0-1j,-4+2j,9]])
+        Asp = self.spcreator(A)
+        Bsp = self.spcreator(B)
+        assert_almost_equal(toarray(Asp / Bsp), A/B)
+
+        # integer
+        A = array([[1,2,3],[-3,2,1]])
+        B = array([[0,1,2],[0,-2,3]])
+        Asp = self.spcreator(A)
+        Bsp = self.spcreator(B)
+        with np.errstate(divide='ignore'):
+            assert_array_equal(toarray(Asp / Bsp), A / B)
+
+        # mismatching sparsity patterns
+        A = array([[0,1],[1,0]])
+        B = array([[1,0],[1,0]])
+        Asp = self.spcreator(A)
+        Bsp = self.spcreator(B)
+        with np.errstate(divide='ignore', invalid='ignore'):
+            assert_array_equal(np.array(toarray(Asp / Bsp)), A / B)
+
+    def test_pow(self):
+        A = array([[1, 0, 2, 0], [0, 3, 4, 0], [0, 5, 0, 0], [0, 6, 7, 8]])
+        B = self.spcreator(A)
+
+        if self.is_array_test:  # sparrays use element-wise power
+            # Todo: Add 1+3j to tested exponent list when np1.24 is no longer supported
+            #    Complex exponents of 0 (our implicit fill value) change in numpy-1.25
+            #    from `(nan+nanj)` to `0`. Old value makes array element-wise result
+            #    dense and is hard to check for without any `isnan` method.
+            # So while untested here, element-wise complex exponents work with np>=1.25.
+            # for exponent in [1, 2, 2.2, 3, 1+3j]:
+            for exponent in [1, 2, 2.2, 3]:
+                ret_sp = B**exponent
+                ret_np = A**exponent
+                assert_array_equal(ret_sp.toarray(), ret_np)
+                assert_equal(ret_sp.dtype, ret_np.dtype)
+
+            # invalid exponents
+            assert_raises(NotImplementedError, B.__pow__, 0)
+            assert_raises(ValueError, B.__pow__, -1)
+
+            # nonsquare matrix
+            B = self.spcreator(A[:3,:])
+            assert_equal((B**1).toarray(), B.toarray())
+        else:  # test sparse matrix. spmatrices use matrix multiplicative power
+            for exponent in [0,1,2,3]:
+                ret_sp = B**exponent
+                ret_np = np.linalg.matrix_power(A, exponent)
+                assert_array_equal(ret_sp.toarray(), ret_np)
+                assert_equal(ret_sp.dtype, ret_np.dtype)
+
+            # invalid exponents
+            for exponent in [-1, 2.2, 1 + 3j]:
+                assert_raises(ValueError, B.__pow__, exponent)
+
+            # nonsquare matrix
+            B = self.spcreator(A[:3,:])
+            assert_raises(TypeError, B.__pow__, 1)
+
+    def test_rmatvec(self):
+        M = self.spcreator([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
+        assert_array_almost_equal([1,2,3,4] @ M, dot([1,2,3,4], M.toarray()))
+        row = array([[1,2,3,4]])
+        assert_array_almost_equal(row @ M, row @ M.toarray())
+
+    def test_small_multiplication(self):
+        # test that A*x works for x with shape () (1,) (1,1) and (1,0)
+        A = self.spcreator([[1],[2],[3]])
+
+        assert_(issparse(A * array(1)))
+        assert_equal((A * array(1)).toarray(), [[1], [2], [3]])
+
+        assert_equal(A @ array([1]), array([1, 2, 3]))
+        assert_equal(A @ array([[1]]), array([[1], [2], [3]]))
+        assert_equal(A @ np.ones((1, 1)), array([[1], [2], [3]]))
+        assert_equal(A @ np.ones((1, 0)), np.ones((3, 0)))
+
+    def test_star_vs_at_sign_for_sparray_and_spmatrix(self):
+        # test that * is matmul for spmatrix and mul for sparray
+        A = np.array([[1], [2], [3]])
+        Asp = self.spcreator(A)
+
+        if self.is_array_test:
+            assert_array_almost_equal((Asp * np.ones((3, 1))).toarray(), A)
+            assert_array_almost_equal((Asp * array([[1]])).toarray(), A)
+        else:
+            assert_equal(Asp * array([1]), array([1, 2, 3]))
+            assert_equal(Asp * array([[1]]), array([[1], [2], [3]]))
+            assert_equal(Asp * np.ones((1, 0)), np.ones((3, 0)))
+
+    def test_binop_custom_type(self):
+        # Non-regression test: previously, binary operations would raise
+        # NotImplementedError instead of returning NotImplemented
+        # (https://docs.python.org/library/constants.html#NotImplemented)
+        # so overloading Custom + matrix etc. didn't work.
+        A = self.spcreator([[1], [2], [3]])
+        B = BinopTester()
+        assert_equal(A + B, "matrix on the left")
+        assert_equal(A - B, "matrix on the left")
+        assert_equal(A * B, "matrix on the left")
+        assert_equal(B + A, "matrix on the right")
+        assert_equal(B - A, "matrix on the right")
+        assert_equal(B * A, "matrix on the right")
+
+        assert_equal(A @ B, "matrix on the left")
+        assert_equal(B @ A, "matrix on the right")
+
+    def test_binop_custom_type_with_shape(self):
+        A = self.spcreator([[1], [2], [3]])
+        B = BinopTester_with_shape((3,1))
+        assert_equal(A + B, "matrix on the left")
+        assert_equal(A - B, "matrix on the left")
+        assert_equal(A * B, "matrix on the left")
+        assert_equal(B + A, "matrix on the right")
+        assert_equal(B - A, "matrix on the right")
+        assert_equal(B * A, "matrix on the right")
+
+        assert_equal(A @ B, "matrix on the left")
+        assert_equal(B @ A, "matrix on the right")
+
+    def test_mul_custom_type(self):
+        class Custom:
+            def __init__(self, scalar):
+                self.scalar = scalar
+
+            def __rmul__(self, other):
+                return other * self.scalar
+
+        scalar = 2
+        A = self.spcreator([[1],[2],[3]])
+        c = Custom(scalar)
+        A_scalar = A * scalar
+        A_c = A * c
+        assert_array_equal_dtype(A_scalar.toarray(), A_c.toarray())
+        assert_equal(A_scalar.format, A_c.format)
+
+    def test_comparisons_custom_type(self):
+        A = self.spcreator([[1], [2], [3]])
+        B = ComparisonTester()
+        assert_equal(A == B, "eq")
+        assert_equal(A != B, "ne")
+        assert_equal(A > B, "lt")
+        assert_equal(A >= B, "le")
+        assert_equal(A < B, "gt")
+        assert_equal(A <= B, "ge")
+
+    def test_dot_scalar(self):
+        M = self.spcreator(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
+        scalar = 10
+        actual = M.dot(scalar)
+        expected = M * scalar
+
+        assert_allclose(actual.toarray(), expected.toarray())
+
+    def test_matmul(self):
+        M = self.spcreator(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
+        B = self.spcreator(array([[0,1],[1,0],[0,2]],'d'))
+        col = array([[1,2,3]]).T
+
+        matmul = operator.matmul
+        # check matrix-vector
+        assert_array_almost_equal(matmul(M, col), M.toarray() @ col)
+
+        # check matrix-matrix
+        assert_array_almost_equal(matmul(M, B).toarray(), (M @ B).toarray())
+        assert_array_almost_equal(matmul(M.toarray(), B), (M @ B).toarray())
+        assert_array_almost_equal(matmul(M, B.toarray()), (M @ B).toarray())
+
+        # check error on matrix-scalar
+        assert_raises(ValueError, matmul, M, 1)
+        assert_raises(ValueError, matmul, 1, M)
+
+    def test_matvec(self):
+        M = self.spcreator([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
+        col = array([[1,2,3]]).T
+
+        assert_array_almost_equal(M @ col, M.toarray() @ col)
+
+        # check result dimensions (ticket #514)
+        assert_equal((M @ array([1,2,3])).shape,(4,))
+        assert_equal((M @ array([[1],[2],[3]])).shape,(4,1))
+        assert_equal((M @ matrix([[1],[2],[3]])).shape,(4,1))
+
+        # check result type
+        assert_(isinstance(M @ array([1,2,3]), ndarray))
+        matrix_or_array = ndarray if self.is_array_test else np.matrix
+        assert_(isinstance(M @ matrix([1,2,3]).T, matrix_or_array))
+
+        # ensure exception is raised for improper dimensions
+        bad_vecs = [array([1,2]), array([1,2,3,4]), array([[1],[2]]),
+                    matrix([1,2,3]), matrix([[1],[2]])]
+        for x in bad_vecs:
+            assert_raises(ValueError, M.__matmul__, x)
+
+        # The current relationship between sparse matrix products and array
+        # products is as follows:
+        assert_almost_equal(M@array([1,2,3]), dot(M.toarray(),[1,2,3]))
+        assert_almost_equal(M@[[1],[2],[3]], np.atleast_2d(dot(M.toarray(),[1,2,3])).T)
+        # Note that the result of M * x is dense if x has a singleton dimension.
+
+        # Currently M.matvec(asarray(col)) is rank-1, whereas M.matvec(col)
+        # is rank-2.  Is this desirable?
+
+    def test_matmat_sparse(self):
+        a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
+        a2 = array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
+        b = matrix([[0,1],[1,0],[0,2]],'d')
+        asp = self.spcreator(a)
+        bsp = self.spcreator(b)
+        assert_array_almost_equal((asp @ bsp).toarray(), a @ b)
+        assert_array_almost_equal(asp @ b, a @ b)
+        assert_array_almost_equal(a @ bsp, a @ b)
+        assert_array_almost_equal(a2 @ bsp, a @ b)
+
+        # Now try performing cross-type multiplication:
+        csp = bsp.tocsc()
+        c = b
+        want = a @ c
+        assert_array_almost_equal((asp @ csp).toarray(), want)
+        assert_array_almost_equal(asp @ c, want)
+
+        assert_array_almost_equal(a @ csp, want)
+        assert_array_almost_equal(a2 @ csp, want)
+        csp = bsp.tocsr()
+        assert_array_almost_equal((asp @ csp).toarray(), want)
+        assert_array_almost_equal(asp @ c, want)
+
+        assert_array_almost_equal(a @ csp, want)
+        assert_array_almost_equal(a2 @ csp, want)
+        csp = bsp.tocoo()
+        assert_array_almost_equal((asp @ csp).toarray(), want)
+        assert_array_almost_equal(asp @ c, want)
+
+        assert_array_almost_equal(a @ csp, want)
+        assert_array_almost_equal(a2 @ csp, want)
+
+        # Test provided by Andy Fraser, 2006-03-26
+        L = 30
+        frac = .3
+        random.seed(0)  # make runs repeatable
+        A = zeros((L,2))
+        for i in range(L):
+            for j in range(2):
+                r = random.random()
+                if r < frac:
+                    A[i,j] = r/frac
+
+        A = self.spcreator(A)
+        B = A @ A.T
+        assert_array_almost_equal(B.toarray(), A.toarray() @ A.T.toarray())
+        assert_array_almost_equal(B.toarray(), A.toarray() @ A.toarray().T)
+
+        # check dimension mismatch 2x2 times 3x2
+        A = self.spcreator([[1,2],[3,4]])
+        B = self.spcreator([[1,2],[3,4],[5,6]])
+        assert_raises(ValueError, A.__matmul__, B)
+        if self.is_array_test:
+            assert_raises(ValueError, A.__mul__, B)
+
+    def test_matmat_dense(self):
+        a = [[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]
+        asp = self.spcreator(a)
+
+        # check both array and matrix types
+        bs = [array([[1,2],[3,4],[5,6]]), matrix([[1,2],[3,4],[5,6]])]
+
+        for b in bs:
+            result = asp @ b
+            assert_(isinstance(result, ndarray if self.is_array_test else type(b)))
+            assert_equal(result.shape, (4,2))
+            assert_equal(result, dot(a,b))
+
+    def test_sparse_format_conversions(self):
+        A = sparse.kron([[1,0,2],[0,3,4],[5,0,0]], [[1,2],[0,3]])
+        D = A.toarray()
+        A = self.spcreator(A)
+
+        for format in ['bsr','coo','csc','csr','dia','dok','lil']:
+            a = A.asformat(format)
+            assert_equal(a.format,format)
+            assert_array_equal(a.toarray(), D)
+
+            b = self.spcreator(D+3j).asformat(format)
+            assert_equal(b.format,format)
+            assert_array_equal(b.toarray(), D+3j)
+
+            c = self.spcreator(D).asformat(format)
+            assert_equal(c.format,format)
+            assert_array_equal(c.toarray(), D)
+
+        for format in ['array', 'dense']:
+            a = A.asformat(format)
+            assert_array_equal(a, D)
+
+            b = self.spcreator(D+3j).asformat(format)
+            assert_array_equal(b, D+3j)
+
+    def test_tobsr(self):
+        x = array([[1,0,2,0],[0,0,0,0],[0,0,4,5]])
+        y = array([[0,1,2],[3,0,5]])
+        A = kron(x,y)
+        Asp = self.spcreator(A)
+        for format in ['bsr']:
+            fn = getattr(Asp, 'to' + format)
+
+            for X in [1, 2, 3, 6]:
+                for Y in [1, 2, 3, 4, 6, 12]:
+                    assert_equal(fn(blocksize=(X, Y)).toarray(), A)
+
+    def test_transpose(self):
+        dat_1 = self.dat
+        dat_2 = np.array([[]])
+        matrices = [dat_1, dat_2]
+
+        def check(dtype, j):
+            dat = array(matrices[j], dtype=dtype)
+            datsp = self.spcreator(dat)
+
+            a = datsp.transpose()
+            b = dat.transpose()
+
+            assert_array_equal(a.toarray(), b)
+            assert_array_equal(a.transpose().toarray(), dat)
+            assert_array_equal(datsp.transpose(axes=(1, 0)).toarray(), b)
+            assert_equal(a.dtype, b.dtype)
+
+        # See gh-5987
+        empty = self.spcreator((3, 4))
+        assert_array_equal(np.transpose(empty).toarray(),
+                           np.transpose(zeros((3, 4))))
+        assert_array_equal(empty.T.toarray(), zeros((4, 3)))
+        assert_raises(ValueError, empty.transpose, axes=0)
+
+        for dtype in self.checked_dtypes:
+            for j in range(len(matrices)):
+                check(dtype, j)
+
+    def test_add_dense(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            # adding a dense matrix to a sparse matrix
+            sum1 = dat + datsp
+            assert_array_equal(sum1, dat + dat)
+            sum2 = datsp + dat
+            assert_array_equal(sum2, dat + dat)
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_sub_dense(self):
+        # subtracting a dense matrix to/from a sparse matrix
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            # Behavior is different for bool.
+            if dat.dtype == bool:
+                sum1 = dat - datsp
+                assert_array_equal(sum1, dat - dat)
+                sum2 = datsp - dat
+                assert_array_equal(sum2, dat - dat)
+            else:
+                # Manually add to avoid upcasting from scalar
+                # multiplication.
+                sum1 = (dat + dat + dat) - datsp
+                assert_array_equal(sum1, dat + dat)
+                sum2 = (datsp + datsp + datsp) - dat
+                assert_array_equal(sum2, dat + dat)
+
+        for dtype in self.math_dtypes:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            check(dtype)
+
+    def test_maximum_minimum(self):
+        A_dense = np.array([[1, 0, 3], [0, 4, 5], [0, 0, 0]])
+        B_dense = np.array([[1, 1, 2], [0, 3, 6], [1, -1, 0]])
+
+        A_dense_cpx = np.array([[1, 0, 3], [0, 4+2j, 5], [0, 1j, -1j]])
+
+        def check(dtype, dtype2, btype):
+            if np.issubdtype(dtype, np.complexfloating):
+                A = self.spcreator(A_dense_cpx.astype(dtype))
+            else:
+                A = self.spcreator(A_dense.astype(dtype))
+            if btype == 'scalar':
+                B = dtype2.type(1)
+            elif btype == 'scalar2':
+                B = dtype2.type(-1)
+            elif btype == 'dense':
+                B = B_dense.astype(dtype2)
+            elif btype == 'sparse':
+                B = self.spcreator(B_dense.astype(dtype2))
+            else:
+                raise ValueError()
+
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning,
+                           "Taking maximum .minimum. with > 0 .< 0. number "
+                           "results to a dense matrix")
+
+                max_s = A.maximum(B)
+                min_s = A.minimum(B)
+
+            max_d = np.maximum(toarray(A), toarray(B))
+            assert_array_equal(toarray(max_s), max_d)
+            assert_equal(max_s.dtype, max_d.dtype)
+
+            min_d = np.minimum(toarray(A), toarray(B))
+            assert_array_equal(toarray(min_s), min_d)
+            assert_equal(min_s.dtype, min_d.dtype)
+
+        for dtype in self.math_dtypes:
+            for dtype2 in [np.int8, np.float64, np.complex128]:
+                for btype in ['scalar', 'scalar2', 'dense', 'sparse']:
+                    check(np.dtype(dtype), np.dtype(dtype2), btype)
+
+    def test_copy(self):
+        # Check whether the copy=True and copy=False keywords work
+        A = self.datsp
+
+        # check that copy preserves format
+        assert_equal(A.copy().format, A.format)
+        assert_equal(A.__class__(A,copy=True).format, A.format)
+        assert_equal(A.__class__(A,copy=False).format, A.format)
+
+        assert_equal(A.copy().toarray(), A.toarray())
+        assert_equal(A.__class__(A, copy=True).toarray(), A.toarray())
+        assert_equal(A.__class__(A, copy=False).toarray(), A.toarray())
+
+        # check that XXX_array.toXXX() works
+        toself = getattr(A,'to' + A.format)
+        assert_(toself() is A)
+        assert_(toself(copy=False) is A)
+        assert_equal(toself(copy=True).format, A.format)
+        assert_equal(toself(copy=True).toarray(), A.toarray())
+
+        # check whether the data is copied?
+        assert_(not sparse_may_share_memory(A.copy(), A))
+
+    # test that __iter__ is compatible with NumPy matrix
+    def test_iterator(self):
+        B = self.asdense(np.arange(50).reshape(5, 10))
+        A = self.spcreator(B)
+
+        for x, y in zip(A, B):
+            assert_equal(x.toarray(), y)
+
+    def test_size_zero_matrix_arithmetic(self):
+        # Test basic matrix arithmetic with shapes like (0,0), (10,0),
+        # (0, 3), etc.
+        mat = array([])
+        a = mat.reshape((0, 0))
+        b = mat.reshape((0, 1))
+        c = mat.reshape((0, 5))
+        d = mat.reshape((1, 0))
+        e = mat.reshape((5, 0))
+        f = np.ones([5, 5])
+
+        asp = self.spcreator(a)
+        bsp = self.spcreator(b)
+        csp = self.spcreator(c)
+        dsp = self.spcreator(d)
+        esp = self.spcreator(e)
+        fsp = self.spcreator(f)
+
+        # matrix product.
+        assert_array_equal(asp.dot(asp).toarray(), np.dot(a, a))
+        assert_array_equal(bsp.dot(dsp).toarray(), np.dot(b, d))
+        assert_array_equal(dsp.dot(bsp).toarray(), np.dot(d, b))
+        assert_array_equal(csp.dot(esp).toarray(), np.dot(c, e))
+        assert_array_equal(csp.dot(fsp).toarray(), np.dot(c, f))
+        assert_array_equal(esp.dot(csp).toarray(), np.dot(e, c))
+        assert_array_equal(dsp.dot(csp).toarray(), np.dot(d, c))
+        assert_array_equal(fsp.dot(esp).toarray(), np.dot(f, e))
+
+        # bad matrix products
+        assert_raises(ValueError, dsp.dot, e)
+        assert_raises(ValueError, asp.dot, d)
+
+        # elemente-wise multiplication
+        assert_array_equal(asp.multiply(asp).toarray(), np.multiply(a, a))
+        assert_array_equal(bsp.multiply(bsp).toarray(), np.multiply(b, b))
+        assert_array_equal(dsp.multiply(dsp).toarray(), np.multiply(d, d))
+
+        assert_array_equal(asp.multiply(a).toarray(), np.multiply(a, a))
+        assert_array_equal(bsp.multiply(b).toarray(), np.multiply(b, b))
+        assert_array_equal(dsp.multiply(d).toarray(), np.multiply(d, d))
+
+        assert_array_equal(asp.multiply(6).toarray(), np.multiply(a, 6))
+        assert_array_equal(bsp.multiply(6).toarray(), np.multiply(b, 6))
+        assert_array_equal(dsp.multiply(6).toarray(), np.multiply(d, 6))
+
+        # bad element-wise multiplication
+        assert_raises(ValueError, asp.multiply, c)
+        assert_raises(ValueError, esp.multiply, c)
+
+        # Addition
+        assert_array_equal(asp.__add__(asp).toarray(), a.__add__(a))
+        assert_array_equal(bsp.__add__(bsp).toarray(), b.__add__(b))
+        assert_array_equal(dsp.__add__(dsp).toarray(), d.__add__(d))
+
+        # bad addition
+        assert_raises(ValueError, asp.__add__, dsp)
+        assert_raises(ValueError, bsp.__add__, asp)
+
+    def test_size_zero_conversions(self):
+        mat = array([])
+        a = mat.reshape((0, 0))
+        b = mat.reshape((0, 5))
+        c = mat.reshape((5, 0))
+
+        for m in [a, b, c]:
+            spm = self.spcreator(m)
+            assert_array_equal(spm.tocoo().toarray(), m)
+            assert_array_equal(spm.tocsr().toarray(), m)
+            assert_array_equal(spm.tocsc().toarray(), m)
+            assert_array_equal(spm.tolil().toarray(), m)
+            assert_array_equal(spm.todok().toarray(), m)
+            assert_array_equal(spm.tobsr().toarray(), m)
+
+    def test_dtype_check(self):
+        a = np.array([[3.5, 0, 1.1], [0, 0, 0]], dtype=np.float16)
+        with assert_raises(ValueError, match="does not support dtype"):
+            self.spcreator(a)
+
+        A32 = self.spcreator(a.astype(np.float32))
+        with assert_raises(ValueError, match="does not support dtype"):
+            self.spcreator(A32, dtype=np.float16)
+
+    def test_pickle(self):
+        import pickle
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        def check():
+            datsp = self.datsp.copy()
+            for protocol in range(pickle.HIGHEST_PROTOCOL):
+                sploaded = pickle.loads(pickle.dumps(datsp, protocol=protocol))
+                assert_equal(datsp.shape, sploaded.shape)
+                assert_array_equal(datsp.toarray(), sploaded.toarray())
+                assert_equal(datsp.format, sploaded.format)
+                # Hacky check for class member equality. This assumes that
+                # all instance variables are one of:
+                #  1. Plain numpy ndarrays
+                #  2. Tuples of ndarrays
+                #  3. Types that support equality comparison with ==
+                for key, val in datsp.__dict__.items():
+                    if isinstance(val, np.ndarray):
+                        assert_array_equal(val, sploaded.__dict__[key])
+                    elif (isinstance(val, tuple) and val
+                          and isinstance(val[0], np.ndarray)):
+                        assert_array_equal(val, sploaded.__dict__[key])
+                    else:
+                        assert_(val == sploaded.__dict__[key])
+        check()
+
+    def test_unary_ufunc_overrides(self):
+        def check(name):
+            if name == "sign":
+                pytest.skip("sign conflicts with comparison op "
+                            "support on Numpy")
+            if self.datsp.format in ["dok", "lil"]:
+                pytest.skip("Unary ops not implemented for dok/lil")
+            ufunc = getattr(np, name)
+
+            X = self.spcreator(np.arange(20).reshape(4, 5) / 20.)
+            X0 = ufunc(X.toarray())
+
+            X2 = ufunc(X)
+            assert_array_equal(X2.toarray(), X0)
+
+        for name in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
+                     "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
+                     "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt",
+                     "abs"]:
+            check(name)
+
+    def test_resize(self):
+        # resize(shape) resizes the matrix in-place
+        D = np.array([[1, 0, 3, 4],
+                      [2, 0, 0, 0],
+                      [3, 0, 0, 0]])
+        S = self.spcreator(D)
+        assert_(S.resize((3, 2)) is None)
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [3, 0]])
+        S.resize((2, 2))
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0]])
+        S.resize((3, 2))
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [0, 0]])
+        S.resize((3, 3))
+        assert_array_equal(S.toarray(), [[1, 0, 0],
+                                         [2, 0, 0],
+                                         [0, 0, 0]])
+        # test no-op
+        S.resize((3, 3))
+        assert_array_equal(S.toarray(), [[1, 0, 0],
+                                         [2, 0, 0],
+                                         [0, 0, 0]])
+
+        # test *args
+        S.resize(3, 2)
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [0, 0]])
+
+        if self.is_array_test and S.format in ["coo", "csr"]:
+            S.resize(1)
+        else:
+            assert_raises((ValueError, NotImplementedError, IndexError), S.resize, 1)
+
+        for bad_shape in [(-1, 2), (2, -1), (1, 2, 3)]:
+            assert_raises(ValueError, S.resize, bad_shape)
+
+    def test_constructor1_base(self):
+        A = self.datsp
+
+        self_format = A.format
+
+        C = A.__class__(A, copy=False)
+        assert_array_equal_dtype(A.toarray(), C.toarray())
+        if self_format not in NON_ARRAY_BACKED_FORMATS:
+            assert_(sparse_may_share_memory(A, C))
+
+        C = A.__class__(A, dtype=A.dtype, copy=False)
+        assert_array_equal_dtype(A.toarray(), C.toarray())
+        if self_format not in NON_ARRAY_BACKED_FORMATS:
+            assert_(sparse_may_share_memory(A, C))
+
+        C = A.__class__(A, dtype=np.float32, copy=False)
+        assert_array_equal(A.toarray(), C.toarray())
+
+        C = A.__class__(A, copy=True)
+        assert_array_equal_dtype(A.toarray(), C.toarray())
+        assert_(not sparse_may_share_memory(A, C))
+
+        for other_format in ['csr', 'csc', 'coo', 'dia', 'dok', 'lil']:
+            if other_format == self_format:
+                continue
+            B = A.asformat(other_format)
+            C = A.__class__(B, copy=False)
+            assert_array_equal_dtype(A.toarray(), C.toarray())
+
+            C = A.__class__(B, copy=True)
+            assert_array_equal_dtype(A.toarray(), C.toarray())
+            assert_(not sparse_may_share_memory(B, C))
+
+
+class _TestInplaceArithmetic:
+    def test_inplace_dense(self):
+        a = np.ones((3, 4))
+        b = self.spcreator(a)
+
+        x = a.copy()
+        y = a.copy()
+        x += a
+        y += b
+        assert_array_equal(x, y)
+
+        x = a.copy()
+        y = a.copy()
+        x -= a
+        y -= b
+        assert_array_equal(x, y)
+
+        if self.is_array_test:
+            # Elementwise multiply from sparray.__rmul__
+            x = a.copy()
+            y = a.copy()
+            with assert_raises(ValueError, match="inconsistent shapes"):
+                x *= b.T
+            x = x * a
+            y *= b
+            assert_array_equal(x, y.toarray())
+        else:
+            # Matrix multiply from spmatrix.__rmul__
+            x = a.copy()
+            y = a.copy()
+            with assert_raises(ValueError, match="dimension mismatch"):
+                x *= b
+            x = x.dot(a.T)
+            y *= b.T
+            assert_array_equal(x, y)
+
+        # Matrix multiply from __rmatmul__
+        y = a.copy()
+        # skip this test if numpy doesn't support __imatmul__ yet.
+        # move out of the try/except once numpy 1.24 is no longer supported.
+        try:
+            y @= b.T
+        except TypeError:
+            pass
+        else:
+            x = a.copy()
+            y = a.copy()
+            with assert_raises(ValueError, match="dimension mismatch"):
+                x @= b
+            x = x.dot(a.T)
+            y @= b.T
+            assert_array_equal(x, y)
+
+        # Floor division is not supported
+        with assert_raises(TypeError, match="unsupported operand"):
+            x //= b
+
+    def test_imul_scalar(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            # Avoid implicit casting.
+            if np.can_cast(int, dtype, casting='same_kind'):
+                a = datsp.copy()
+                a *= 2
+                b = dat.copy()
+                b *= 2
+                assert_array_equal(b, a.toarray())
+
+            if np.can_cast(float, dtype, casting='same_kind'):
+                a = datsp.copy()
+                a *= 17.3
+                b = dat.copy()
+                b *= 17.3
+                assert_array_equal(b, a.toarray())
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_idiv_scalar(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            if np.can_cast(int, dtype, casting='same_kind'):
+                a = datsp.copy()
+                a /= 2
+                b = dat.copy()
+                b /= 2
+                assert_array_equal(b, a.toarray())
+
+            if np.can_cast(float, dtype, casting='same_kind'):
+                a = datsp.copy()
+                a /= 17.3
+                b = dat.copy()
+                b /= 17.3
+                assert_array_equal(b, a.toarray())
+
+        for dtype in self.math_dtypes:
+            # /= should only be used with float dtypes to avoid implicit
+            # casting.
+            if not np.can_cast(dtype, np.dtype(int)):
+                check(dtype)
+
+    def test_inplace_success(self):
+        # Inplace ops should work even if a specialized version is not
+        # implemented, falling back to x = x  y
+        a = self.spcreator(np.eye(5))
+        b = self.spcreator(np.eye(5))
+        bp = self.spcreator(np.eye(5))
+
+        b += a
+        bp = bp + a
+        assert_allclose(b.toarray(), bp.toarray())
+
+        if self.is_array_test:
+            b *= a
+            bp = bp * a
+            assert_allclose(b.toarray(), bp.toarray())
+
+        b @= a
+        bp = bp @ a
+        assert_allclose(b.toarray(), bp.toarray())
+
+        b -= a
+        bp = bp - a
+        assert_allclose(b.toarray(), bp.toarray())
+
+        with assert_raises(TypeError, match="unsupported operand"):
+            a //= b
+
+
+class _TestGetSet:
+    def test_getelement(self):
+        def check(dtype):
+            D = array([[1,0,0],
+                       [4,3,0],
+                       [0,2,0],
+                       [0,0,0]], dtype=dtype)
+            A = self.spcreator(D)
+
+            M,N = D.shape
+
+            for i in range(-M, M):
+                for j in range(-N, N):
+                    assert_equal(A[i,j], D[i,j])
+
+            assert_equal(type(A[1,1]), dtype)
+
+            for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1), (1, 2, 3)]:
+                assert_raises((IndexError, TypeError), A.__getitem__, ij)
+
+        for dtype in supported_dtypes:
+            check(np.dtype(dtype))
+
+    def test_setelement(self):
+        def check(dtype):
+            A = self.spcreator((3,4), dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[0, 0] = dtype.type(0)  # bug 870
+                A[1, 2] = dtype.type(4.0)
+                A[0, 1] = dtype.type(3)
+                A[2, 0] = dtype.type(2.0)
+                A[0,-1] = dtype.type(8)
+                A[-1,-2] = dtype.type(7)
+                A[0, 1] = dtype.type(5)
+
+            if dtype != np.bool_:
+                assert_array_equal(
+                    A.toarray(),
+                    [
+                        [0, 5, 0, 8],
+                        [0, 0, 4, 0],
+                        [2, 0, 7, 0]
+                    ]
+                )
+
+            for ij in [(0,4),(-1,4),(3,0),(3,4),(3,-1)]:
+                assert_raises(IndexError, A.__setitem__, ij, 123.0)
+
+            for v in [[1,2,3], array([1,2,3])]:
+                assert_raises(ValueError, A.__setitem__, (0,0), v)
+
+            if (not np.issubdtype(dtype, np.complexfloating) and
+                    dtype != np.bool_):
+                for v in [3j]:
+                    assert_raises(TypeError, A.__setitem__, (0,0), v)
+
+        for dtype in supported_dtypes:
+            check(np.dtype(dtype))
+
+    def test_negative_index_assignment(self):
+        # Regression test for GitHub issue 4428.
+
+        def check(dtype):
+            A = self.spcreator((3, 10), dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[0, -4] = 1
+            assert_equal(A[0, -4], 1)
+
+        for dtype in self.math_dtypes:
+            check(np.dtype(dtype))
+
+    def test_scalar_assign_2(self):
+        n, m = (5, 10)
+
+        def _test_set(i, j, nitems):
+            msg = f"{i!r} ; {j!r} ; {nitems!r}"
+            A = self.spcreator((n, m))
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[i, j] = 1
+            assert_almost_equal(A.sum(), nitems, err_msg=msg)
+            assert_almost_equal(A[i, j], 1, err_msg=msg)
+
+        # [i,j]
+        for i, j in [(2, 3), (-1, 8), (-1, -2), (array(-1), -2), (-1, array(-2)),
+                     (array(-1), array(-2))]:
+            _test_set(i, j, 1)
+
+    def test_index_scalar_assign(self):
+        A = self.spcreator((5, 5))
+        B = np.zeros((5, 5))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            for C in [A, B]:
+                C[0,1] = 1
+                C[3,0] = 4
+                C[3,0] = 9
+        assert_array_equal(A.toarray(), B)
+
+
+@pytest.mark.thread_unsafe
+class _TestSolve:
+    def test_solve(self):
+        # Test whether the lu_solve command segfaults, as reported by Nils
+        # Wagner for a 64-bit machine, 02 March 2005 (EJS)
+        n = 20
+        np.random.seed(0)  # make tests repeatable
+        A = zeros((n,n), dtype=complex)
+        x = np.random.rand(n)
+        y = np.random.rand(n-1)+1j*np.random.rand(n-1)
+        r = np.random.rand(n)
+        for i in range(len(x)):
+            A[i,i] = x[i]
+        for i in range(len(y)):
+            A[i,i+1] = y[i]
+            A[i+1,i] = conjugate(y[i])
+        A = self.spcreator(A)
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning,
+                       "splu converted its input to CSC format")
+            x = splu(A).solve(r)
+        assert_almost_equal(A @ x,r)
+
+
+class _TestSlicing:
+    def test_dtype_preservation(self):
+        assert_equal(self.spcreator((1,10), dtype=np.int16)[0,1:5].dtype, np.int16)
+        assert_equal(self.spcreator((1,10), dtype=np.int32)[0,1:5].dtype, np.int32)
+        assert_equal(self.spcreator((1,10), dtype=np.float32)[0,1:5].dtype, np.float32)
+        assert_equal(self.spcreator((1,10), dtype=np.float64)[0,1:5].dtype, np.float64)
+
+    def test_dtype_preservation_empty_slice(self):
+        # This should be parametrized with pytest, but something in the parent
+        # class creation used in this file breaks pytest.mark.parametrize.
+        for dt in [np.int16, np.int32, np.float32, np.float64]:
+            A = self.spcreator((3, 2), dtype=dt)
+            assert_equal(A[:, 0:0:2].dtype, dt)
+            assert_equal(A[0:0:2, :].dtype, dt)
+            assert_equal(A[0, 0:0:2].dtype, dt)
+            assert_equal(A[0:0:2, 0].dtype, dt)
+
+    def test_get_horiz_slice(self):
+        B = self.asdense(arange(50.).reshape(5,10))
+        A = self.spcreator(B)
+        r0, r1, r2 = (0, 1, 2) if self.is_array_test else ([0], [1], [2])
+        assert_array_equal(B[r1, :], A[1, :].toarray())
+        assert_array_equal(B[r1, 2:5], A[1, 2:5].toarray())
+
+        C = self.asdense([[1, 2, 1], [4, 0, 6], [0, 0, 0], [0, 0, 1]])
+        D = self.spcreator(C)
+        assert_array_equal(C[r1, 1:3], D[1, 1:3].toarray())
+
+        # Now test slicing when a row contains only zeros
+        E = self.asdense([[1, 2, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
+        F = self.spcreator(E)
+        assert_array_equal(E[r1, 1:3], F[1, 1:3].toarray())
+        assert_array_equal(E[r2, -2:], F[2, -2:].toarray())
+
+        # The following should raise exceptions:
+        assert_raises(IndexError, A.__getitem__, (slice(None), 11))
+        assert_raises(IndexError, A.__getitem__, (6, slice(3, 7)))
+
+    def test_get_vert_slice(self):
+        B = arange(50.).reshape(5, 10)
+        A = self.spcreator(B)
+        c0, c1, c2 = (0, 1, 2) if self.is_array_test else ([0], [1], [2])
+        assert_array_equal(B[2:5, c0], A[2:5, 0].toarray())
+        assert_array_equal(B[:, c1], A[:, 1].toarray())
+
+        C = array([[1, 2, 1], [4, 0, 6], [0, 0, 0], [0, 0, 1]])
+        D = self.spcreator(C)
+        assert_array_equal(C[1:3, c1], D[1:3, 1].toarray())
+        assert_array_equal(C[:, c2], D[:, 2].toarray())
+
+        # Now test slicing when a column contains only zeros
+        E = array([[1, 0, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
+        F = self.spcreator(E)
+        assert_array_equal(E[:, c1], F[:, 1].toarray())
+        assert_array_equal(E[-2:, c2], F[-2:, 2].toarray())
+
+        # The following should raise exceptions:
+        assert_raises(IndexError, A.__getitem__, (slice(None), 11))
+        assert_raises(IndexError, A.__getitem__, (6, slice(3, 7)))
+
+    def test_get_slices(self):
+        B = arange(50.).reshape(5, 10)
+        A = self.spcreator(B)
+        assert_array_equal(A[2:5, 0:3].toarray(), B[2:5, 0:3])
+        assert_array_equal(A[1:, :-1].toarray(), B[1:, :-1])
+        assert_array_equal(A[:-1, 1:].toarray(), B[:-1, 1:])
+
+        # Now test slicing when a column contains only zeros
+        E = array([[1, 0, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
+        F = self.spcreator(E)
+        assert_array_equal(E[1:2, 1:2], F[1:2, 1:2].toarray())
+        assert_array_equal(E[:, 1:], F[:, 1:].toarray())
+
+    def test_non_unit_stride_2d_indexing(self):
+        # Regression test -- used to silently ignore the stride.
+        v0 = np.random.rand(50, 50)
+        try:
+            v = self.spcreator(v0)[0:25:2, 2:30:3]
+        except ValueError:
+            # if unsupported
+            raise pytest.skip("feature not implemented")
+
+        assert_array_equal(v.toarray(), v0[0:25:2, 2:30:3])
+
+    def test_slicing_2(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        # [i,j]
+        assert_equal(A[2,3], B[2,3])
+        assert_equal(A[-1,8], B[-1,8])
+        assert_equal(A[-1,-2],B[-1,-2])
+        assert_equal(A[array(-1),-2],B[-1,-2])
+        assert_equal(A[-1,array(-2)],B[-1,-2])
+        assert_equal(A[array(-1),array(-2)],B[-1,-2])
+
+        # [i,1:2]
+        assert_equal(A[2, :].toarray(), B[2, :])
+        assert_equal(A[2, 5:-2].toarray(), B[2, 5:-2])
+        assert_equal(A[array(2), 5:-2].toarray(), B[2, 5:-2])
+
+        # [1:2,j]
+        assert_equal(A[:, 2].toarray(), B[:, 2])
+        assert_equal(A[3:4, 9].toarray(), B[3:4, 9])
+        assert_equal(A[1:4, -5].toarray(), B[1:4, -5])
+        assert_equal(A[2:-1, 3].toarray(), B[2:-1, 3])
+        assert_equal(A[2:-1, array(3)].toarray(), B[2:-1, 3])
+
+        # [1:2,1:2]
+        assert_equal(A[1:2, 1:2].toarray(), B[1:2, 1:2])
+        assert_equal(A[4:, 3:].toarray(), B[4:, 3:])
+        assert_equal(A[:4, :5].toarray(), B[:4, :5])
+        assert_equal(A[2:-1, :5].toarray(), B[2:-1, :5])
+
+        # [i]
+        assert_equal(A[1, :].toarray(), B[1, :])
+        assert_equal(A[-2, :].toarray(), B[-2, :])
+        assert_equal(A[array(-2), :].toarray(), B[-2, :])
+
+        # [1:2]
+        assert_equal(A[1:4].toarray(), B[1:4])
+        assert_equal(A[1:-2].toarray(), B[1:-2])
+
+        # Check bug reported by Robert Cimrman:
+        # http://thread.gmane.org/gmane.comp.python.scientific.devel/7986 (dead link)
+        s = slice(int8(2),int8(4),None)
+        assert_equal(A[s, :].toarray(), B[2:4, :])
+        assert_equal(A[:, s].toarray(), B[:, 2:4])
+
+    @pytest.mark.fail_slow(2)
+    def test_slicing_3(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        s_ = np.s_
+        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
+                  s_[15:20], s_[3:2],
+                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
+                  0, 1, s_[:], s_[1:5], -1, -2, -5,
+                  array(-1), np.int8(-3)]
+
+        def check_1(a):
+            x = A[a]
+            y = B[a]
+            if y.shape == ():
+                assert_equal(x, y, repr(a))
+            else:
+                if x.size == 0 and y.size == 0:
+                    pass
+                else:
+                    assert_array_equal(x.toarray(), y, repr(a))
+
+        for j, a in enumerate(slices):
+            check_1(a)
+
+        def check_2(a, b):
+            # Indexing np.matrix with 0-d arrays seems to be broken,
+            # as they seem not to be treated as scalars.
+            # https://github.com/numpy/numpy/issues/3110
+            if isinstance(a, np.ndarray):
+                ai = int(a)
+            else:
+                ai = a
+            if isinstance(b, np.ndarray):
+                bi = int(b)
+            else:
+                bi = b
+
+            x = A[a, b]
+            y = B[ai, bi]
+
+            if y.shape == ():
+                assert_equal(x, y, repr((a, b)))
+            else:
+                if x.size == 0 and y.size == 0:
+                    pass
+                else:
+                    assert_array_equal(x.toarray(), y, repr((a, b)))
+
+        for i, a in enumerate(slices):
+            for j, b in enumerate(slices):
+                check_2(a, b)
+
+        # Check out of bounds etc. systematically
+        extra_slices = []
+        for a, b, c in itertools.product(*([(None, 0, 1, 2, 5, 15,
+                                             -1, -2, 5, -15)]*3)):
+            if c == 0:
+                continue
+            extra_slices.append(slice(a, b, c))
+
+        for a in extra_slices:
+            check_2(a, a)
+            check_2(a, -2)
+            check_2(-2, a)
+
+    def test_None_slicing(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        assert A[1, 2].ndim == 0
+        assert A[None, 1, 2:4].shape == (1, 2)
+        assert A[None, 1, 2, None].shape == (1, 1)
+
+        # see gh-22458
+        assert A[None, 1].shape == (1, 10)
+        assert A[1, None].shape == (1, 10)
+        assert A[None, 1, :].shape == (1, 10)
+        assert A[1, None, :].shape == (1, 10)
+        assert A[1, :, None].shape == (10, 1)
+
+        assert A[None, 1:3, 2].shape == B[None, 1:3, 2].shape == (1, 2)
+        assert A[1:3, None, 2].shape == B[1:3, None, 2].shape == (2, 1)
+        assert A[1:3, 2, None].shape == B[1:3, 2, None].shape == (2, 1)
+        assert A[None, 1, 2:4].shape == B[None, 1, 2:4].shape == (1, 2)
+        assert A[1, None, 2:4].shape == B[1, None, 2:4].shape == (1, 2)
+        assert A[1, 2:4, None].shape == B[1, 2:4, None].shape == (2, 1)
+
+        # different for spmatrix
+        if self.is_array_test:
+            assert A[1:3, 2].shape == B[1:3, 2].shape == (2,)
+            assert A[1, 2:4].shape == B[1, 2:4].shape == (2,)
+            assert A[None, 1, 2].shape == B[None, 1, 2].shape == (1,)
+            assert A[1, None, 2].shape == B[1, None, 2].shape == (1,)
+            assert A[1, 2, None].shape == B[1, 2, None].shape == (1,)
+        else:
+            assert A[1, 2:4].shape == B[1, 2:4].shape == (1, 2)
+            assert A[1:3, 2].shape == B[1:3, 2].shape == (2, 1)
+            assert A[None, 1, 2].shape == B[None, 1, 2].shape == (1, 1)
+            assert A[1, None, 2].shape == B[1, None, 2].shape == (1, 1)
+            assert A[1, 2, None].shape == B[1, 2, None].shape == (1, 1)
+
+    def test_ellipsis_slicing(self):
+        b = self.asdense(arange(50).reshape(5,10))
+        a = self.spcreator(b)
+
+        assert_array_equal(a[...].toarray(), b[...])
+        assert_array_equal(a[...,].toarray(), b[...,])
+
+        assert_array_equal(a[4, ...].toarray(), b[4, ...])
+        assert_array_equal(a[..., 4].toarray(), b[..., 4])
+        assert_array_equal(a[..., 5].toarray(), b[..., 5])
+        with pytest.raises(IndexError, match='index .5. out of range'):
+            a[5, ...]
+        with pytest.raises(IndexError, match='index .10. out of range'):
+            a[..., 10]
+        with pytest.raises(IndexError, match='index .5. out of range'):
+            a.T[..., 5]
+
+        assert_array_equal(a[1:, ...].toarray(), b[1:, ...])
+        assert_array_equal(a[..., 1:].toarray(), b[..., 1:])
+        assert_array_equal(a[:2, ...].toarray(), b[:2, ...])
+        assert_array_equal(a[..., :2].toarray(), b[..., :2])
+
+        # check slice limit outside range
+        assert_array_equal(a[:5, ...].toarray(), b[:5, ...])
+        assert_array_equal(a[..., :5].toarray(), b[..., :5])
+        assert_array_equal(a[5:, ...].toarray(), b[5:, ...])
+        assert_array_equal(a[..., 5:].toarray(), b[..., 5:])
+        assert_array_equal(a[10:, ...].toarray(), b[10:, ...])
+        assert_array_equal(a[..., 10:].toarray(), b[..., 10:])
+
+        # ellipsis should be ignored
+        assert_array_equal(a[1:, 1, ...].toarray(), b[1:, 1, ...])
+        assert_array_equal(a[1, ..., 1:].toarray(), b[1, ..., 1:])
+        assert_array_equal(a[..., 1, 1:].toarray(), b[1, ..., 1:])
+        assert_array_equal(a[:2, 1, ...].toarray(), b[:2, 1, ...])
+        assert_array_equal(a[1, ..., :2].toarray(), b[1, ..., :2])
+        assert_array_equal(a[..., 1, :2].toarray(), b[1, ..., :2])
+        # These return ints
+        assert_equal(a[1, 1, ...], b[1, 1, ...])
+        assert_equal(a[1, ..., 1], b[1, ..., 1])
+
+    def test_ellipsis_fancy_bool(self):
+        numpy_a = self.asdense(arange(50).reshape(5, 10))
+        a = self.spcreator(numpy_a)
+
+        ix5 = [True, False, True, False, True]
+        ix10 = [False] * 5 + ix5  # same number of True values as ix5
+        ix10_6True = ix5 + ix5  # not same number of True values as ix5
+        full_ix = [ix10] * 5
+
+        assert_array_equal(toarray(a[full_ix, ...]), numpy_a[full_ix, ...])
+        assert_array_equal(toarray(a[..., full_ix]), numpy_a[..., full_ix])
+
+        assert_array_equal(toarray(a[ix5, ...]), numpy_a[ix5, ...])
+        assert_array_equal(toarray(a[..., ix10]), numpy_a[..., ix10])
+
+        assert_array_equal(toarray(a[ix5, ..., ix10]), numpy_a[ix5, ..., ix10])
+        assert_array_equal(toarray(a[..., ix5, ix10]), numpy_a[..., ix5, ix10])
+        assert_array_equal(toarray(a[ix5, ix10, ...]), numpy_a[ix5, ix10, ...])
+
+        with assert_raises(ValueError, match="shape mismatch"):
+            a[ix5, ix10_6True]
+
+    def test_ellipsis_fancy_slicing(self):
+        b = self.asdense(arange(50).reshape(5, 10))
+        a = self.spcreator(b)
+
+        assert_array_equal(a[[4], ...].toarray(), b[[4], ...])
+        assert_array_equal(a[[2, 4], ...].toarray(), b[[2, 4], ...])
+        assert_array_equal(a[..., [4]].toarray(), b[..., [4]])
+        assert_array_equal(a[..., [2, 4]].toarray(), b[..., [2, 4]])
+
+        assert_array_equal(a[[4], 1, ...].toarray(), b[[4], 1, ...])
+        assert_array_equal(a[[2, 4], 1, ...].toarray(), b[[2, 4], 1, ...])
+        assert_array_equal(a[[4], ..., 1].toarray(), b[[4], ..., 1])
+        assert_array_equal(a[..., [4], 1].toarray(), b[..., [4], 1])
+        # fancy index gives dense
+        assert_array_equal(toarray(a[[2, 4], ..., [2, 4]]), b[[2, 4], ..., [2, 4]])
+        assert_array_equal(toarray(a[..., [2, 4], [2, 4]]), b[..., [2, 4], [2, 4]])
+
+    def test_multiple_ellipsis_slicing(self):
+        a = self.spcreator(arange(6).reshape(3, 2))
+
+        with pytest.raises(IndexError,
+                           match='an index can only have a single ellipsis'):
+            a[..., ...]
+        with pytest.raises(IndexError,
+                           match='an index can only have a single ellipsis'):
+            a[..., 1, ...]
+
+
+class _TestSlicingAssign:
+    def test_slice_scalar_assign(self):
+        A = self.spcreator((5, 5))
+        B = np.zeros((5, 5))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            for C in [A, B]:
+                C[0:1,1] = 1
+                C[3:0,0] = 4
+                C[3:4,0] = 9
+                C[0,4:] = 1
+                C[3::-1,4:] = 9
+        assert_array_equal(A.toarray(), B)
+
+    def test_slice_assign_2(self):
+        n, m = (5, 10)
+
+        def _test_set(i, j):
+            msg = f"i={i!r}; j={j!r}"
+            A = self.spcreator((n, m))
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[i, j] = 1
+            B = np.zeros((n, m))
+            B[i, j] = 1
+            assert_array_almost_equal(A.toarray(), B, err_msg=msg)
+        # [i,1:2]
+        for i, j in [(2, slice(3)), (2, slice(None, 10, 4)), (2, slice(5, -2)),
+                     (array(2), slice(5, -2))]:
+            _test_set(i, j)
+
+    def test_self_self_assignment(self):
+        # Tests whether a row of one sparse array can be assigned to another.
+        B = self.spcreator((4,3))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            B[0,0] = 2
+            B[1,2] = 7
+            B[2,1] = 3
+            B[3,0] = 10
+
+            A = B / 10
+            B[0,:] = A[0,:]
+            assert_array_equal(A[0,:].toarray(), B[0,:].toarray())
+
+            A = B / 10
+            B[:,:] = A[:1,:1]
+            assert_array_equal(np.zeros((4,3)) + A[0,0], B.toarray())
+
+            A = B / 10
+            B[:-1,0] = A[None,0,:].T
+            assert_array_equal(A[0,:].toarray().T, B[:-1,0].toarray())
+
+    def test_slice_assignment(self):
+        B = self.spcreator((4,3))
+        expected = array([[10,0,0],
+                          [0,0,6],
+                          [0,14,0],
+                          [0,0,0]])
+        block = [[1,0],[0,4]]
+
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            B[0,0] = 5
+            B[1,2] = 3
+            B[2,1] = 7
+            B[:,:] = B+B
+            assert_array_equal(B.toarray(), expected)
+
+            B[:2,:2] = self.csc_container(array(block))
+            assert_array_equal(B.toarray()[:2, :2], block)
+
+    def test_sparsity_modifying_assignment(self):
+        B = self.spcreator((4,3))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            B[0,0] = 5
+            B[1,2] = 3
+            B[2,1] = 7
+            B[3,0] = 10
+            B[:3] = self.csr_container(np.eye(3))
+
+        expected = array([[1,0,0],[0,1,0],[0,0,1],[10,0,0]])
+        assert_array_equal(B.toarray(), expected)
+
+    def test_set_slice(self):
+        A = self.spcreator((5,10))
+        B = array(zeros((5, 10), float))
+        s_ = np.s_
+        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
+                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
+                  0, 1, s_[:], s_[1:5], -1, -2, -5,
+                  array(-1), np.int8(-3)]
+
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            for j, a in enumerate(slices):
+                A[a] = j
+                B[a] = j
+                assert_array_equal(A.toarray(), B, repr(a))
+
+            for i, a in enumerate(slices):
+                for j, b in enumerate(slices):
+                    A[a,b] = 10*i + 1000*(j+1)
+                    B[a,b] = 10*i + 1000*(j+1)
+                    assert_array_equal(A.toarray(), B, repr((a, b)))
+
+            A[0, 1:10:2] = range(1, 10, 2)
+            B[0, 1:10:2] = range(1, 10, 2)
+            assert_array_equal(A.toarray(), B)
+            A[1:5:2, 0] = np.arange(1, 5, 2)[:, None]
+            B[1:5:2, 0] = np.arange(1, 5, 2)[:]
+            assert_array_equal(A.toarray(), B)
+
+        # The next commands should raise exceptions
+        assert_raises(ValueError, A.__setitem__, (0, 0), list(range(100)))
+        assert_raises(ValueError, A.__setitem__, (0, 0), arange(100))
+        assert_raises(ValueError, A.__setitem__, (0, slice(None)),
+                      list(range(100)))
+        assert_raises(ValueError, A.__setitem__, (slice(None), 1),
+                      list(range(100)))
+        assert_raises(ValueError, A.__setitem__, (slice(None), 1), A.copy())
+        assert_raises(ValueError, A.__setitem__,
+                      ([[1, 2, 3], [0, 3, 4]], [1, 2, 3]), [1, 2, 3, 4])
+        assert_raises(ValueError, A.__setitem__,
+                      ([[1, 2, 3], [0, 3, 4], [4, 1, 3]],
+                       [[1, 2, 4], [0, 1, 3]]), [2, 3, 4])
+        assert_raises(ValueError, A.__setitem__, (slice(4), 0),
+                      [[1, 2], [3, 4]])
+
+    def test_assign_empty(self):
+        A = self.spcreator(np.ones((2, 3)))
+        B = self.spcreator((1, 2))
+        A[1, :2] = B
+        assert_array_equal(A.toarray(), [[1, 1, 1], [0, 0, 1]])
+
+    def test_assign_1d_slice(self):
+        A = self.spcreator(np.ones((3, 3)))
+        x = np.zeros(3)
+        A[:, 0] = x
+        A[1, :] = x
+        assert_array_equal(A.toarray(), [[0, 1, 1], [0, 0, 0], [0, 1, 1]])
+
+
+class _TestFancyIndexing:
+    """Tests fancy indexing features.  The tests for any matrix formats
+    that implement these features should derive from this class.
+    """
+
+    def test_dtype_preservation_empty_index(self):
+        # This should be parametrized with pytest, but something in the parent
+        # class creation used in this file breaks pytest.mark.parametrize.
+        for dt in [np.int16, np.int32, np.float32, np.float64]:
+            A = self.spcreator((3, 2), dtype=dt)
+            assert_equal(A[:, [False, False]].dtype, dt)
+            assert_equal(A[[False, False, False], :].dtype, dt)
+            assert_equal(A[:, []].dtype, dt)
+            assert_equal(A[[], :].dtype, dt)
+
+    def test_bad_index(self):
+        A = self.spcreator(np.zeros([5, 5]))
+        assert_raises((IndexError, ValueError, TypeError), A.__getitem__, "foo")
+        assert_raises((IndexError, ValueError, TypeError), A.__getitem__, (2, "foo"))
+        assert_raises((IndexError, ValueError), A.__getitem__,
+                      ([1, 2, 3], [1, 2, 3, 4]))
+
+    def test_fancy_indexing(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        # [i]
+        assert_equal(A[[3]].toarray(), B[[3]])
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+
+        # [i,[1,2]]
+        assert_equal(A[3, [3]].toarray(), B[3, [3]])
+        assert_equal(A[3, [1, 3]].toarray(), B[3, [1, 3]])
+        assert_equal(A[-1, [2, -5]].toarray(), B[-1, [2, -5]])
+        assert_equal(A[array(-1), [2, -5]].toarray(), B[-1, [2, -5]])
+        assert_equal(A[-1, array([2, -5])].toarray(), B[-1, [2, -5]])
+        assert_equal(A[array(-1), array([2, -5])].toarray(), B[-1, [2, -5]])
+
+        # [1:2,[1,2]]
+        assert_equal(A[:, [2, 8, 3, -1]].toarray(), B[:, [2, 8, 3, -1]])
+        assert_equal(A[3:4, [9]].toarray(), B[3:4, [9]])
+        assert_equal(A[1:4, [-1, -5]].toarray(), B[1:4, [-1, -5]])
+        assert_equal(A[1:4, array([-1, -5])].toarray(), B[1:4, [-1, -5]])
+
+        # [[1,2],j]
+        assert_equal(A[[3], 3].toarray(), B[[3], 3])
+        assert_equal(A[[1, 3], 3].toarray(), B[[1, 3], 3])
+        assert_equal(A[[2, -5], -4].toarray(), B[[2, -5], -4])
+        assert_equal(A[array([2, -5]), -4].toarray(), B[[2, -5], -4])
+        assert_equal(A[[2, -5], array(-4)].toarray(), B[[2, -5], -4])
+        assert_equal(A[array([2, -5]), array(-4)].toarray(), B[[2, -5], -4])
+
+        # [[1,2],1:2]
+        assert_equal(A[[3], :].toarray(), B[[3], :])
+        assert_equal(A[[1, 3], :].toarray(), B[[1, 3], :])
+        assert_equal(A[[2, -5], 8:-1].toarray(), B[[2, -5], 8:-1])
+        assert_equal(A[array([2, -5]), 8:-1].toarray(), B[[2, -5], 8:-1])
+
+        # [[1,2],[1,2]]
+        assert_equal(toarray(A[[3], [4]]), B[[3], [4]])
+        assert_equal(toarray(A[[1, 3], [2, 4]]), B[[1, 3], [2, 4]])
+        assert_equal(toarray(A[[-1, -3], [2, -4]]), B[[-1, -3], [2, -4]])
+        assert_equal(
+            toarray(A[array([-1, -3]), [2, -4]]), B[[-1, -3], [2, -4]]
+        )
+        assert_equal(
+            toarray(A[[-1, -3], array([2, -4])]), B[[-1, -3], [2, -4]]
+        )
+        assert_equal(
+            toarray(A[array([-1, -3]), array([2, -4])]), B[[-1, -3], [2, -4]]
+        )
+
+        # [[[1],[2]],[1,2]]
+        assert_equal(A[[[1], [3]], [2, 4]].toarray(), B[[[1], [3]], [2, 4]])
+        assert_equal(
+            A[[[-1], [-3], [-2]], [2, -4]].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[array([[-1], [-3], [-2]]), [2, -4]].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[[[-1], [-3], [-2]], array([2, -4])].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[array([[-1], [-3], [-2]]), array([2, -4])].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+
+        # [[1,2]]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+        assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
+        assert_equal(A[array([-1, -3])].toarray(), B[[-1, -3]])
+
+        # [[1,2],:][:,[1,2]]
+        assert_equal(A[[3], :][:, [4]].toarray(), B[[3], :][:, [4]])
+        assert_equal(
+            A[[1, 3], :][:, [2, 4]].toarray(), B[[1, 3], :][:, [2, 4]]
+        )
+        assert_equal(
+            A[[-1, -3], :][:, [2, -4]].toarray(), B[[-1, -3], :][:, [2, -4]]
+        )
+        assert_equal(
+            A[array([-1, -3]), :][:, array([2, -4])].toarray(),
+            B[[-1, -3], :][:, [2, -4]]
+        )
+
+        # [1,[[1,2]]][[[1,2]],1]
+        assert_equal(
+            A[1, [[1, 3]]][[[0, 0]], 1].toarray(), B[1, [[1, 3]]][[[0, 0]], 1]
+        )
+        assert_equal(
+            A[1, [[-1, -3]]][[[0, -1]], 1].toarray(), B[1, [[-1, -3]]][[[0, -1]], 1]
+        )
+        # [:1,[[1,2]]][[[1,2]],:1]
+        with pytest.raises(IndexError, match="Only 1D or 2D arrays allowed"):
+            A[:1, [[1, 3]]]
+        with pytest.raises(IndexError, match="Only 1D or 2D arrays allowed"):
+            A[[[0, 0]], :1]
+
+        # [:,[1,2]][[1,2],:]
+        assert_equal(
+            A[:, [1, 3]][[2, 4], :].toarray(), B[:, [1, 3]][[2, 4], :]
+        )
+        assert_equal(
+            A[:, [-1, -3]][[2, -4], :].toarray(), B[:, [-1, -3]][[2, -4], :]
+        )
+        assert_equal(
+            A[:, array([-1, -3])][array([2, -4]), :].toarray(),
+            B[:, [-1, -3]][[2, -4], :]
+        )
+
+        # Check bug reported by Robert Cimrman:
+        # http://thread.gmane.org/gmane.comp.python.scientific.devel/7986 (dead link)
+        s = slice(int8(2),int8(4),None)
+        assert_equal(A[s, :].toarray(), B[2:4, :])
+        assert_equal(A[:, s].toarray(), B[:, 2:4])
+
+        # Regression for gh-4917: index with tuple of 2D arrays
+        i = np.array([[1]], dtype=int)
+        assert_equal(A[i, i].toarray(), B[i, i])
+
+        # Regression for gh-4917: index with tuple of empty nested lists
+        assert_equal(A[[[]], [[]]].toarray(), B[[[]], [[]]])
+
+    def test_fancy_indexing_randomized(self):
+        np.random.seed(1234)  # make runs repeatable
+
+        NUM_SAMPLES = 50
+        M = 6
+        N = 4
+
+        D = self.asdense(np.random.rand(M,N))
+        D = np.multiply(D, D > 0.5)
+
+        I = np.random.randint(-M + 1, M, size=NUM_SAMPLES)
+        J = np.random.randint(-N + 1, N, size=NUM_SAMPLES)
+
+        S = self.spcreator(D)
+
+        SIJ = S[I,J]
+        if issparse(SIJ):
+            SIJ = SIJ.toarray()
+        assert_equal(SIJ, D[I,J])
+
+        I_bad = I + M
+        J_bad = J - N
+
+        assert_raises(IndexError, S.__getitem__, (I_bad,J))
+        assert_raises(IndexError, S.__getitem__, (I,J_bad))
+
+    def test_missized_masking(self):
+        M, N = 5, 10
+
+        B = self.asdense(arange(M * N).reshape(M, N))
+        A = self.spcreator(B)
+
+        # Content of mask shouldn't matter, only its size
+        row_long = np.ones(M + 1, dtype=bool)
+        row_short = np.ones(M - 1, dtype=bool)
+        col_long = np.ones(N + 2, dtype=bool)
+        col_short = np.ones(N - 2, dtype=bool)
+
+        match="bool index .* has shape .* instead of .*"
+        for i, j in itertools.product(
+            (row_long, row_short, slice(None)),
+            (col_long, col_short, slice(None)),
+        ):
+            if isinstance(i, slice) and isinstance(j, slice):
+                continue
+            with pytest.raises(IndexError, match=match):
+                _ = A[i, j]
+
+    def test_fancy_indexing_boolean(self):
+        np.random.seed(1234)  # make runs repeatable
+
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        I = np.array(np.random.randint(0, 2, size=5), dtype=bool)
+        J = np.array(np.random.randint(0, 2, size=10), dtype=bool)
+        X = np.array(np.random.randint(0, 2, size=(5, 10)), dtype=bool)
+
+        assert_equal(toarray(A[I]), B[I])
+        assert_equal(toarray(A[:, J]), B[:, J])
+        assert_equal(toarray(A[X]), B[X])
+        assert_equal(toarray(A[B > 9]), B[B > 9])
+
+        I = np.array([True, False, True, True, False])
+        J = np.array([False, True, True, False, True,
+                      False, False, False, False, False])
+
+        assert_equal(toarray(A[I, J]), B[I, J])
+
+        Z1 = np.zeros((6, 11), dtype=bool)
+        Z2 = np.zeros((6, 11), dtype=bool)
+        Z2[0,-1] = True
+        Z3 = np.zeros((6, 11), dtype=bool)
+        Z3[-1,0] = True
+
+        assert_raises(IndexError, A.__getitem__, Z1)
+        assert_raises(IndexError, A.__getitem__, Z2)
+        assert_raises(IndexError, A.__getitem__, Z3)
+        assert_raises((IndexError, ValueError), A.__getitem__, (X, 1))
+
+    def test_fancy_indexing_sparse_boolean(self):
+        np.random.seed(1234)  # make runs repeatable
+
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        X = np.array(np.random.randint(0, 2, size=(5, 10)), dtype=bool)
+
+        Xsp = self.csr_container(X)
+
+        assert_equal(toarray(A[Xsp]), B[X])
+        assert_equal(toarray(A[A > 9]), B[B > 9])
+
+        Z = np.array(np.random.randint(0, 2, size=(5, 11)), dtype=bool)
+        Y = np.array(np.random.randint(0, 2, size=(6, 10)), dtype=bool)
+
+        Zsp = self.csr_container(Z)
+        Ysp = self.csr_container(Y)
+
+        assert_raises(IndexError, A.__getitem__, Zsp)
+        assert_raises(IndexError, A.__getitem__, Ysp)
+        assert_raises((IndexError, ValueError), A.__getitem__, (Xsp, 1))
+
+    def test_fancy_indexing_regression_3087(self):
+        mat = self.spcreator(array([[1, 0, 0], [0,1,0], [1,0,0]]))
+        desired_cols = np.ravel(mat.sum(0)) > 0
+        assert_equal(mat[:, desired_cols].toarray(), [[1, 0], [0, 1], [1, 0]])
+
+    def test_fancy_indexing_seq_assign(self):
+        mat = self.spcreator(array([[1, 0], [0, 1]]))
+        assert_raises(ValueError, mat.__setitem__, (0, 0), np.array([1,2]))
+
+    def test_fancy_indexing_2d_assign(self):
+        # regression test for gh-10695
+        mat = self.spcreator(array([[1, 0], [2, 3]]))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            mat[[0, 1], [1, 1]] = mat[[1, 0], [0, 0]]
+        assert_equal(toarray(mat), array([[1, 2], [2, 1]]))
+
+    def test_fancy_indexing_empty(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        B[1,:] = 0
+        B[:,2] = 0
+        B[3,6] = 0
+        A = self.spcreator(B)
+
+        K = np.array([False, False, False, False, False])
+        assert_equal(toarray(A[K]), B[K])
+        K = np.array([], dtype=int)
+        assert_equal(toarray(A[K]), B[K])
+        assert_equal(toarray(A[K, K]), B[K, K])
+        J = np.array([0, 1, 2, 3, 4], dtype=int)[:,None]
+        assert_equal(toarray(A[K, J]), B[K, J])
+        assert_equal(toarray(A[J, K]), B[J, K])
+
+
+@contextlib.contextmanager
+def check_remains_sorted(X):
+    """Checks that sorted indices property is retained through an operation
+    """
+    if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices:
+        yield
+        return
+    yield
+    indices = X.indices.copy()
+    X.has_sorted_indices = False
+    X.sort_indices()
+    assert_array_equal(indices, X.indices,
+                       'Expected sorted indices, found unsorted')
+
+
+class _TestFancyIndexingAssign:
+    def test_bad_index_assign(self):
+        A = self.spcreator(np.zeros([5, 5]))
+        assert_raises((IndexError, ValueError, TypeError), A.__setitem__, "foo", 2)
+        assert_raises((IndexError, ValueError, TypeError), A.__setitem__, (2, "foo"), 5)
+
+    def test_fancy_indexing_set(self):
+        n, m = (5, 10)
+
+        def _test_set_slice(i, j):
+            A = self.spcreator((n, m))
+            B = self.asdense(np.zeros((n, m)))
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                B[i, j] = 1
+                with check_remains_sorted(A):
+                    A[i, j] = 1
+            assert_array_almost_equal(A.toarray(), B)
+        # [1:2,1:2]
+        for i, j in [((2, 3, 4), slice(None, 10, 4)),
+                     (np.arange(3), slice(5, -2)),
+                     (slice(2, 5), slice(5, -2))]:
+            _test_set_slice(i, j)
+        for i, j in [(np.arange(3), np.arange(3)), ((0, 3, 4), (1, 2, 4))]:
+            _test_set_slice(i, j)
+
+    def test_fancy_assignment_dtypes(self):
+        def check(dtype):
+            A = self.spcreator((5, 5), dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[[0,1],[0,1]] = dtype.type(1)
+                assert_equal(A.sum(), dtype.type(1)*2)
+                A[0:2,0:2] = dtype.type(1.0)
+                assert_equal(A.sum(), dtype.type(1)*4)
+                A[2,2] = dtype.type(1.0)
+                assert_equal(A.sum(), dtype.type(1)*4 + dtype.type(1))
+
+        for dtype in supported_dtypes:
+            check(np.dtype(dtype))
+
+    def test_sequence_assignment(self):
+        A = self.spcreator((4,3))
+        B = self.spcreator(eye(3,4))
+
+        i0 = [0,1,2]
+        i1 = (0,1,2)
+        i2 = array(i0)
+
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            with check_remains_sorted(A):
+                A[0,i0] = B[i0,0].T
+                A[1,i1] = B[i1,1].T
+                A[2,i2] = B[i2,2].T
+            assert_array_equal(A.toarray(), B.T.toarray())
+
+            # column slice
+            A = self.spcreator((2,3))
+            with check_remains_sorted(A):
+                A[1,1:3] = [10,20]
+            assert_array_equal(A.toarray(), [[0, 0, 0], [0, 10, 20]])
+
+            # row slice
+            A = self.spcreator((3,2))
+            with check_remains_sorted(A):
+                A[1:3,1] = [[10],[20]]
+            assert_array_equal(A.toarray(), [[0, 0], [0, 10], [0, 20]])
+
+            # both slices
+            A = self.spcreator((3,3))
+            B = self.asdense(np.zeros((3,3)))
+            with check_remains_sorted(A):
+                for C in [A, B]:
+                    C[[0,1,2], [0,1,2]] = [4,5,6]
+            assert_array_equal(A.toarray(), B)
+
+            # both slices (2)
+            A = self.spcreator((4, 3))
+            with check_remains_sorted(A):
+                A[(1, 2, 3), (0, 1, 2)] = [1, 2, 3]
+            assert_almost_equal(A.sum(), 6)
+            B = self.asdense(np.zeros((4, 3)))
+            B[(1, 2, 3), (0, 1, 2)] = [1, 2, 3]
+            assert_array_equal(A.toarray(), B)
+
+    def test_fancy_assign_empty(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        B[1,:] = 0
+        B[:,2] = 0
+        B[3,6] = 0
+        A = self.spcreator(B)
+
+        K = np.array([False, False, False, False, False])
+        A[K] = 42
+        assert_equal(toarray(A), B)
+
+        K = np.array([], dtype=int)
+        A[K] = 42
+        assert_equal(toarray(A), B)
+        A[K,K] = 42
+        assert_equal(toarray(A), B)
+
+        J = np.array([0, 1, 2, 3, 4], dtype=int)[:,None]
+        A[K,J] = 42
+        assert_equal(toarray(A), B)
+        A[J,K] = 42
+        assert_equal(toarray(A), B)
+
+
+class _TestFancyMultidim:
+    def test_fancy_indexing_ndarray(self):
+        sets = [
+            (np.array([[1], [2], [3]]), np.array([3, 4, 2])),
+            (np.array([[1], [2], [3]]), np.array([[3, 4, 2]])),
+            (np.array([[1, 2, 3]]), np.array([[3], [4], [2]])),
+            (np.array([1, 2, 3]), np.array([[3], [4], [2]])),
+            (np.array([[1, 2, 3], [3, 4, 2]]),
+             np.array([[5, 6, 3], [2, 3, 1]]))
+            ]
+        # These inputs generate 3-D outputs
+        #    (np.array([[[1], [2], [3]], [[3], [4], [2]]]),
+        #     np.array([[[5], [6], [3]], [[2], [3], [1]]])),
+
+        for I, J in sets:
+            np.random.seed(1234)
+            D = self.asdense(np.random.rand(5, 7))
+            S = self.spcreator(D)
+
+            SIJ = S[I,J]
+            if issparse(SIJ):
+                SIJ = SIJ.toarray()
+            assert_equal(SIJ, D[I,J])
+
+            I_bad = I + 5
+            J_bad = J + 7
+
+            assert_raises(IndexError, S.__getitem__, (I_bad,J))
+            assert_raises(IndexError, S.__getitem__, (I,J_bad))
+
+            # This would generate 3-D arrays -- not supported
+            assert_raises(IndexError, S.__getitem__, ([I, I], slice(None)))
+            assert_raises(IndexError, S.__getitem__, (slice(None), [J, J]))
+
+
+class _TestFancyMultidimAssign:
+    def test_fancy_assign_ndarray(self):
+        np.random.seed(1234)
+
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+        X = np.random.rand(2, 3)
+
+        I = np.array([[1, 2, 3], [3, 4, 2]])
+        J = np.array([[5, 6, 3], [2, 3, 1]])
+
+        with check_remains_sorted(S):
+            S[I,J] = X
+        D[I,J] = X
+        assert_equal(S.toarray(), D)
+
+        I_bad = I + 5
+        J_bad = J + 7
+
+        C = [1, 2, 3]
+
+        with check_remains_sorted(S):
+            S[I,J] = C
+        D[I,J] = C
+        assert_equal(S.toarray(), D)
+
+        with check_remains_sorted(S):
+            S[I,J] = 3
+        D[I,J] = 3
+        assert_equal(S.toarray(), D)
+
+        assert_raises(IndexError, S.__setitem__, (I_bad,J), C)
+        assert_raises(IndexError, S.__setitem__, (I,J_bad), C)
+
+    def test_fancy_indexing_multidim_set(self):
+        n, m = (5, 10)
+
+        def _test_set_slice(i, j):
+            A = self.spcreator((n, m))
+            with check_remains_sorted(A), suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[i, j] = 1
+            B = self.asdense(np.zeros((n, m)))
+            B[i, j] = 1
+            assert_array_almost_equal(A.toarray(), B)
+        # [[[1, 2], [1, 2]], [1, 2]]
+        for i, j in [(np.array([[1, 2], [1, 3]]), [1, 3]),
+                        (np.array([0, 4]), [[0, 3], [1, 2]]),
+                        ([[1, 2, 3], [0, 2, 4]], [[0, 4, 3], [4, 1, 2]])]:
+            _test_set_slice(i, j)
+
+    def test_fancy_assign_list(self):
+        np.random.seed(1234)
+
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+        X = np.random.rand(2, 3)
+
+        I = [[1, 2, 3], [3, 4, 2]]
+        J = [[5, 6, 3], [2, 3, 1]]
+
+        S[I,J] = X
+        D[I,J] = X
+        assert_equal(S.toarray(), D)
+
+        I_bad = [[ii + 5 for ii in i] for i in I]
+        J_bad = [[jj + 7 for jj in j] for j in J]
+        C = [1, 2, 3]
+
+        S[I,J] = C
+        D[I,J] = C
+        assert_equal(S.toarray(), D)
+
+        S[I,J] = 3
+        D[I,J] = 3
+        assert_equal(S.toarray(), D)
+
+        assert_raises(IndexError, S.__setitem__, (I_bad,J), C)
+        assert_raises(IndexError, S.__setitem__, (I,J_bad), C)
+
+    def test_fancy_assign_slice(self):
+        np.random.seed(1234)
+
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+
+        I = [1, 2, 3, 3, 4, 2]
+        J = [5, 6, 3, 2, 3, 1]
+
+        I_bad = [ii + 5 for ii in I]
+        J_bad = [jj + 7 for jj in J]
+
+        C1 = [1, 2, 3, 4, 5, 6, 7]
+        C2 = np.arange(5)[:, None]
+        assert_raises(IndexError, S.__setitem__, (I_bad, slice(None)), C1)
+        assert_raises(IndexError, S.__setitem__, (slice(None), J_bad), C2)
+
+
+class _TestArithmetic:
+    """
+    Test real/complex arithmetic
+    """
+    def __arith_init(self):
+        # these can be represented exactly in FP (so arithmetic should be exact)
+        __A = array([[-1.5, 6.5, 0, 2.25, 0, 0],
+                          [3.125, -7.875, 0.625, 0, 0, 0],
+                          [0, 0, -0.125, 1.0, 0, 0],
+                          [0, 0, 8.375, 0, 0, 0]], 'float64')
+        __B = array([[0.375, 0, 0, 0, -5, 2.5],
+                          [14.25, -3.75, 0, 0, -0.125, 0],
+                          [0, 7.25, 0, 0, 0, 0],
+                          [18.5, -0.0625, 0, 0, 0, 0]], 'complex128')
+        __B.imag = array([[1.25, 0, 0, 0, 6, -3.875],
+                               [2.25, 4.125, 0, 0, 0, 2.75],
+                               [0, 4.125, 0, 0, 0, 0],
+                               [-0.0625, 0, 0, 0, 0, 0]], 'float64')
+
+        # fractions are all x/16ths
+        assert_array_equal((__A*16).astype('int32'),16*__A)
+        assert_array_equal((__B.real*16).astype('int32'),16*__B.real)
+        assert_array_equal((__B.imag*16).astype('int32'),16*__B.imag)
+
+        __Asp = self.spcreator(__A)
+        __Bsp = self.spcreator(__B)
+        return __A, __B, __Asp, __Bsp
+
+    @pytest.mark.fail_slow(20)
+    def test_add_sub(self):
+        __A, __B, __Asp, __Bsp = self.__arith_init()
+
+        # basic tests
+        assert_array_equal(
+            (__Asp + __Bsp).toarray(), __A + __B
+        )
+
+        # check conversions
+        for x in supported_dtypes:
+            with np.errstate(invalid="ignore"):
+                A = __A.astype(x)
+            Asp = self.spcreator(A)
+            for y in supported_dtypes:
+                if not np.issubdtype(y, np.complexfloating):
+                    with np.errstate(invalid="ignore"):
+                        B = __B.real.astype(y)
+                else:
+                    B = __B.astype(y)
+                Bsp = self.spcreator(B)
+
+                # addition
+                D1 = A + B
+                S1 = Asp + Bsp
+
+                assert_equal(S1.dtype,D1.dtype)
+                assert_array_equal(S1.toarray(), D1)
+                assert_array_equal(Asp + B,D1)          # check sparse + dense
+                assert_array_equal(A + Bsp,D1)          # check dense + sparse
+
+                # subtraction
+                if np.dtype('bool') in [x, y]:
+                    # boolean array subtraction deprecated in 1.9.0
+                    continue
+
+                D1 = A - B
+                S1 = Asp - Bsp
+
+                assert_equal(S1.dtype,D1.dtype)
+                assert_array_equal(S1.toarray(), D1)
+                assert_array_equal(Asp - B,D1)          # check sparse - dense
+                assert_array_equal(A - Bsp,D1)          # check dense - sparse
+
+    def test_mu(self):
+        __A, __B, __Asp, __Bsp = self.__arith_init()
+
+        # basic tests
+        assert_array_equal((__Asp @ __Bsp.T).toarray(),
+                            __A @ __B.T)
+
+        for x in supported_dtypes:
+            with np.errstate(invalid="ignore"):
+                A = __A.astype(x)
+            Asp = self.spcreator(A)
+            for y in supported_dtypes:
+                if np.issubdtype(y, np.complexfloating):
+                    B = __B.astype(y)
+                else:
+                    with np.errstate(invalid="ignore"):
+                        B = __B.real.astype(y)
+                Bsp = self.spcreator(B)
+
+                D1 = A @ B.T
+                S1 = Asp @ Bsp.T
+
+                assert_allclose(S1.toarray(), D1,
+                                atol=1e-14*abs(D1).max())
+                assert_equal(S1.dtype,D1.dtype)
+
+
+class _TestMinMax:
+    def test_minmax(self):
+        for dtype in [np.float32, np.float64, np.int32, np.int64, np.complex128]:
+            D = np.arange(20, dtype=dtype).reshape(5,4)
+
+            X = self.spcreator(D)
+            assert_equal(X.min(), 0)
+            assert_equal(X.max(), 19)
+            assert_equal(X.min().dtype, dtype)
+            assert_equal(X.max().dtype, dtype)
+
+            D *= -1
+            X = self.spcreator(D)
+            assert_equal(X.min(), -19)
+            assert_equal(X.max(), 0)
+
+            D += 5
+            X = self.spcreator(D)
+            assert_equal(X.min(), -14)
+            assert_equal(X.max(), 5)
+
+        # try a fully dense matrix
+        X = self.spcreator(np.arange(1, 10).reshape(3, 3))
+        assert_equal(X.min(), 1)
+        assert_equal(X.min().dtype, X.dtype)
+
+        X = -X
+        assert_equal(X.max(), -1)
+
+        # and a fully sparse matrix
+        Z = self.spcreator(np.zeros((1, 1)))
+        assert_equal(Z.min(), 0)
+        assert_equal(Z.max(), 0)
+        assert_equal(Z.max().dtype, Z.dtype)
+
+        # another test
+        D = np.arange(20, dtype=float).reshape(5,4)
+        D[0:2, :] = 0
+        X = self.spcreator(D)
+        assert_equal(X.min(), 0)
+        assert_equal(X.max(), 19)
+
+        # zero-size matrices
+        for D in [np.zeros((0, 0)), np.zeros((0, 10)), np.zeros((10, 0))]:
+            X = self.spcreator(D)
+            assert_raises(ValueError, X.min)
+            assert_raises(ValueError, X.max)
+
+    def test_minmax_axis(self):
+        keep = not self.is_array_test
+        D = np.arange(50).reshape(5, 10)
+        # completely empty rows, leaving some completely full:
+        D[1, :] = 0
+        # empty at end for reduceat:
+        D[:, 9] = 0
+        # partial rows/cols:
+        D[3, 3] = 0
+        # entries on either side of 0:
+        D[2, 2] = -1
+        X = self.spcreator(D)
+
+        axes_even = [0, -2]
+        axes_odd = [1, -1]
+        for axis in axes_odd + axes_even:
+            assert_array_equal(
+                X.max(axis=axis).toarray(), D.max(axis=axis, keepdims=keep)
+            )
+            assert_array_equal(
+                X.min(axis=axis).toarray(), D.min(axis=axis, keepdims=keep)
+            )
+
+        for axis in axes_even:
+            assert_equal(
+                X.max(axis=axis, explicit=True).toarray(),
+                self.asdense([40, 41, 42, 43, 44, 45, 46, 47, 48, 0])
+            )
+            if np.any(X.data == 0):
+                # Noncanonical case
+                expected = self.asdense([20, 1, -1, 3, 4, 5, 0, 7, 8, 0])
+            else:
+                expected = self.asdense([20, 1, -1, 3, 4, 5, 6, 7, 8, 0])
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), expected)
+
+        for axis in axes_odd:
+            expected_max = np.array([8, 0, 28, 38, 48])
+            expected_min = np.array([1, 0, -1, 30, 40])
+            if not self.is_array_test:
+                expected_max = expected_max.reshape((5, 1))
+                expected_min = expected_min.reshape((5, 1))
+            assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max)
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min)
+
+        # full matrix
+        D = np.arange(1, 51).reshape(10, 5)
+        X = self.spcreator(D)
+        for axis in axes_odd + axes_even:
+            assert_array_equal(
+                X.max(axis=axis).toarray(), D.max(axis=axis, keepdims=keep)
+            )
+            assert_array_equal(
+                X.min(axis=axis).toarray(), D.min(axis=axis, keepdims=keep)
+            )
+
+        for axis in axes_even:
+            expected_max = D[-1, :]
+            expected_min = D[0, :]
+            if not self.is_array_test:
+                expected_max = D[None, -1, :]
+                expected_min = D[None, 0, :]
+            assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max)
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min)
+        for axis in axes_odd:
+            expected_max = D[:, -1]
+            expected_min = D[:, 0]
+            if not self.is_array_test:
+                expected_max = D[:, -1, None]
+                expected_min = D[:, 0, None]
+            assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max)
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min)
+
+        # empty matrix
+        D = self.asdense(np.zeros((10, 5)))
+        X = self.spcreator(D)
+        for axis in axes_even + axes_odd:
+            assert_equal(X.max(axis=axis, explicit=True).toarray(), D.max(axis=axis))
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), D.min(axis=axis))
+
+        # zero-size matrices
+        D = self.asdense(np.zeros((0, 10)))
+        X = self.spcreator(D)
+        explicit_values = [True, False]
+        even_explicit_pairs = list(itertools.product(axes_even, explicit_values))
+        odd_explicit_pairs = list(itertools.product(axes_odd, explicit_values))
+        for axis, ex in even_explicit_pairs:
+            assert_raises(ValueError, X.min, axis=axis, explicit=ex)
+            assert_raises(ValueError, X.max, axis=axis, explicit=ex)
+        for axis, ex in odd_explicit_pairs:
+            assert_equal(X.max(axis=axis, explicit=ex).toarray(), D.max(axis=axis))
+            assert_equal(X.min(axis=axis, explicit=ex).toarray(), D.min(axis=axis))
+
+        D = self.asdense(np.zeros((10, 0)))
+        X = self.spcreator(D)
+        for axis, ex in odd_explicit_pairs:
+            assert_raises(ValueError, X.min, axis=axis, explicit=ex)
+            assert_raises(ValueError, X.max, axis=axis, explicit=ex)
+        for axis, ex in even_explicit_pairs:
+            assert_equal(X.max(axis=axis, explicit=ex).toarray(), D.max(axis=axis))
+            assert_equal(X.min(axis=axis, explicit=ex).toarray(), D.min(axis=axis))
+
+    def test_nanminmax(self):
+        D = self.asdense(np.arange(50).reshape(5,10), dtype=float)
+        D[1, :] = 0
+        D[:, 9] = 0
+        D[3, 3] = 0
+        D[2, 2] = -1
+        D[4, 2] = np.nan
+        D[1, 4] = np.nan
+        X = self.spcreator(D)
+
+        X_nan_maximum = X.nanmax()
+        assert np.isscalar(X_nan_maximum)
+        assert X_nan_maximum == np.nanmax(D)
+
+        X_nan_minimum = X.nanmin()
+        assert np.isscalar(X_nan_minimum)
+        assert X_nan_minimum == np.nanmin(D)
+
+        axes = [-2, -1, 0, 1]
+        for axis in axes:
+            X_nan_maxima = X.nanmax(axis=axis)
+            assert_allclose(X_nan_maxima.toarray(), np.nanmax(D, axis=axis))
+            assert isinstance(X_nan_maxima, self.coo_container)
+
+            X_nan_minima = X.nanmin(axis=axis)
+            assert_allclose(X_nan_minima.toarray(), np.nanmin(D, axis=axis))
+            assert isinstance(X_nan_minima, self.coo_container)
+
+    def test_minmax_invalid_params(self):
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        for fname in ('min', 'max'):
+            func = getattr(datsp, fname)
+            assert_raises(ValueError, func, axis=3)
+            assert_raises(TypeError, func, axis=(0, 1))
+            assert_raises(TypeError, func, axis=1.5)
+            assert_raises(ValueError, func, axis=1, out=1)
+
+    def test_numpy_minmax(self):
+        # See gh-5987
+        # xref gh-7460 in 'numpy'
+        from scipy.sparse import _data
+
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        # We are only testing sparse matrices who have
+        # implemented 'min' and 'max' because they are
+        # the ones with the compatibility issues with
+        # the 'numpy' implementation.
+        if isinstance(datsp, _data._minmax_mixin):
+            assert_array_equal(np.min(datsp), np.min(dat))
+            assert_array_equal(np.max(datsp), np.max(dat))
+
+    def test_argmax(self):
+        from scipy.sparse import _data
+        D1 = np.array([
+            [-1, 5, 2, 3],
+            [0, 0, -1, -2],
+            [-1, -2, -3, -4],
+            [1, 2, 3, 4],
+            [1, 2, 0, 0],
+        ])
+        D2 = D1.transpose()
+        # Non-regression test cases for gh-16929.
+        D3 = np.array([[4, 3], [7, 5]])
+        D4 = np.array([[4, 3], [7, 0]])
+        D5 = np.array([[5, 5, 3], [4, 9, 10], [3, 4, 9]])
+
+        for D in [D1, D2, D3, D4, D5]:
+            D = self.asdense(D)
+            mat = self.spcreator(D)
+            if not isinstance(mat, _data._minmax_mixin):
+                continue
+
+            assert_equal(mat.argmax(), np.argmax(D))
+            assert_equal(mat.argmin(), np.argmin(D))
+
+            assert_equal(mat.argmax(axis=0), np.argmax(D, axis=0))
+            assert_equal(mat.argmin(axis=0), np.argmin(D, axis=0))
+
+            assert_equal(mat.argmax(axis=1), np.argmax(D, axis=1))
+            assert_equal(mat.argmin(axis=1), np.argmin(D, axis=1))
+
+        # zero-size matrices
+        D6 = self.spcreator(np.empty((0, 5)))
+        D7 = self.spcreator(np.empty((5, 0)))
+        explicits = [True, False]
+
+        for mat, axis, ex in itertools.product([D6, D7], [None, 0, 1], explicits):
+            if axis is None or mat.shape[axis] == 0:
+                with pytest.raises(ValueError, match="Cannot apply"):
+                    mat.argmax(axis=axis, explicit=ex)
+                with pytest.raises(ValueError, match="Cannot apply"):
+                    mat.argmin(axis=axis, explicit=ex)
+            else:
+                if self.is_array_test:
+                    expected = np.zeros(0)
+                else:
+                    expected = np.zeros((0, 1) if axis == 1 else (1, 0))
+                assert_equal(mat.argmin(axis=axis, explicit=ex), expected)
+                assert_equal(mat.argmax(axis=axis, explicit=ex), expected)
+
+        mat = self.spcreator(D1)
+        assert_equal(mat.argmax(axis=0, explicit=True), self.asdense([3, 0, 3, 3]))
+        assert_equal(mat.argmin(axis=0, explicit=True), self.asdense([0, 2, 2, 2]))
+
+        expected_max = np.array([1, 2, 0, 3, 1])
+        expected_min = np.array([0, 3, 3, 0, 0])
+        if mat.nnz != 16:
+            # Noncanonical case
+            expected_min[-1] = 2
+        if not self.is_array_test:
+            expected_max = expected_max.reshape((5, 1))
+            expected_min = expected_min.reshape((5, 1))
+
+        assert_equal(mat.argmax(axis=1, explicit=True), expected_max)
+        assert_equal(asarray(mat.argmin(axis=1, explicit=True)), expected_min)
+
+        # all zeros
+        D = np.zeros((2, 2))
+        mat = self.spcreator(D)
+        if mat.nnz != 0:
+            # Noncanonical case
+            assert_equal(mat.argmin(axis=None, explicit=True), 0)
+            assert_equal(mat.argmax(axis=None, explicit=True), 0)
+        else:
+            # Canonical case
+            with pytest.raises(ValueError, match="Cannot apply"):
+                mat.argmin(axis=None, explicit=True)
+            with pytest.raises(ValueError, match="Cannot apply"):
+                mat.argmax(axis=None, explicit=True)
+
+
+class _TestGetNnzAxis:
+    def test_getnnz_axis(self):
+        dat = array([[0, 2],
+                     [3, 5],
+                     [-6, 9]])
+        bool_dat = dat.astype(bool)
+        datsp = self.spcreator(dat)
+
+        accepted_return_dtypes = (np.int32, np.int64)
+
+        getnnz = datsp.count_nonzero if self.is_array_test else datsp.getnnz
+        assert_array_equal(bool_dat.sum(axis=None), getnnz(axis=None))
+        assert_array_equal(bool_dat.sum(), getnnz())
+        assert_array_equal(bool_dat.sum(axis=0), getnnz(axis=0))
+        assert_in(getnnz(axis=0).dtype, accepted_return_dtypes)
+        assert_array_equal(bool_dat.sum(axis=1), getnnz(axis=1))
+        assert_in(getnnz(axis=1).dtype, accepted_return_dtypes)
+        assert_array_equal(bool_dat.sum(axis=-2), getnnz(axis=-2))
+        assert_in(getnnz(axis=-2).dtype, accepted_return_dtypes)
+        assert_array_equal(bool_dat.sum(axis=-1), getnnz(axis=-1))
+        assert_in(getnnz(axis=-1).dtype, accepted_return_dtypes)
+
+        assert_raises(ValueError, getnnz, axis=2)
+
+
+#------------------------------------------------------------------------------
+# Tailored base class for generic tests
+#------------------------------------------------------------------------------
+
+def _possibly_unimplemented(cls, require=True):
+    """
+    Construct a class that either runs tests as usual (require=True),
+    or each method skips if it encounters a common error.
+    """
+    if require:
+        return cls
+    else:
+        def wrap(fc):
+            @functools.wraps(fc)
+            def wrapper(*a, **kw):
+                try:
+                    return fc(*a, **kw)
+                except (NotImplementedError, TypeError, ValueError,
+                        IndexError, AttributeError):
+                    raise pytest.skip("feature not implemented")
+
+            return wrapper
+
+        new_dict = dict(cls.__dict__)
+        for name, func in cls.__dict__.items():
+            if name.startswith('test_'):
+                new_dict[name] = wrap(func)
+        return type(cls.__name__ + "NotImplemented",
+                    cls.__bases__,
+                    new_dict)
+
+
+def sparse_test_class(getset=True, slicing=True, slicing_assign=True,
+                      fancy_indexing=True, fancy_assign=True,
+                      fancy_multidim_indexing=True, fancy_multidim_assign=True,
+                      minmax=True, nnz_axis=True):
+    """
+    Construct a base class, optionally converting some of the tests in
+    the suite to check that the feature is not implemented.
+    """
+    bases = (_TestCommon,
+             _possibly_unimplemented(_TestGetSet, getset),
+             _TestSolve,
+             _TestInplaceArithmetic,
+             _TestArithmetic,
+             _possibly_unimplemented(_TestSlicing, slicing),
+             _possibly_unimplemented(_TestSlicingAssign, slicing_assign),
+             _possibly_unimplemented(_TestFancyIndexing, fancy_indexing),
+             _possibly_unimplemented(_TestFancyIndexingAssign,
+                                     fancy_assign),
+             _possibly_unimplemented(_TestFancyMultidim,
+                                     fancy_indexing and fancy_multidim_indexing),
+             _possibly_unimplemented(_TestFancyMultidimAssign,
+                                     fancy_multidim_assign and fancy_assign),
+             _possibly_unimplemented(_TestMinMax, minmax),
+             _possibly_unimplemented(_TestGetNnzAxis, nnz_axis))
+
+    # check that test names do not clash
+    names = {}
+    for cls in bases:
+        for name in cls.__dict__:
+            if not name.startswith('test_'):
+                continue
+            old_cls = names.get(name)
+            if old_cls is not None:
+                raise ValueError(f"Test class {cls.__name__} overloads test "
+                                 f"{name} defined in {old_cls.__name__}")
+            names[name] = cls
+
+    return type("TestBase", bases, {})
+
+
+#------------------------------------------------------------------------------
+# Matrix class based tests
+#------------------------------------------------------------------------------
+
+class TestCSR(sparse_test_class()):
+    @classmethod
+    def spcreator(cls, *args, **kwargs):
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            return csr_array(*args, **kwargs)
+    math_dtypes = [np.bool_, np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        b = array([[0, 4, 0],
+                   [3, 0, 0],
+                   [0, 2, 0]], 'd')
+        bsp = self.csr_container(b)
+        assert_array_almost_equal(bsp.data,[4,3,2])
+        assert_array_equal(bsp.indices,[1,0,1])
+        assert_array_equal(bsp.indptr,[0,1,2,3])
+        assert_equal(bsp.nnz,3)
+        assert_equal(bsp.format,'csr')
+        assert_array_equal(bsp.toarray(), b)
+
+    def test_constructor2(self):
+        b = zeros((6,6),'d')
+        b[3,4] = 5
+        bsp = self.csr_container(b)
+        assert_array_almost_equal(bsp.data,[5])
+        assert_array_equal(bsp.indices,[4])
+        assert_array_equal(bsp.indptr,[0,0,0,0,1,1,1])
+        assert_array_almost_equal(bsp.toarray(), b)
+
+    def test_constructor3(self):
+        b = array([[1, 0],
+                   [0, 2],
+                   [3, 0]], 'd')
+        bsp = self.csr_container(b)
+        assert_array_almost_equal(bsp.data,[1,2,3])
+        assert_array_equal(bsp.indices,[0,1,0])
+        assert_array_equal(bsp.indptr,[0,1,2,3])
+        assert_array_almost_equal(bsp.toarray(), b)
+
+    def test_constructor4(self):
+        # using (data, ij) format
+        row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
+        col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
+        data = array([6., 10., 3., 9., 1., 4.,
+                              11., 2., 8., 5., 7.])
+
+        ij = vstack((row,col))
+        csr = self.csr_container((data,ij),(4,3))
+        assert_array_equal(arange(12).reshape(4, 3), csr.toarray())
+
+        # using Python lists and a specified dtype
+        csr = self.csr_container(([2**63 + 1, 1], ([0, 1], [0, 1])), dtype=np.uint64)
+        dense = array([[2**63 + 1, 0], [0, 1]], dtype=np.uint64)
+        assert_array_equal(dense, csr.toarray())
+
+        # with duplicates (should sum the duplicates)
+        csr = self.csr_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
+        assert csr.nnz == 2
+
+    def test_constructor5(self):
+        # infer dimensions from arrays
+        indptr = array([0,1,3,3])
+        indices = array([0,5,1,2])
+        data = array([1,2,3,4])
+        csr = self.csr_container((data, indices, indptr))
+        assert_array_equal(csr.shape,(3,6))
+
+    def test_constructor6(self):
+        # infer dimensions and dtype from lists
+        indptr = [0, 1, 3, 3]
+        indices = [0, 5, 1, 2]
+        data = [1, 2, 3, 4]
+        csr = self.csr_container((data, indices, indptr))
+        assert_array_equal(csr.shape, (3,6))
+        assert_(np.issubdtype(csr.dtype, np.signedinteger))
+
+    def test_constructor_smallcol(self):
+        # int64 indices not required
+        data = arange(6) + 1
+        col = array([1, 2, 1, 0, 0, 2], dtype=np.int64)
+        ptr = array([0, 2, 4, 6], dtype=np.int64)
+
+        a = self.csr_container((data, col, ptr), shape=(3, 3))
+
+        b = array([[0, 1, 2],
+                   [4, 3, 0],
+                   [5, 0, 6]], 'd')
+
+        # sparray is less aggressive in downcasting indices to int32 than spmatrix
+        expected_dtype = np.dtype(np.int64 if self.is_array_test else np.int32)
+        assert_equal(a.indptr.dtype, expected_dtype)
+        assert_equal(a.indices.dtype, expected_dtype)
+        assert_array_equal(a.toarray(), b)
+
+    def test_constructor_largecol(self):
+        # int64 indices required
+        data = arange(6) + 1
+        large = np.iinfo(np.int32).max + 100
+        col = array([0, 1, 2, large, large+1, large+2], dtype=np.int64)
+        ptr = array([0, 2, 4, 6], dtype=np.int64)
+
+        a = self.csr_container((data, col, ptr))
+
+        assert_equal(a.indptr.dtype, np.dtype(np.int64))
+        assert_equal(a.indices.dtype, np.dtype(np.int64))
+        assert_array_equal(a.shape, (3, max(col)+1))
+
+    def test_sort_indices(self):
+        data = arange(5)
+        indices = array([7, 2, 1, 5, 4])
+        indptr = array([0, 3, 5])
+        asp = self.csr_container((data, indices, indptr), shape=(2,10))
+        bsp = asp.copy()
+        asp.sort_indices()
+        assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_eliminate_zeros(self):
+        data = array([1, 0, 0, 0, 2, 0, 3, 0])
+        indices = array([1, 2, 3, 4, 5, 6, 7, 8])
+        indptr = array([0, 3, 8])
+        asp = self.csr_container((data, indices, indptr), shape=(2,10))
+        bsp = asp.copy()
+        asp.eliminate_zeros()
+        assert_array_equal(asp.nnz, 3)
+        assert_array_equal(asp.data,[1, 2, 3])
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_ufuncs(self):
+        X = self.csr_container(np.arange(20).reshape(4, 5) / 20.)
+        for f in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
+                  "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
+                  "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt"]:
+            assert_equal(hasattr(self.datsp, f), True)
+            X2 = getattr(X, f)()
+            assert_equal(X.shape, X2.shape)
+            assert_array_equal(X.indices, X2.indices)
+            assert_array_equal(X.indptr, X2.indptr)
+            assert_array_equal(X2.toarray(), getattr(np, f)(X.toarray()))
+
+    def test_unsorted_arithmetic(self):
+        data = arange(5)
+        indices = array([7, 2, 1, 5, 4])
+        indptr = array([0, 3, 5])
+        asp = self.csr_container((data, indices, indptr), shape=(2,10))
+        data = arange(6)
+        indices = array([8, 1, 5, 7, 2, 4])
+        indptr = array([0, 2, 6])
+        bsp = self.csr_container((data, indices, indptr), shape=(2,10))
+        assert_equal((asp + bsp).toarray(), asp.toarray() + bsp.toarray())
+
+    def test_fancy_indexing_broadcast(self):
+        # broadcasting indexing mode is supported
+        I = np.array([[1], [2], [3]])
+        J = np.array([3, 4, 2])
+
+        np.random.seed(1234)
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+
+        SIJ = S[I,J]
+        if issparse(SIJ):
+            SIJ = SIJ.toarray()
+        assert_equal(SIJ, D[I,J])
+
+    def test_has_sorted_indices(self):
+        "Ensure has_sorted_indices memoizes sorted state for sort_indices"
+        sorted_inds = np.array([0, 1])
+        unsorted_inds = np.array([1, 0])
+        data = np.array([1, 1])
+        indptr = np.array([0, 2])
+        M = self.csr_container((data, sorted_inds, indptr)).copy()
+        assert_equal(True, M.has_sorted_indices)
+        assert isinstance(M.has_sorted_indices, bool)
+
+        M = self.csr_container((data, unsorted_inds, indptr)).copy()
+        assert_equal(False, M.has_sorted_indices)
+
+        # set by sorting
+        M.sort_indices()
+        assert_equal(True, M.has_sorted_indices)
+        assert_array_equal(M.indices, sorted_inds)
+
+        M = self.csr_container((data, unsorted_inds, indptr)).copy()
+        # set manually (although underlyingly unsorted)
+        M.has_sorted_indices = True
+        assert_equal(True, M.has_sorted_indices)
+        assert_array_equal(M.indices, unsorted_inds)
+
+        # ensure sort bypassed when has_sorted_indices == True
+        M.sort_indices()
+        assert_array_equal(M.indices, unsorted_inds)
+
+    def test_has_canonical_format(self):
+        "Ensure has_canonical_format memoizes state for sum_duplicates"
+
+        M = self.csr_container((np.array([2]), np.array([0]), np.array([0, 1])))
+        assert_equal(True, M.has_canonical_format)
+
+        indices = np.array([0, 0])  # contains duplicate
+        data = np.array([1, 1])
+        indptr = np.array([0, 2])
+
+        M = self.csr_container((data, indices, indptr)).copy()
+        assert_equal(False, M.has_canonical_format)
+        assert isinstance(M.has_canonical_format, bool)
+
+        # set by deduplicating
+        M.sum_duplicates()
+        assert_equal(True, M.has_canonical_format)
+        assert_equal(1, len(M.indices))
+
+        M = self.csr_container((data, indices, indptr)).copy()
+        # set manually (although underlyingly duplicated)
+        M.has_canonical_format = True
+        assert_equal(True, M.has_canonical_format)
+        assert_equal(2, len(M.indices))  # unaffected content
+
+        # ensure deduplication bypassed when has_canonical_format == True
+        M.sum_duplicates()
+        assert_equal(2, len(M.indices))  # unaffected content
+
+    def test_scalar_idx_dtype(self):
+        # Check that index dtype takes into account all parameters
+        # passed to sparsetools, including the scalar ones
+        indptr = np.zeros(2, dtype=np.int32)
+        indices = np.zeros(0, dtype=np.int32)
+        vals = np.zeros(0)
+        a = self.csr_container((vals, indices, indptr), shape=(1, 2**31-1))
+        b = self.csr_container((vals, indices, indptr), shape=(1, 2**31))
+        ij = np.zeros((2, 0), dtype=np.int32)
+        c = self.csr_container((vals, ij), shape=(1, 2**31-1))
+        d = self.csr_container((vals, ij), shape=(1, 2**31))
+        e = self.csr_container((1, 2**31-1))
+        f = self.csr_container((1, 2**31))
+        assert_equal(a.indptr.dtype, np.int32)
+        assert_equal(b.indptr.dtype, np.int64)
+        assert_equal(c.indptr.dtype, np.int32)
+        assert_equal(d.indptr.dtype, np.int64)
+        assert_equal(e.indptr.dtype, np.int32)
+        assert_equal(f.indptr.dtype, np.int64)
+
+        # These shouldn't fail
+        for x in [a, b, c, d, e, f]:
+            x + x
+
+    def test_setdiag_csr(self):
+        # see gh-21791 setting mixture of existing and not when new_values < 0.001*nnz
+        D = self.dia_container(([np.arange(1002)], [0]), shape=(1002, 1002))
+        A = self.spcreator(D)
+        A.setdiag(5 * np.ones(A.shape[0]))
+        assert A[-1, -1] == 5
+
+    def test_binop_explicit_zeros(self):
+        # Check that binary ops don't introduce spurious explicit zeros.
+        # See gh-9619 for context.
+        a = self.csr_container([[0, 1, 0]])
+        b = self.csr_container([[1, 1, 0]])
+        assert (a + b).nnz == 2
+        assert a.multiply(b).nnz == 1
+
+
+TestCSR.init_class()
+
+
+class TestCSRMatrix(_MatrixMixin, TestCSR):
+    @classmethod
+    def spcreator(cls, *args, **kwargs):
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            return csr_matrix(*args, **kwargs)
+
+
+TestCSRMatrix.init_class()
+
+
+class TestCSC(sparse_test_class()):
+    @classmethod
+    def spcreator(cls, *args, **kwargs):
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            return csc_array(*args, **kwargs)
+    math_dtypes = [np.bool_, np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        b = array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 2, 0, 3]], 'd')
+        bsp = self.csc_container(b)
+        assert_array_almost_equal(bsp.data,[1,2,1,3])
+        assert_array_equal(bsp.indices,[0,2,1,2])
+        assert_array_equal(bsp.indptr,[0,1,2,3,4])
+        assert_equal(bsp.nnz,4)
+        assert_equal(bsp.shape,b.shape)
+        assert_equal(bsp.format,'csc')
+
+    def test_constructor2(self):
+        b = zeros((6,6),'d')
+        b[2,4] = 5
+        bsp = self.csc_container(b)
+        assert_array_almost_equal(bsp.data,[5])
+        assert_array_equal(bsp.indices,[2])
+        assert_array_equal(bsp.indptr,[0,0,0,0,0,1,1])
+
+    def test_constructor3(self):
+        b = array([[1, 0], [0, 0], [0, 2]], 'd')
+        bsp = self.csc_container(b)
+        assert_array_almost_equal(bsp.data,[1,2])
+        assert_array_equal(bsp.indices,[0,2])
+        assert_array_equal(bsp.indptr,[0,1,2])
+
+    def test_constructor4(self):
+        # using (data, ij) format
+        row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
+        col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
+        data = array([6., 10., 3., 9., 1., 4., 11., 2., 8., 5., 7.])
+
+        ij = vstack((row,col))
+        csc = self.csc_container((data,ij),(4,3))
+        assert_array_equal(arange(12).reshape(4, 3), csc.toarray())
+
+        # with duplicates (should sum the duplicates)
+        csc = self.csc_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
+        assert csc.nnz == 2
+
+    def test_constructor5(self):
+        # infer dimensions from arrays
+        indptr = array([0,1,3,3])
+        indices = array([0,5,1,2])
+        data = array([1,2,3,4])
+        csc = self.csc_container((data, indices, indptr))
+        assert_array_equal(csc.shape,(6,3))
+
+    def test_constructor6(self):
+        # infer dimensions and dtype from lists
+        indptr = [0, 1, 3, 3]
+        indices = [0, 5, 1, 2]
+        data = [1, 2, 3, 4]
+        csc = self.csc_container((data, indices, indptr))
+        assert_array_equal(csc.shape,(6,3))
+        assert_(np.issubdtype(csc.dtype, np.signedinteger))
+
+    def test_eliminate_zeros(self):
+        data = array([1, 0, 0, 0, 2, 0, 3, 0])
+        indices = array([1, 2, 3, 4, 5, 6, 7, 8])
+        indptr = array([0, 3, 8])
+        asp = self.csc_container((data, indices, indptr), shape=(10,2))
+        bsp = asp.copy()
+        asp.eliminate_zeros()
+        assert_array_equal(asp.nnz, 3)
+        assert_array_equal(asp.data,[1, 2, 3])
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_sort_indices(self):
+        data = arange(5)
+        row = array([7, 2, 1, 5, 4])
+        ptr = [0, 3, 5]
+        asp = self.csc_container((data, row, ptr), shape=(10,2))
+        bsp = asp.copy()
+        asp.sort_indices()
+        assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_ufuncs(self):
+        X = self.csc_container(np.arange(21).reshape(7, 3) / 21.)
+        for f in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
+                  "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
+                  "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt"]:
+            assert_equal(hasattr(self.datsp, f), True)
+            X2 = getattr(X, f)()
+            assert_equal(X.shape, X2.shape)
+            assert_array_equal(X.indices, X2.indices)
+            assert_array_equal(X.indptr, X2.indptr)
+            assert_array_equal(X2.toarray(), getattr(np, f)(X.toarray()))
+
+    def test_unsorted_arithmetic(self):
+        data = arange(5)
+        indices = array([7, 2, 1, 5, 4])
+        indptr = array([0, 3, 5])
+        asp = self.csc_container((data, indices, indptr), shape=(10,2))
+        data = arange(6)
+        indices = array([8, 1, 5, 7, 2, 4])
+        indptr = array([0, 2, 6])
+        bsp = self.csc_container((data, indices, indptr), shape=(10,2))
+        assert_equal((asp + bsp).toarray(), asp.toarray() + bsp.toarray())
+
+    def test_fancy_indexing_broadcast(self):
+        # broadcasting indexing mode is supported
+        I = np.array([[1], [2], [3]])
+        J = np.array([3, 4, 2])
+
+        np.random.seed(1234)
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+
+        SIJ = S[I,J]
+        if issparse(SIJ):
+            SIJ = SIJ.toarray()
+        assert_equal(SIJ, D[I,J])
+
+    def test_scalar_idx_dtype(self):
+        # Check that index dtype takes into account all parameters
+        # passed to sparsetools, including the scalar ones
+        indptr = np.zeros(2, dtype=np.int32)
+        indices = np.zeros(0, dtype=np.int32)
+        vals = np.zeros(0)
+        a = self.csc_container((vals, indices, indptr), shape=(2**31-1, 1))
+        b = self.csc_container((vals, indices, indptr), shape=(2**31, 1))
+        ij = np.zeros((2, 0), dtype=np.int32)
+        c = self.csc_container((vals, ij), shape=(2**31-1, 1))
+        d = self.csc_container((vals, ij), shape=(2**31, 1))
+        e = self.csr_container((1, 2**31-1))
+        f = self.csr_container((1, 2**31))
+        assert_equal(a.indptr.dtype, np.int32)
+        assert_equal(b.indptr.dtype, np.int64)
+        assert_equal(c.indptr.dtype, np.int32)
+        assert_equal(d.indptr.dtype, np.int64)
+        assert_equal(e.indptr.dtype, np.int32)
+        assert_equal(f.indptr.dtype, np.int64)
+
+        # These shouldn't fail
+        for x in [a, b, c, d, e, f]:
+            x + x
+
+    def test_setdiag_csc(self):
+        # see gh-21791 setting mixture of existing and not when new_values < 0.001*nnz
+        D = self.dia_container(([np.arange(1002)], [0]), shape=(1002, 1002))
+        A = self.spcreator(D)
+        A.setdiag(5 * np.ones(A.shape[0]))
+        assert A[-1, -1] == 5
+
+
+TestCSC.init_class()
+
+
+class TestCSCMatrix(_MatrixMixin, TestCSC):
+    @classmethod
+    def spcreator(cls, *args, **kwargs):
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            return csc_matrix(*args, **kwargs)
+
+
+TestCSCMatrix.init_class()
+
+
+class TestDOK(sparse_test_class(minmax=False, nnz_axis=False)):
+    spcreator = dok_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_mult(self):
+        A = self.dok_container((10, 12))
+        A[0, 3] = 10
+        A[5, 6] = 20
+        D = A @ A.T
+        E = A @ A.T.conjugate()
+        assert_array_equal(D.toarray(), E.toarray())
+
+    def test_add_nonzero(self):
+        A = self.spcreator((3,2))
+        A[0,1] = -10
+        A[2,0] = 20
+        A = A + 10
+        B = array([[10, 0], [10, 10], [30, 10]])
+        assert_array_equal(A.toarray(), B)
+
+        A = A + 1j
+        B = B + 1j
+        assert_array_equal(A.toarray(), B)
+
+    def test_dok_divide_scalar(self):
+        A = self.spcreator((3,2))
+        A[0,1] = -10
+        A[2,0] = 20
+
+        assert_array_equal((A/1j).toarray(), A.toarray()/1j)
+        assert_array_equal((A/9).toarray(), A.toarray()/9)
+
+    def test_convert(self):
+        # Test provided by Andrew Straw.  Fails in SciPy <= r1477.
+        (m, n) = (6, 7)
+        a = self.dok_container((m, n))
+
+        # set a few elements, but none in the last column
+        a[2,1] = 1
+        a[0,2] = 2
+        a[3,1] = 3
+        a[1,5] = 4
+        a[4,3] = 5
+        a[4,2] = 6
+
+        # assert that the last column is all zeros
+        assert_array_equal(a.toarray()[:,n-1], zeros(m,))
+
+        # make sure it still works for CSC format
+        csc = a.tocsc()
+        assert_array_equal(csc.toarray()[:,n-1], zeros(m,))
+
+        # now test CSR
+        (m, n) = (n, m)
+        b = a.transpose()
+        assert_equal(b.shape, (m, n))
+        # assert that the last row is all zeros
+        assert_array_equal(b.toarray()[m-1,:], zeros(n,))
+
+        # make sure it still works for CSR format
+        csr = b.tocsr()
+        assert_array_equal(csr.toarray()[m-1,:], zeros(n,))
+
+    def test_ctor(self):
+        # Empty ctor
+        assert_raises(TypeError, self.dok_container)
+
+        # Dense ctor
+        b = array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 2, 0, 3]], 'd')
+        A = self.dok_container(b)
+        assert_equal(b.dtype, A.dtype)
+        assert_equal(A.toarray(), b)
+
+        # Sparse ctor
+        c = self.csr_container(b)
+        assert_equal(A.toarray(), c.toarray())
+
+        data = [[0, 1, 2], [3, 0, 0]]
+        d = self.dok_container(data, dtype=np.float32)
+        assert_equal(d.dtype, np.float32)
+        da = d.toarray()
+        assert_equal(da.dtype, np.float32)
+        assert_array_equal(da, data)
+
+    def test_ticket1160(self):
+        # Regression test for ticket #1160.
+        a = self.dok_container((3,3))
+        a[0,0] = 0
+        # This assert would fail, because the above assignment would
+        # incorrectly call __set_item__ even though the value was 0.
+        assert_((0,0) not in a.keys(), "Unexpected entry (0,0) in keys")
+
+        # Slice assignments were also affected.
+        b = self.dok_container((3,3))
+        b[:,0] = 0
+        assert_(len(b.keys()) == 0, "Unexpected entries in keys")
+
+
+class TestDOKMatrix(_MatrixMixin, TestDOK):
+    spcreator = dok_matrix
+
+
+TestDOK.init_class()
+TestDOKMatrix.init_class()
+
+
+class TestLIL(sparse_test_class(minmax=False)):
+    spcreator = lil_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_dot(self):
+        A = zeros((10, 10), np.complex128)
+        A[0, 3] = 10
+        A[5, 6] = 20j
+
+        B = self.lil_container((10, 10), dtype=np.complex128)
+        B[0, 3] = 10
+        B[5, 6] = 20j
+
+        # TODO: properly handle this assertion on ppc64le
+        if platform.machine() != 'ppc64le':
+            assert_array_equal(A @ A.T, (B @ B.T).toarray())
+
+        assert_array_equal(A @ A.conjugate().T, (B @ B.conjugate().T).toarray())
+
+    def test_scalar_mul(self):
+        x = self.lil_container((3, 3))
+        x[0, 0] = 2
+
+        x = x*2
+        assert_equal(x[0, 0], 4)
+
+        x = x*0
+        assert_equal(x[0, 0], 0)
+
+    def test_truediv_scalar(self):
+        A = self.spcreator((3, 2))
+        A[0, 1] = -10
+        A[2, 0] = 20
+
+        assert_array_equal((A / 1j).toarray(), A.toarray() / 1j)
+        assert_array_equal((A / 9).toarray(), A.toarray() / 9)
+
+    def test_inplace_ops(self):
+        A = self.lil_container([[0, 2, 3], [4, 0, 6]])
+        B = self.lil_container([[0, 1, 0], [0, 2, 3]])
+
+        data = {'add': (B, A + B),
+                'sub': (B, A - B),
+                'mul': (3, A * 3)}
+
+        for op, (other, expected) in data.items():
+            result = A.copy()
+            getattr(result, f'__i{op}__')(other)
+
+            assert_array_equal(result.toarray(), expected.toarray())
+
+        # Ticket 1604.
+        A = self.lil_container((1, 3), dtype=np.dtype('float64'))
+        B = self.asdense([0.1, 0.1, 0.1])
+        A[0, :] += B
+        assert_array_equal(A[0, :].toarray(), B)
+
+    def test_lil_iteration(self):
+        row_data = [[1, 2, 3], [4, 5, 6]]
+        B = self.lil_container(array(row_data))
+        for r, row in enumerate(B):
+            assert_array_equal(row.toarray(), array(row_data[r], ndmin=row.ndim))
+
+    def test_lil_from_csr(self):
+        # Tests whether a LIL can be constructed from a CSR.
+        B = self.lil_container((10, 10))
+        B[0, 3] = 10
+        B[5, 6] = 20
+        B[8, 3] = 30
+        B[3, 8] = 40
+        B[8, 9] = 50
+        C = B.tocsr()
+        D = self.lil_container(C)
+        assert_array_equal(C.toarray(), D.toarray())
+
+    def test_fancy_indexing_lil(self):
+        M = self.asdense(arange(25).reshape(5, 5))
+        A = self.lil_container(M)
+
+        assert_equal(A[array([1, 2, 3]), 2:3].toarray(),
+                     M[array([1, 2, 3]), 2:3])
+
+    def test_point_wise_multiply(self):
+        l = self.lil_container((4, 3))
+        l[0, 0] = 1
+        l[1, 1] = 2
+        l[2, 2] = 3
+        l[3, 1] = 4
+
+        m = self.lil_container((4, 3))
+        m[0, 0] = 1
+        m[0, 1] = 2
+        m[2, 2] = 3
+        m[3, 1] = 4
+        m[3, 2] = 4
+
+        assert_array_equal(l.multiply(m).toarray(),
+                           m.multiply(l).toarray())
+
+        assert_array_equal(l.multiply(m).toarray(),
+                           [[1, 0, 0],
+                            [0, 0, 0],
+                            [0, 0, 9],
+                            [0, 16, 0]])
+
+    def test_lil_multiply_removal(self):
+        # Ticket #1427.
+        a = self.lil_container(np.ones((3, 3)))
+        a *= 2.
+        a[0, :] = 0
+
+
+class TestLILMatrix(_MatrixMixin, TestLIL):
+    spcreator = lil_matrix
+
+
+TestLIL.init_class()
+TestLILMatrix.init_class()
+
+
+class TestCOO(sparse_test_class(getset=False,
+                                slicing=False, slicing_assign=False,
+                                fancy_indexing=False, fancy_assign=False)):
+    spcreator = coo_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        # unsorted triplet format
+        row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
+        col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
+        data = array([6., 10., 3., 9., 1., 4., 11., 2., 8., 5., 7.])
+
+        coo = self.coo_container((data,(row,col)),(4,3))
+        assert_array_equal(arange(12).reshape(4, 3), coo.toarray())
+
+        # using Python lists and a specified dtype
+        coo = self.coo_container(([2**63 + 1, 1], ([0, 1], [0, 1])), dtype=np.uint64)
+        dense = array([[2**63 + 1, 0], [0, 1]], dtype=np.uint64)
+        assert_array_equal(dense, coo.toarray())
+
+    def test_constructor2(self):
+        # unsorted triplet format with duplicates (which are summed)
+        row = array([0,1,2,2,2,2,0,0,2,2])
+        col = array([0,2,0,2,1,1,1,0,0,2])
+        data = array([2,9,-4,5,7,0,-1,2,1,-5])
+        coo = self.coo_container((data,(row,col)),(3,3))
+
+        mat = array([[4, -1, 0], [0, 0, 9], [-3, 7, 0]])
+
+        assert_array_equal(mat, coo.toarray())
+
+    def test_constructor3(self):
+        # empty matrix
+        coo = self.coo_container((4,3))
+
+        assert_array_equal(coo.shape,(4,3))
+        assert_array_equal(coo.row,[])
+        assert_array_equal(coo.col,[])
+        assert_array_equal(coo.data,[])
+        assert_array_equal(coo.toarray(), zeros((4, 3)))
+
+    def test_constructor4(self):
+        # from dense matrix
+        mat = array([[0,1,0,0],
+                     [7,0,3,0],
+                     [0,4,0,0]])
+        coo = self.coo_container(mat)
+        assert_array_equal(coo.toarray(), mat)
+
+        # upgrade rank 1 arrays to row matrix
+        mat = array([0,1,0,0])
+        coo = self.coo_container(mat)
+        expected = mat if self.is_array_test else mat.reshape(1, -1)
+        assert_array_equal(coo.toarray(), expected)
+
+        # error if second arg interpreted as shape (gh-9919)
+        with pytest.raises(TypeError, match=r'object cannot be interpreted'):
+            self.coo_container([0, 11, 22, 33], ([0, 1, 2, 3], [0, 0, 0, 0]))
+
+        # error if explicit shape arg doesn't match the dense matrix
+        with pytest.raises(ValueError, match=r'inconsistent shapes'):
+            self.coo_container([0, 11, 22, 33], shape=(4, 4))
+
+    def test_constructor_data_ij_dtypeNone(self):
+        data = [1]
+        coo = self.coo_container((data, ([0], [0])), dtype=None)
+        assert coo.dtype == np.array(data).dtype
+
+    @pytest.mark.xfail(run=False, reason='COO does not have a __getitem__')
+    def test_iterator(self):
+        pass
+
+    def test_todia_all_zeros(self):
+        zeros = [[0, 0]]
+        dia = self.coo_container(zeros).todia()
+        assert_array_equal(dia.toarray(), zeros)
+
+    def test_sum_duplicates(self):
+        coo = self.coo_container((4,3))
+        coo.sum_duplicates()
+        coo = self.coo_container(([1,2], ([1,0], [1,0])))
+        coo.sum_duplicates()
+        assert_array_equal(coo.toarray(), [[2,0],[0,1]])
+        coo = self.coo_container(([1,2], ([1,1], [1,1])))
+        coo.sum_duplicates()
+        assert_array_equal(coo.toarray(), [[0,0],[0,3]])
+        assert_array_equal(coo.row, [1])
+        assert_array_equal(coo.col, [1])
+        assert_array_equal(coo.data, [3])
+
+    def test_todok_duplicates(self):
+        coo = self.coo_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
+        dok = coo.todok()
+        assert_array_equal(dok.toarray(), coo.toarray())
+
+    def test_tocompressed_duplicates(self):
+        coo = self.coo_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
+        csr = coo.tocsr()
+        assert_equal(csr.nnz + 2, coo.nnz)
+        csc = coo.tocsc()
+        assert_equal(csc.nnz + 2, coo.nnz)
+
+    def test_eliminate_zeros(self):
+        data = array([1, 0, 0, 0, 2, 0, 3, 0])
+        row = array([0, 0, 0, 1, 1, 1, 1, 1])
+        col = array([1, 2, 3, 4, 5, 6, 7, 8])
+        asp = self.coo_container((data, (row, col)), shape=(2,10))
+        bsp = asp.copy()
+        asp.eliminate_zeros()
+        assert_((asp.data != 0).all())
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_reshape_copy(self):
+        arr = [[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]]
+        new_shape = (2, 6)
+        x = self.coo_container(arr)
+
+        y = x.reshape(new_shape)
+        assert_(y.data is x.data)
+
+        y = x.reshape(new_shape, copy=False)
+        assert_(y.data is x.data)
+
+        y = x.reshape(new_shape, copy=True)
+        assert_(not np.may_share_memory(y.data, x.data))
+
+    def test_large_dimensions_reshape(self):
+        # Test that reshape is immune to integer overflow when number of elements
+        # exceeds 2^31-1
+        mat1 = self.coo_container(([1], ([3000000], [1000])), (3000001, 1001))
+        mat2 = self.coo_container(([1], ([1000], [3000000])), (1001, 3000001))
+
+        # assert_array_equal is slow for big matrices because it expects dense
+        # Using __ne__ and nnz instead
+        assert_((mat1.reshape((1001, 3000001), order='C') != mat2).nnz == 0)
+        assert_((mat2.reshape((3000001, 1001), order='F') != mat1).nnz == 0)
+
+
+class TestCOOMatrix(_MatrixMixin, TestCOO):
+    spcreator = coo_matrix
+
+
+TestCOO.init_class()
+TestCOOMatrix.init_class()
+
+
+class TestDIA(sparse_test_class(getset=False, slicing=False, slicing_assign=False,
+                                fancy_indexing=False, fancy_assign=False,
+                                minmax=False, nnz_axis=False)):
+    spcreator = dia_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        D = array([[1, 0, 3, 0],
+                   [1, 2, 0, 4],
+                   [0, 2, 3, 0],
+                   [0, 0, 3, 4]])
+        data = np.array([[1,2,3,4]]).repeat(3,axis=0)
+        offsets = np.array([0,-1,2])
+        assert_equal(self.dia_container((data, offsets), shape=(4, 4)).toarray(), D)
+
+    @pytest.mark.xfail(run=False, reason='DIA does not have a __getitem__')
+    def test_iterator(self):
+        pass
+
+    @with_64bit_maxval_limit(3)
+    def test_setdiag_dtype(self):
+        m = self.dia_container(np.eye(3))
+        assert_equal(m.offsets.dtype, np.int32)
+        m.setdiag((3,), k=2)
+        assert_equal(m.offsets.dtype, np.int32)
+
+        m = self.dia_container(np.eye(4))
+        assert_equal(m.offsets.dtype, np.int64)
+        m.setdiag((3,), k=3)
+        assert_equal(m.offsets.dtype, np.int64)
+
+    @pytest.mark.skip(reason='DIA stores extra zeros')
+    def test_getnnz_axis(self):
+        pass
+
+    def test_convert_gh14555(self):
+        # regression test for gh-14555
+        m = self.dia_container(([[1, 1, 0]], [-1]), shape=(4, 2))
+        expected = m.toarray()
+        assert_array_equal(m.tocsc().toarray(), expected)
+        assert_array_equal(m.tocsr().toarray(), expected)
+
+    def test_tocoo_gh10050(self):
+        # regression test for gh-10050
+        m = self.dia_container([[1, 2], [3, 4]]).tocoo()
+        flat_inds = np.ravel_multi_index((m.row, m.col), m.shape)
+        inds_are_sorted = np.all(np.diff(flat_inds) > 0)
+        assert m.has_canonical_format == inds_are_sorted
+
+    def test_tocoo_tocsr_tocsc_gh19245(self):
+        # test index_dtype with tocoo, tocsr, tocsc
+        data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
+        offsets = np.array([0, -1, 2], dtype=np.int32)
+        dia = sparse.dia_array((data, offsets), shape=(4, 4))
+
+        coo = dia.tocoo()
+        assert coo.col.dtype == np.int32
+        csr = dia.tocsr()
+        assert csr.indices.dtype == np.int32
+        csc = dia.tocsc()
+        assert csc.indices.dtype == np.int32
+
+    def test_mul_scalar(self):
+        # repro for gh-20434
+        m = self.dia_container([[1, 2], [0, 4]])
+        res = m * 3
+        assert isinstance(res, m.__class__)
+        assert_array_equal(res.toarray(), [[3, 6], [0, 12]])
+
+        res2 = m.multiply(3)
+        assert isinstance(res2, m.__class__)
+        assert_array_equal(res2.toarray(), [[3, 6], [0, 12]])
+
+
+class TestDIAMatrix(_MatrixMixin, TestDIA):
+    spcreator = dia_matrix
+
+
+TestDIA.init_class()
+TestDIAMatrix.init_class()
+
+
+class TestBSR(sparse_test_class(getset=False,
+                                slicing=False, slicing_assign=False,
+                                fancy_indexing=False, fancy_assign=False,
+                                nnz_axis=False)):
+    spcreator = bsr_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        # check native BSR format constructor
+        indptr = array([0,2,2,4])
+        indices = array([0,2,2,3])
+        data = zeros((4,2,3))
+
+        data[0] = array([[0, 1, 2],
+                         [3, 0, 5]])
+        data[1] = array([[0, 2, 4],
+                         [6, 0, 10]])
+        data[2] = array([[0, 4, 8],
+                         [12, 0, 20]])
+        data[3] = array([[0, 5, 10],
+                         [15, 0, 25]])
+
+        A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]])
+        Asp = self.bsr_container((data,indices,indptr),shape=(6,12))
+        assert_equal(Asp.toarray(), A)
+
+        # infer shape from arrays
+        Asp = self.bsr_container((data,indices,indptr))
+        assert_equal(Asp.toarray(), A)
+
+    def test_constructor2(self):
+        # construct from dense
+
+        # test zero mats
+        for shape in [(1,1), (5,1), (1,10), (10,4), (3,7), (2,1)]:
+            A = zeros(shape)
+            assert_equal(self.bsr_container(A).toarray(), A)
+        A = zeros((4,6))
+        assert_equal(self.bsr_container(A, blocksize=(2, 2)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A)
+
+        A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]])
+        assert_equal(self.bsr_container(A).toarray(), A)
+        assert_equal(self.bsr_container(A, shape=(6, 12)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(1, 1)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(2, 6)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(2, 12)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(3, 12)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(6, 12)).toarray(), A)
+
+        A = kron([[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]])
+        assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A)
+
+    def test_constructor3(self):
+        # construct from coo-like (data,(row,col)) format
+        arg = ([1,2,3], ([0,1,1], [0,0,1]))
+        A = array([[1,0],[2,3]])
+        assert_equal(self.bsr_container(arg, blocksize=(2, 2)).toarray(), A)
+
+    def test_constructor4(self):
+        # regression test for gh-6292: self.bsr_matrix((data, indices, indptr)) was
+        #  trying to compare an int to a None
+        n = 8
+        data = np.ones((n, n, 1), dtype=np.int8)
+        indptr = np.array([0, n], dtype=np.int32)
+        indices = np.arange(n, dtype=np.int32)
+        self.bsr_container((data, indices, indptr), blocksize=(n, 1), copy=False)
+
+    def test_constructor5(self):
+        # check for validations introduced in gh-13400
+        n = 8
+        data_1dim = np.ones(n)
+        data = np.ones((n, n, n))
+        indptr = np.array([0, n])
+        indices = np.arange(n)
+
+        with assert_raises(ValueError):
+            # data ndim check
+            self.bsr_container((data_1dim, indices, indptr))
+
+        with assert_raises(ValueError):
+            # invalid blocksize
+            self.bsr_container((data, indices, indptr), blocksize=(1, 1, 1))
+
+        with assert_raises(ValueError):
+            # mismatching blocksize
+            self.bsr_container((data, indices, indptr), blocksize=(1, 1))
+
+    def test_default_dtype(self):
+        # As a numpy array, `values` has shape (2, 2, 1).
+        values = [[[1], [1]], [[1], [1]]]
+        indptr = np.array([0, 2], dtype=np.int32)
+        indices = np.array([0, 1], dtype=np.int32)
+        b = self.bsr_container((values, indices, indptr), blocksize=(2, 1))
+        assert b.dtype == np.array(values).dtype
+
+    def test_bsr_tocsr(self):
+        # check native conversion from BSR to CSR
+        indptr = array([0, 2, 2, 4])
+        indices = array([0, 2, 2, 3])
+        data = zeros((4, 2, 3))
+
+        data[0] = array([[0, 1, 2],
+                         [3, 0, 5]])
+        data[1] = array([[0, 2, 4],
+                         [6, 0, 10]])
+        data[2] = array([[0, 4, 8],
+                         [12, 0, 20]])
+        data[3] = array([[0, 5, 10],
+                         [15, 0, 25]])
+
+        A = kron([[1, 0, 2, 0], [0, 0, 0, 0], [0, 0, 4, 5]],
+                 [[0, 1, 2], [3, 0, 5]])
+        Absr = self.bsr_container((data, indices, indptr), shape=(6, 12))
+        Acsr = Absr.tocsr()
+        Acsr_via_coo = Absr.tocoo().tocsr()
+        assert_equal(Acsr.toarray(), A)
+        assert_equal(Acsr.toarray(), Acsr_via_coo.toarray())
+
+    def test_eliminate_zeros(self):
+        data = kron([1, 0, 0, 0, 2, 0, 3, 0], [[1,1],[1,1]]).T
+        data = data.reshape(-1,2,2)
+        indices = array([1, 2, 3, 4, 5, 6, 7, 8])
+        indptr = array([0, 3, 8])
+        asp = self.bsr_container((data, indices, indptr), shape=(4,20))
+        bsp = asp.copy()
+        asp.eliminate_zeros()
+        assert_array_equal(asp.nnz, 3*4)
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    # GitHub issue #9687
+    def test_eliminate_zeros_all_zero(self):
+        np.random.seed(0)
+        m = self.bsr_container(np.random.random((12, 12)), blocksize=(2, 3))
+
+        # eliminate some blocks, but not all
+        m.data[m.data <= 0.9] = 0
+        m.eliminate_zeros()
+        assert_equal(m.nnz, 66)
+        assert_array_equal(m.data.shape, (11, 2, 3))
+
+        # eliminate all remaining blocks
+        m.data[m.data <= 1.0] = 0
+        m.eliminate_zeros()
+        assert_equal(m.nnz, 0)
+        assert_array_equal(m.data.shape, (0, 2, 3))
+        assert_array_equal(m.toarray(), np.zeros((12, 12)))
+
+        # test fast path
+        m.eliminate_zeros()
+        assert_equal(m.nnz, 0)
+        assert_array_equal(m.data.shape, (0, 2, 3))
+        assert_array_equal(m.toarray(), np.zeros((12, 12)))
+
+    def test_bsr_matvec(self):
+        A = self.bsr_container(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5))
+        x = arange(A.shape[1]).reshape(-1,1)
+        assert_equal(A @ x, A.toarray() @ x)
+
+    def test_bsr_matvecs(self):
+        A = self.bsr_container(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5))
+        x = arange(A.shape[1]*6).reshape(-1,6)
+        assert_equal(A @ x, A.toarray() @ x)
+
+    @pytest.mark.xfail(run=False, reason='BSR does not have a __getitem__')
+    def test_iterator(self):
+        pass
+
+    @pytest.mark.xfail(run=False, reason='BSR does not have a __setitem__')
+    def test_setdiag(self):
+        pass
+
+    def test_resize_blocked(self):
+        # test resize() with non-(1,1) blocksize
+        D = np.array([[1, 0, 3, 4],
+                      [2, 0, 0, 0],
+                      [3, 0, 0, 0]])
+        S = self.spcreator(D, blocksize=(1, 2))
+        assert_(S.resize((3, 2)) is None)
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [3, 0]])
+        S.resize((2, 2))
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0]])
+        S.resize((3, 2))
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [0, 0]])
+        S.resize((3, 4))
+        assert_array_equal(S.toarray(), [[1, 0, 0, 0],
+                                         [2, 0, 0, 0],
+                                         [0, 0, 0, 0]])
+        assert_raises(ValueError, S.resize, (2, 3))
+
+    @pytest.mark.xfail(run=False, reason='BSR does not have a __setitem__')
+    def test_setdiag_comprehensive(self):
+        pass
+
+    @pytest.mark.skipif(IS_COLAB, reason="exceeds memory limit")
+    def test_scalar_idx_dtype(self):
+        # Check that index dtype takes into account all parameters
+        # passed to sparsetools, including the scalar ones
+        indptr = np.zeros(2, dtype=np.int32)
+        indices = np.zeros(0, dtype=np.int32)
+        vals = np.zeros((0, 1, 1))
+        a = self.bsr_container((vals, indices, indptr), shape=(1, 2**31-1))
+        b = self.bsr_container((vals, indices, indptr), shape=(1, 2**31))
+        c = self.bsr_container((1, 2**31-1))
+        d = self.bsr_container((1, 2**31))
+        assert_equal(a.indptr.dtype, np.int32)
+        assert_equal(b.indptr.dtype, np.int64)
+        assert_equal(c.indptr.dtype, np.int32)
+        assert_equal(d.indptr.dtype, np.int64)
+
+        try:
+            vals2 = np.zeros((0, 1, 2**31-1))
+            vals3 = np.zeros((0, 1, 2**31))
+            e = self.bsr_container((vals2, indices, indptr), shape=(1, 2**31-1))
+            f = self.bsr_container((vals3, indices, indptr), shape=(1, 2**31))
+            assert_equal(e.indptr.dtype, np.int32)
+            assert_equal(f.indptr.dtype, np.int64)
+        except (MemoryError, ValueError):
+            # May fail on 32-bit Python
+            e = 0
+            f = 0
+
+        # These shouldn't fail
+        for x in [a, b, c, d, e, f]:
+            x + x
+
+
+class TestBSRMatrix(_MatrixMixin, TestBSR):
+    spcreator = bsr_matrix
+
+
+TestBSR.init_class()
+TestBSRMatrix.init_class()
+
+
+#------------------------------------------------------------------------------
+# Tests for non-canonical representations (with duplicates, unsorted indices)
+#------------------------------------------------------------------------------
+
+def _same_sum_duplicate(data, *inds, **kwargs):
+    """Duplicates entries to produce the same matrix"""
+    indptr = kwargs.pop('indptr', None)
+    if np.issubdtype(data.dtype, np.bool_) or \
+       np.issubdtype(data.dtype, np.unsignedinteger):
+        if indptr is None:
+            return (data,) + inds
+        else:
+            return (data,) + inds + (indptr,)
+
+    zeros_pos = (data == 0).nonzero()
+
+    # duplicate data
+    data = data.repeat(2, axis=0)
+    data[::2] -= 1
+    data[1::2] = 1
+
+    # don't spoil all explicit zeros
+    if zeros_pos[0].size > 0:
+        pos = tuple(p[0] for p in zeros_pos)
+        pos1 = (2*pos[0],) + pos[1:]
+        pos2 = (2*pos[0]+1,) + pos[1:]
+        data[pos1] = 0
+        data[pos2] = 0
+
+    inds = tuple(indices.repeat(2) for indices in inds)
+
+    if indptr is None:
+        return (data,) + inds
+    else:
+        return (data,) + inds + (indptr * 2,)
+
+
+class _NonCanonicalMixin:
+    def spcreator(self, D, *args, sorted_indices=False, **kwargs):
+        """Replace D with a non-canonical equivalent: containing
+        duplicate elements and explicit zeros"""
+        construct = super().spcreator
+        M = construct(D, *args, **kwargs)
+
+        zero_pos = (M.toarray() == 0).nonzero()
+        has_zeros = (zero_pos[0].size > 0)
+        if has_zeros:
+            k = zero_pos[0].size//2
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                M = self._insert_explicit_zero(M, zero_pos[0][k], zero_pos[1][k])
+
+        arg1 = self._arg1_for_noncanonical(M, sorted_indices)
+        if 'shape' not in kwargs:
+            kwargs['shape'] = M.shape
+        NC = construct(arg1, **kwargs)
+
+        # check that result is valid
+        if NC.dtype in [np.float32, np.complex64]:
+            # For single-precision floats, the differences between M and NC
+            # that are introduced by the extra operations involved in the
+            # construction of NC necessitate a more lenient tolerance level
+            # than the default.
+            rtol = 1e-05
+        else:
+            rtol = 1e-07
+        assert_allclose(NC.toarray(), M.toarray(), rtol=rtol)
+
+        # check that at least one explicit zero
+        if has_zeros:
+            assert_((NC.data == 0).any())
+        # TODO check that NC has duplicates (which are not explicit zeros)
+
+        return NC
+
+    @pytest.mark.skip(reason='bool(matrix) counts explicit zeros')
+    def test_bool(self):
+        pass
+
+    @pytest.mark.skip(reason='getnnz-axis counts explicit zeros')
+    def test_getnnz_axis(self):
+        pass
+
+    @pytest.mark.skip(reason='nnz counts explicit zeros')
+    def test_empty(self):
+        pass
+
+
+class _NonCanonicalCompressedMixin(_NonCanonicalMixin):
+    def _arg1_for_noncanonical(self, M, sorted_indices=False):
+        """Return non-canonical constructor arg1 equivalent to M"""
+        data, indices, indptr = _same_sum_duplicate(M.data, M.indices,
+                                                    indptr=M.indptr)
+        if not sorted_indices:
+            for start, stop in zip(indptr, indptr[1:]):
+                indices[start:stop] = indices[start:stop][::-1].copy()
+                data[start:stop] = data[start:stop][::-1].copy()
+        return data, indices, indptr
+
+    def _insert_explicit_zero(self, M, i, j):
+        M[i,j] = 0
+        return M
+
+
+class _NonCanonicalCSMixin(_NonCanonicalCompressedMixin):
+    def test_getelement(self):
+        def check(dtype, sorted_indices):
+            D = array([[1,0,0],
+                       [4,3,0],
+                       [0,2,0],
+                       [0,0,0]], dtype=dtype)
+            A = self.spcreator(D, sorted_indices=sorted_indices)
+
+            M,N = D.shape
+
+            for i in range(-M, M):
+                for j in range(-N, N):
+                    assert_equal(A[i,j], D[i,j])
+
+            for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1), (1, 2, 3)]:
+                assert_raises((IndexError, TypeError), A.__getitem__, ij)
+
+        for dtype in supported_dtypes:
+            for sorted_indices in [False, True]:
+                check(np.dtype(dtype), sorted_indices)
+
+    def test_setitem_sparse(self):
+        D = np.eye(3)
+        A = self.spcreator(D)
+        B = self.spcreator([[1,2,3]])
+
+        D[1,:] = B.toarray()
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            A[1,:] = B
+        assert_array_equal(A.toarray(), D)
+
+        D[:,2] = B.toarray().ravel()
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            A[:,2] = B.T
+        assert_array_equal(A.toarray(), D)
+
+    @pytest.mark.xfail(run=False, reason='inverse broken with non-canonical matrix')
+    def test_inv(self):
+        pass
+
+    @pytest.mark.xfail(run=False, reason='solve broken with non-canonical matrix')
+    def test_solve(self):
+        pass
+
+
+class TestCSRNonCanonical(_NonCanonicalCSMixin, TestCSR):
+    pass
+
+
+class TestCSRNonCanonicalMatrix(TestCSRNonCanonical, TestCSRMatrix):
+    pass
+
+
+class TestCSCNonCanonical(_NonCanonicalCSMixin, TestCSC):
+    pass
+
+
+class TestCSCNonCanonicalMatrix(TestCSCNonCanonical, TestCSCMatrix):
+    pass
+
+
+class TestBSRNonCanonical(_NonCanonicalCompressedMixin, TestBSR):
+    def _insert_explicit_zero(self, M, i, j):
+        x = M.tocsr()
+        x[i,j] = 0
+        return x.tobsr(blocksize=M.blocksize)
+
+    @pytest.mark.xfail(run=False, reason='diagonal broken with non-canonical BSR')
+    def test_diagonal(self):
+        pass
+
+    @pytest.mark.xfail(run=False, reason='expm broken with non-canonical BSR')
+    def test_expm(self):
+        pass
+
+
+class TestBSRNonCanonicalMatrix(TestBSRNonCanonical, TestBSRMatrix):
+    pass
+
+
+class TestCOONonCanonical(_NonCanonicalMixin, TestCOO):
+    def _arg1_for_noncanonical(self, M, sorted_indices=None):
+        """Return non-canonical constructor arg1 equivalent to M"""
+        data, row, col = _same_sum_duplicate(M.data, M.row, M.col)
+        return data, (row, col)
+
+    def _insert_explicit_zero(self, M, i, j):
+        M.data = np.r_[M.data.dtype.type(0), M.data]
+        M.row = np.r_[M.row.dtype.type(i), M.row]
+        M.col = np.r_[M.col.dtype.type(j), M.col]
+        return M
+
+    def test_setdiag_noncanonical(self):
+        m = self.spcreator(np.eye(3))
+        m.sum_duplicates()
+        m.setdiag([3, 2], k=1)
+        m.sum_duplicates()
+        assert_(np.all(np.diff(m.col) >= 0))
+
+
+class TestCOONonCanonicalMatrix(TestCOONonCanonical, TestCOOMatrix):
+    pass
+
+
+#Todo: Revisit 64bit tests: avoid rerun of all tests for each version of get_index_dtype
+def cases_64bit(sp_api):
+    """Yield all tests for all formats that use get_index_dtype
+
+    This is more than testing get_index_dtype. It allows checking whether upcasting
+    or downcasting the index dtypes affects test results. The approach used here
+    does not try to figure out which tests might fail due to 32/64-bit issues.
+    We just run them all.
+    So, each test method in that uses cases_64bit reruns most of the test suite!
+    """
+    if sp_api == "sparray":
+        TEST_CLASSES = [TestBSR, TestCOO, TestCSC, TestCSR, TestDIA,
+                         # lil/dok->other conversion operations use get_index_dtype
+                         # so we include lil & dok test suite even though they do not
+                         # use get_index_dtype within the class. That means many of
+                         # these tests are superfluous, but it's hard to pick which
+                         TestDOK, TestLIL
+                        ]
+    elif sp_api == "spmatrix":
+        TEST_CLASSES = [TestBSRMatrix, TestCOOMatrix, TestCSCMatrix,
+                         TestCSRMatrix, TestDIAMatrix,
+                         # lil/dok->other conversion operations use get_index_dtype
+                         TestDOKMatrix, TestLILMatrix
+                        ]
+    else:
+        raise ValueError(f"parameter {sp_api=} is not one of 'sparray' or 'spmatrix'")
+
+    # The following features are missing, so skip the tests:
+    SKIP_TESTS = {
+        'test_expm': 'expm for 64-bit indices not available',
+        'test_inv': 'linsolve for 64-bit indices not available',
+        'test_solve': 'linsolve for 64-bit indices not available',
+        'test_scalar_idx_dtype': 'test implemented in base class',
+        'test_large_dimensions_reshape': 'test actually requires 64-bit to work',
+        'test_constructor_smallcol': 'test verifies int32 indexes',
+        'test_constructor_largecol': 'test verifies int64 indexes',
+        'test_tocoo_tocsr_tocsc_gh19245': 'test verifies int32 indexes',
+    }
+
+    for cls in TEST_CLASSES:
+        for method_name in sorted(dir(cls)):
+            method = getattr(cls, method_name)
+            if (method_name.startswith('test_') and
+                    not getattr(method, 'slow', False)):
+                marks = []
+
+                msg = SKIP_TESTS.get(method_name)
+                if bool(msg):
+                    marks += [pytest.mark.skip(reason=msg)]
+
+                markers = getattr(method, 'pytestmark', [])
+                for mark in markers:
+                    if mark.name in ('skipif', 'skip', 'xfail', 'xslow'):
+                        marks.append(mark)
+
+                yield pytest.param(cls, method_name, marks=marks)
+
+
+class Test64Bit:
+    # classes that use get_index_dtype
+    MAT_CLASSES = [
+        bsr_matrix, coo_matrix, csc_matrix, csr_matrix, dia_matrix,
+        bsr_array, coo_array, csc_array, csr_array, dia_array,
+    ]
+
+    def _compare_index_dtype(self, m, dtype):
+        dtype = np.dtype(dtype)
+        if m.format in ['csc', 'csr', 'bsr']:
+            return (m.indices.dtype == dtype) and (m.indptr.dtype == dtype)
+        elif m.format == 'coo':
+            return (m.row.dtype == dtype) and (m.col.dtype == dtype)
+        elif m.format == 'dia':
+            return (m.offsets.dtype == dtype)
+        else:
+            raise ValueError(f"matrix {m!r} has no integer indices")
+
+    @pytest.mark.thread_unsafe
+    def test_decorator_maxval_limit(self):
+        # Test that the with_64bit_maxval_limit decorator works
+
+        @with_64bit_maxval_limit(maxval_limit=10)
+        def check(mat_cls):
+            m = mat_cls(np.random.rand(10, 1))
+            assert_(self._compare_index_dtype(m, np.int32))
+            m = mat_cls(np.random.rand(11, 1))
+            assert_(self._compare_index_dtype(m, np.int64))
+
+        for mat_cls in self.MAT_CLASSES:
+            check(mat_cls)
+
+    @pytest.mark.thread_unsafe
+    def test_decorator_maxval_random(self):
+        # Test that the with_64bit_maxval_limit decorator works (2)
+
+        @with_64bit_maxval_limit(random=True)
+        def check(mat_cls):
+            seen_32 = False
+            seen_64 = False
+            for k in range(100):
+                m = mat_cls(np.random.rand(9, 9))
+                seen_32 = seen_32 or self._compare_index_dtype(m, np.int32)
+                seen_64 = seen_64 or self._compare_index_dtype(m, np.int64)
+                if seen_32 and seen_64:
+                    break
+            else:
+                raise AssertionError("both 32 and 64 bit indices not seen")
+
+        for mat_cls in self.MAT_CLASSES:
+            check(mat_cls)
+
+    @pytest.mark.thread_unsafe
+    def test_downcast_intp(self):
+        # Check that bincount and ufunc.reduceat intp downcasts are
+        # dealt with. The point here is to trigger points in the code
+        # that can fail on 32-bit systems when using 64-bit indices,
+        # due to use of functions that only work with intp-size
+        # indices.
+
+        @with_64bit_maxval_limit(fixed_dtype=np.int64, downcast_maxval=1)
+        def check_limited(csc_container, csr_container, coo_container):
+            # These involve indices larger than `downcast_maxval`
+            a = csc_container([[1, 2], [3, 4], [5, 6]])
+            assert_raises(AssertionError, a.count_nonzero, axis=1)
+            assert_raises(AssertionError, a.sum, axis=0)
+
+            a = csr_container([[1, 2, 3], [3, 4, 6]])
+            assert_raises(AssertionError, a.count_nonzero, axis=0)
+            assert_raises(AssertionError, a.sum, axis=1)
+
+            a = coo_container([[1, 2, 3], [3, 4, 5]])
+            assert_raises(AssertionError, a.count_nonzero, axis=0)
+            a.has_canonical_format = False
+            assert_raises(AssertionError, a.sum_duplicates)
+
+        @with_64bit_maxval_limit(fixed_dtype=np.int64)
+        def check_unlimited(csc_container, csr_container, coo_container):
+            # These involve indices smaller than `downcast_maxval`
+            a = csc_container([[1, 2], [3, 4], [5, 6]])
+            a.count_nonzero(axis=1)
+            a.sum(axis=0)
+
+            a = csr_container([[1, 2, 3], [3, 4, 6]])
+            a.count_nonzero(axis=0)
+            a.sum(axis=1)
+
+            a = coo_container([[1, 2, 3], [3, 4, 5]])
+            a.count_nonzero(axis=0)
+            a.has_canonical_format = False
+            a.sum_duplicates()
+
+        check_limited(csc_array, csr_array, coo_array)
+        check_unlimited(csc_array, csr_array, coo_array)
+        check_limited(csc_matrix, csr_matrix, coo_matrix)
+        check_unlimited(csc_matrix, csr_matrix, coo_matrix)
+
+
+# Testing both spmatrices and sparrays for 64bit index dtype handling is
+# expensive and double-checks the same code (e.g. _coobase)
+class RunAll64Bit:
+    def _check_resiliency(self, cls, method_name, **kw):
+        # Resiliency test, to check that sparse matrices deal reasonably
+        # with varying index data types.
+
+        @with_64bit_maxval_limit(**kw)
+        def check(cls, method_name):
+            instance = cls()
+            if hasattr(instance, 'setup_method'):
+                instance.setup_method()
+            try:
+                getattr(instance, method_name)()
+            finally:
+                if hasattr(instance, 'teardown_method'):
+                    instance.teardown_method()
+
+        check(cls, method_name)
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.slow
+class Test64BitArray(RunAll64Bit):
+    # inheritance of pytest test classes does not separate marks for subclasses.
+    # So we define these functions in both Array and Matrix versions.
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray"))
+    def test_resiliency_limit_10(self, cls, method_name):
+        self._check_resiliency(cls, method_name, maxval_limit=10)
+
+    @pytest.mark.fail_slow(2)
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray"))
+    def test_resiliency_random(self, cls, method_name):
+        # bsr_array.eliminate_zeros relies on csr_array constructor
+        # not making copies of index arrays --- this is not
+        # necessarily true when we pick the index data type randomly
+        self._check_resiliency(cls, method_name, random=True)
+
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray"))
+    def test_resiliency_all_32(self, cls, method_name):
+        self._check_resiliency(cls, method_name, fixed_dtype=np.int32)
+
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray"))
+    def test_resiliency_all_64(self, cls, method_name):
+        self._check_resiliency(cls, method_name, fixed_dtype=np.int64)
+
+
+@pytest.mark.thread_unsafe
+class Test64BitMatrix(RunAll64Bit):
+    # assert_32bit=True only for spmatrix cuz sparray does not check index content
+    @pytest.mark.fail_slow(5)
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_no_64(self, cls, method_name):
+        self._check_resiliency(cls, method_name, assert_32bit=True)
+
+    # inheritance of pytest test classes does not separate marks for subclasses.
+    # So we define these functions in both Array and Matrix versions.
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_resiliency_limit_10(self, cls, method_name):
+        self._check_resiliency(cls, method_name, maxval_limit=10)
+
+    @pytest.mark.fail_slow(2)
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_resiliency_random(self, cls, method_name):
+        # bsr_array.eliminate_zeros relies on csr_array constructor
+        # not making copies of index arrays --- this is not
+        # necessarily true when we pick the index data type randomly
+        self._check_resiliency(cls, method_name, random=True)
+
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_resiliency_all_32(self, cls, method_name):
+        self._check_resiliency(cls, method_name, fixed_dtype=np.int32)
+
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_resiliency_all_64(self, cls, method_name):
+        self._check_resiliency(cls, method_name, fixed_dtype=np.int64)
+
+def test_broadcast_to():
+    a = np.array([[1, 0, 2]])
+    b = np.array([[1], [0], [2]])
+    c = np.array([[1, 0, 2], [0, 3, 0]])
+    d = np.array([[7]])
+    e = np.array([[0]])
+    f = np.array([[0,0,0,0]])
+    for container in (csc_matrix, csc_array, csr_matrix, csr_array):
+        res_a = container(a)._broadcast_to((2,3))
+        res_b = container(b)._broadcast_to((3,4))
+        res_c = container(c)._broadcast_to((2,3))
+        res_d = container(d)._broadcast_to((4,4))
+        res_e = container(e)._broadcast_to((5,6))
+        res_f = container(f)._broadcast_to((2,4))
+        assert_array_equal(res_a.toarray(), np.broadcast_to(a, (2,3)))
+        assert_array_equal(res_b.toarray(), np.broadcast_to(b, (3,4)))
+        assert_array_equal(res_c.toarray(), c)
+        assert_array_equal(res_d.toarray(), np.broadcast_to(d, (4,4)))
+        assert_array_equal(res_e.toarray(), np.broadcast_to(e, (5,6)))
+        assert_array_equal(res_f.toarray(), np.broadcast_to(f, (2,4)))
+
+        with pytest.raises(ValueError, match="cannot be broadcast"):
+            container([[1, 2, 0], [3, 0, 1]])._broadcast_to(shape=(2, 1))
+
+        with pytest.raises(ValueError, match="cannot be broadcast"):
+            container([[0, 1, 2]])._broadcast_to(shape=(3, 2))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab091f7c8fccc42c6d9c6c249e59b1d5e9c326b8
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py
@@ -0,0 +1,447 @@
+"""Test of 1D aspects of sparse array classes"""
+
+import pytest
+
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+
+from scipy.sparse import (
+        bsr_array, csc_array, dia_array, lil_array,
+        coo_array, csr_array, dok_array,
+    )
+from scipy.sparse._sputils import supported_dtypes, matrix
+from scipy._lib._util import ComplexWarning
+
+
+sup_complex = np.testing.suppress_warnings()
+sup_complex.filter(ComplexWarning)
+
+
+spcreators = [coo_array, csr_array, dok_array]
+math_dtypes = [np.int64, np.float64, np.complex128]
+
+
+@pytest.fixture
+def dat1d():
+    return np.array([3, 0, 1, 0], 'd')
+
+
+@pytest.fixture
+def datsp_math_dtypes(dat1d):
+    dat_dtypes = {dtype: dat1d.astype(dtype) for dtype in math_dtypes}
+    return {
+        spcreator: [(dtype, dat, spcreator(dat)) for dtype, dat in dat_dtypes.items()]
+        for spcreator in spcreators
+    }
+
+
+# Test init with 1D dense input
+# sparrays which do not plan to support 1D
+@pytest.mark.parametrize("spcreator", [bsr_array, csc_array, dia_array, lil_array])
+def test_no_1d_support_in_init(spcreator):
+    with pytest.raises(ValueError, match="arrays don't support 1D input"):
+        spcreator([0, 1, 2, 3])
+
+
+# Test init with nD dense input
+# sparrays which do not yet support nD
+@pytest.mark.parametrize(
+    "spcreator", [csr_array, dok_array, bsr_array, csc_array, dia_array, lil_array]
+)
+def test_no_nd_support_in_init(spcreator):
+    with pytest.raises(ValueError, match="arrays don't.*support 3D"):
+        spcreator(np.ones((3, 2, 4)))
+
+
+# Main tests class
+@pytest.mark.parametrize("spcreator", spcreators)
+class TestCommon1D:
+    """test common functionality shared by 1D sparse formats"""
+
+    def test_create_empty(self, spcreator):
+        assert_equal(spcreator((3,)).toarray(), np.zeros(3))
+        assert_equal(spcreator((3,)).nnz, 0)
+        assert_equal(spcreator((3,)).count_nonzero(), 0)
+
+    def test_invalid_shapes(self, spcreator):
+        with pytest.raises(ValueError, match='elements cannot be negative'):
+            spcreator((-3,))
+
+    def test_repr(self, spcreator, dat1d):
+        repr(spcreator(dat1d))
+
+    def test_str(self, spcreator, dat1d):
+        str(spcreator(dat1d))
+
+    def test_neg(self, spcreator):
+        A = np.array([-1, 0, 17, 0, -5, 0, 1, -4, 0, 0, 0, 0], 'd')
+        assert_equal(-A, (-spcreator(A)).toarray())
+
+    def test_1d_supported_init(self, spcreator):
+        A = spcreator([0, 1, 2, 3])
+        assert A.ndim == 1
+
+    def test_reshape_1d_tofrom_row_or_column(self, spcreator):
+        # add a dimension 1d->2d
+        x = spcreator([1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5])
+        y = x.reshape(1, 12)
+        desired = [[1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5]]
+        assert_equal(y.toarray(), desired)
+
+        # remove a size-1 dimension 2d->1d
+        x = spcreator(desired)
+        y = x.reshape(12)
+        assert_equal(y.toarray(), desired[0])
+        y2 = x.reshape((12,))
+        assert y.shape == y2.shape
+
+        # make a 2d column into 1d. 2d->1d
+        y = x.T.reshape(12)
+        assert_equal(y.toarray(), desired[0])
+
+    def test_reshape(self, spcreator):
+        x = spcreator([1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5])
+        y = x.reshape((4, 3))
+        desired = [[1, 0, 7], [0, 0, 0], [0, -3, 0], [0, 0, 5]]
+        assert_equal(y.toarray(), desired)
+
+        y = x.reshape((12,))
+        assert y is x
+
+        y = x.reshape(12)
+        assert_equal(y.toarray(), x.toarray())
+
+    def test_sum(self, spcreator):
+        np.random.seed(1234)
+        dat_1 = np.array([0, 1, 2, 3, -4, 5, -6, 7, 9])
+        dat_2 = np.random.rand(5)
+        dat_3 = np.array([])
+        dat_4 = np.zeros((40,))
+        arrays = [dat_1, dat_2, dat_3, dat_4]
+
+        for dat in arrays:
+            datsp = spcreator(dat)
+            with np.errstate(over='ignore'):
+                assert np.isscalar(datsp.sum())
+                assert_allclose(dat.sum(), datsp.sum())
+                assert_allclose(dat.sum(axis=None), datsp.sum(axis=None))
+                assert_allclose(dat.sum(axis=0), datsp.sum(axis=0))
+                assert_allclose(dat.sum(axis=-1), datsp.sum(axis=-1))
+
+        # test `out` parameter
+        datsp.sum(axis=0, out=np.zeros(()))
+
+    def test_sum_invalid_params(self, spcreator):
+        out = np.zeros((3,))  # wrong size for out
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        with pytest.raises(ValueError, match='axis must be None, -1 or 0'):
+            datsp.sum(axis=1)
+        with pytest.raises(TypeError, match='Tuples are not accepted'):
+            datsp.sum(axis=(0, 1))
+        with pytest.raises(TypeError, match='axis must be an integer'):
+            datsp.sum(axis=1.5)
+        with pytest.raises(ValueError, match='output parameter.*wrong.*dimension'):
+            datsp.sum(axis=0, out=out)
+
+    def test_numpy_sum(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        dat_sum = np.sum(dat)
+        datsp_sum = np.sum(datsp)
+
+        assert_allclose(dat_sum, datsp_sum)
+
+    def test_mean(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        assert_allclose(dat.mean(), datsp.mean())
+        assert np.isscalar(datsp.mean(axis=None))
+        assert_allclose(dat.mean(axis=None), datsp.mean(axis=None))
+        assert_allclose(dat.mean(axis=0), datsp.mean(axis=0))
+        assert_allclose(dat.mean(axis=-1), datsp.mean(axis=-1))
+
+        with pytest.raises(ValueError, match='axis'):
+            datsp.mean(axis=1)
+        with pytest.raises(ValueError, match='axis'):
+            datsp.mean(axis=-2)
+
+    def test_mean_invalid_params(self, spcreator):
+        out = np.asarray(np.zeros((1, 3)))
+        dat = np.array([[0, 1, 2], [3, -4, 5], [-6, 7, 9]])
+
+        datsp = spcreator(dat)
+        with pytest.raises(ValueError, match='axis out of range'):
+            datsp.mean(axis=3)
+        with pytest.raises(TypeError, match='Tuples are not accepted'):
+            datsp.mean(axis=(0, 1))
+        with pytest.raises(TypeError, match='axis must be an integer'):
+            datsp.mean(axis=1.5)
+        with pytest.raises(ValueError, match='output parameter.*wrong.*dimension'):
+            datsp.mean(axis=1, out=out)
+
+    def test_sum_dtype(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        for dtype in supported_dtypes:
+            dat_sum = dat.sum(dtype=dtype)
+            datsp_sum = datsp.sum(dtype=dtype)
+
+            assert_allclose(dat_sum, datsp_sum)
+            assert_equal(dat_sum.dtype, datsp_sum.dtype)
+
+    def test_mean_dtype(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        for dtype in supported_dtypes:
+            dat_mean = dat.mean(dtype=dtype)
+            datsp_mean = datsp.mean(dtype=dtype)
+
+            assert_allclose(dat_mean, datsp_mean)
+            assert_equal(dat_mean.dtype, datsp_mean.dtype)
+
+    def test_mean_out(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        dat_out = np.array(0)
+        datsp_out = np.array(0)
+
+        dat.mean(out=dat_out)
+        datsp.mean(out=datsp_out)
+        assert_allclose(dat_out, datsp_out)
+
+        dat.mean(axis=0, out=dat_out)
+        datsp.mean(axis=0, out=datsp_out)
+        assert_allclose(dat_out, datsp_out)
+
+        with pytest.raises(ValueError, match="output parameter.*dimension"):
+            datsp.mean(out=np.array([0]))
+        with pytest.raises(ValueError, match="output parameter.*dimension"):
+            datsp.mean(out=np.array([[0]]))
+
+    def test_numpy_mean(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        dat_mean = np.mean(dat)
+        datsp_mean = np.mean(datsp)
+
+        assert_allclose(dat_mean, datsp_mean)
+        assert_equal(dat_mean.dtype, datsp_mean.dtype)
+
+    @pytest.mark.thread_unsafe
+    @sup_complex
+    def test_from_array(self, spcreator):
+        A = np.array([2, 3, 4])
+        assert_equal(spcreator(A).toarray(), A)
+
+        A = np.array([1.0 + 3j, 0, -1])
+        assert_equal(spcreator(A).toarray(), A)
+        assert_equal(spcreator(A, dtype='int16').toarray(), A.astype('int16'))
+
+    @pytest.mark.thread_unsafe
+    @sup_complex
+    def test_from_list(self, spcreator):
+        A = [2, 3, 4]
+        assert_equal(spcreator(A).toarray(), A)
+
+        A = [1.0 + 3j, 0, -1]
+        assert_equal(spcreator(A).toarray(), np.array(A))
+        assert_equal(
+            spcreator(A, dtype='int16').toarray(), np.array(A).astype('int16')
+        )
+
+    @pytest.mark.thread_unsafe
+    @sup_complex
+    def test_from_sparse(self, spcreator):
+        D = np.array([1, 0, 0])
+        S = coo_array(D)
+        assert_equal(spcreator(S).toarray(), D)
+        S = spcreator(D)
+        assert_equal(spcreator(S).toarray(), D)
+
+        D = np.array([1.0 + 3j, 0, -1])
+        S = coo_array(D)
+        assert_equal(spcreator(S).toarray(), D)
+        assert_equal(spcreator(S, dtype='int16').toarray(), D.astype('int16'))
+        S = spcreator(D)
+        assert_equal(spcreator(S).toarray(), D)
+        assert_equal(spcreator(S, dtype='int16').toarray(), D.astype('int16'))
+
+    def test_toarray(self, spcreator, dat1d):
+        datsp = spcreator(dat1d)
+        # Check C- or F-contiguous (default).
+        chk = datsp.toarray()
+        assert_equal(chk, dat1d)
+        assert chk.flags.c_contiguous == chk.flags.f_contiguous
+
+        # Check C-contiguous (with arg).
+        chk = datsp.toarray(order='C')
+        assert_equal(chk, dat1d)
+        assert chk.flags.c_contiguous
+        assert chk.flags.f_contiguous
+
+        # Check F-contiguous (with arg).
+        chk = datsp.toarray(order='F')
+        assert_equal(chk, dat1d)
+        assert chk.flags.c_contiguous
+        assert chk.flags.f_contiguous
+
+        # Check with output arg.
+        out = np.zeros(datsp.shape, dtype=datsp.dtype)
+        datsp.toarray(out=out)
+        assert_equal(out, dat1d)
+
+        # Check that things are fine when we don't initialize with zeros.
+        out[...] = 1.0
+        datsp.toarray(out=out)
+        assert_equal(out, dat1d)
+
+        # np.dot does not work with sparse matrices (unless scalars)
+        # so this is testing whether dat1d matches datsp.toarray()
+        a = np.array([1.0, 2.0, 3.0, 4.0])
+        dense_dot_dense = np.dot(a, dat1d)
+        check = np.dot(a, datsp.toarray())
+        assert_equal(dense_dot_dense, check)
+
+        b = np.array([1.0, 2.0, 3.0, 4.0])
+        dense_dot_dense = np.dot(dat1d, b)
+        check = np.dot(datsp.toarray(), b)
+        assert_equal(dense_dot_dense, check)
+
+        # Check bool data works.
+        spbool = spcreator(dat1d, dtype=bool)
+        arrbool = dat1d.astype(bool)
+        assert_equal(spbool.toarray(), arrbool)
+
+    def test_add(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            a = dat.copy()
+            a[0] = 2.0
+            b = datsp
+            c = b + a
+            assert_equal(c, b.toarray() + a)
+
+            # test broadcasting
+            # Note: cant add nonzero scalar to sparray. Can add len 1 array
+            c = b + a[0:1]
+            assert_equal(c, b.toarray() + a[0])
+
+    def test_radd(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            a = dat.copy()
+            a[0] = 2.0
+            b = datsp
+            c = a + b
+            assert_equal(c, a + b.toarray())
+
+    def test_rsub(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            assert_equal((dat - datsp), [0, 0, 0, 0])
+            assert_equal((datsp - dat), [0, 0, 0, 0])
+            assert_equal((0 - datsp).toarray(), -dat)
+
+            A = spcreator([1, -4, 0, 2], dtype='d')
+            assert_equal((dat - A), dat - A.toarray())
+            assert_equal((A - dat), A.toarray() - dat)
+            assert_equal(A.toarray() - datsp, A.toarray() - dat)
+            assert_equal(datsp - A.toarray(), dat - A.toarray())
+
+            # test broadcasting
+            assert_equal(dat[:1] - datsp, dat[:1] - dat)
+
+    def test_matmul_basic(self, spcreator):
+        A = np.array([[2, 0, 3.0], [0, 0, 0], [0, 1, 2]])
+        v = np.array([1, 0, 3])
+        Asp = spcreator(A)
+        vsp = spcreator(v)
+
+        # sparse result when both args are sparse and result not scalar
+        assert_equal((Asp @ vsp).toarray(), A @ v)
+        assert_equal(A @ vsp, A @ v)
+        assert_equal(Asp @ v, A @ v)
+        assert_equal((vsp @ Asp).toarray(), v @ A)
+        assert_equal(vsp @ A, v @ A)
+        assert_equal(v @ Asp, v @ A)
+
+        assert_equal(vsp @ vsp, v @ v)
+        assert_equal(v @ vsp, v @ v)
+        assert_equal(vsp @ v, v @ v)
+        assert_equal((Asp @ Asp).toarray(), A @ A)
+        assert_equal(A @ Asp, A @ A)
+        assert_equal(Asp @ A, A @ A)
+
+    def test_matvec(self, spcreator):
+        A = np.array([2, 0, 3.0])
+        Asp = spcreator(A)
+        col = np.array([[1, 2, 3]]).T
+
+        assert_allclose(Asp @ col, Asp.toarray() @ col)
+
+        assert (A @ np.array([1, 2, 3])).shape == ()
+        assert Asp @ np.array([1, 2, 3]) == 11
+        assert (Asp @ np.array([1, 2, 3])).shape == ()
+        assert (Asp @ np.array([[1], [2], [3]])).shape == (1,)
+        # check result type
+        assert isinstance(Asp @ matrix([[1, 2, 3]]).T, np.ndarray)
+
+        # ensure exception is raised for improper dimensions
+        bad_vecs = [np.array([1, 2]), np.array([1, 2, 3, 4]), np.array([[1], [2]])]
+        for x in bad_vecs:
+            with pytest.raises(ValueError, match='dimension mismatch'):
+                Asp @ x
+
+        # The current relationship between sparse matrix products and array
+        # products is as follows:
+        dot_result = np.dot(Asp.toarray(), [1, 2, 3])
+        assert_allclose(Asp @ np.array([1, 2, 3]), dot_result)
+        assert_allclose(Asp @ [[1], [2], [3]], dot_result.T)
+        # Note that the result of Asp @ x is dense if x has a singleton dimension.
+
+    def test_rmatvec(self, spcreator, dat1d):
+        M = spcreator(dat1d)
+        assert_allclose([1, 2, 3, 4] @ M, np.dot([1, 2, 3, 4], M.toarray()))
+        row = np.array([[1, 2, 3, 4]])
+        assert_allclose(row @ M, row @ M.toarray())
+
+    def test_transpose(self, spcreator, dat1d):
+        for A in [dat1d, np.array([])]:
+            B = spcreator(A)
+            assert_equal(B.toarray(), A)
+            assert_equal(B.transpose().toarray(), A)
+            assert_equal(B.dtype, A.dtype)
+
+    def test_add_dense_to_sparse(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            sum1 = dat + datsp
+            assert_equal(sum1, dat + dat)
+            sum2 = datsp + dat
+            assert_equal(sum2, dat + dat)
+
+    def test_iterator(self, spcreator):
+        # test that __iter__ is compatible with NumPy
+        B = np.arange(5)
+        A = spcreator(B)
+
+        if A.format not in ['coo', 'dia', 'bsr']:
+            for x, y in zip(A, B):
+                assert_equal(x, y)
+
+    def test_resize(self, spcreator):
+        # resize(shape) resizes the matrix in-place
+        D = np.array([1, 0, 3, 4])
+        S = spcreator(D)
+        assert S.resize((3,)) is None
+        assert_equal(S.toarray(), [1, 0, 3])
+        S.resize((5,))
+        assert_equal(S.toarray(), [1, 0, 3, 0, 0])
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..38b8288c39f4ebacd9cadc58bba7b18416377c73
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py
@@ -0,0 +1,872 @@
+"""test sparse matrix construction functions"""
+
+import numpy as np
+from numpy import array
+from numpy.testing import (assert_equal, assert_,
+        assert_array_equal, assert_array_almost_equal_nulp)
+import pytest
+from pytest import raises as assert_raises
+from scipy._lib._testutils import check_free_memory
+
+from scipy.sparse import (csr_matrix, coo_matrix,
+                          csr_array, coo_array,
+                          csc_array, bsr_array,
+                          dia_array, dok_array,
+                          lil_array, csc_matrix,
+                          bsr_matrix, dia_matrix,
+                          lil_matrix, sparray, spmatrix,
+                          _construct as construct)
+from scipy.sparse._construct import rand as sprand
+
+sparse_formats = ['csr','csc','coo','bsr','dia','lil','dok']
+
+#TODO check whether format=XXX is respected
+
+
+def _sprandn(m, n, density=0.01, format="coo", dtype=None, rng=None):
+    # Helper function for testing.
+    rng = np.random.default_rng(rng)
+    data_rvs = rng.standard_normal
+    return construct.random(m, n, density, format, dtype, rng, data_rvs)
+
+
+def _sprandn_array(m, n, density=0.01, format="coo", dtype=None, rng=None):
+    # Helper function for testing.
+    rng = np.random.default_rng(rng)
+    data_sampler = rng.standard_normal
+    return construct.random_array((m, n), density=density, format=format, dtype=dtype,
+                                  rng=rng, data_sampler=data_sampler)
+
+
+class TestConstructUtils:
+
+    @pytest.mark.parametrize("cls", [
+        csc_array, csr_array, coo_array, bsr_array,
+        dia_array, dok_array, lil_array
+    ])
+    def test_singleton_array_constructor(self, cls):
+        with pytest.raises(
+            ValueError,
+            match=(
+                'scipy sparse array classes do not support '
+                'instantiation from a scalar'
+            )
+        ):
+            cls(0)
+
+    @pytest.mark.parametrize("cls", [
+        csc_matrix, csr_matrix, coo_matrix,
+        bsr_matrix, dia_matrix, lil_matrix
+    ])
+    def test_singleton_matrix_constructor(self, cls):
+        """
+        This test is for backwards compatibility post scipy 1.13.
+        The behavior observed here is what is to be expected
+        with the older matrix classes. This test comes with the
+        exception of dok_matrix, which was not working pre scipy1.12
+        (unlike the rest of these).
+        """
+        assert cls(0).shape == (1, 1)
+
+    def test_spdiags(self):
+        diags1 = array([[1, 2, 3, 4, 5]])
+        diags2 = array([[1, 2, 3, 4, 5],
+                         [6, 7, 8, 9,10]])
+        diags3 = array([[1, 2, 3, 4, 5],
+                         [6, 7, 8, 9,10],
+                         [11,12,13,14,15]])
+
+        cases = []
+        cases.append((diags1, 0, 1, 1, [[1]]))
+        cases.append((diags1, [0], 1, 1, [[1]]))
+        cases.append((diags1, [0], 2, 1, [[1],[0]]))
+        cases.append((diags1, [0], 1, 2, [[1,0]]))
+        cases.append((diags1, [1], 1, 2, [[0,2]]))
+        cases.append((diags1,[-1], 1, 2, [[0,0]]))
+        cases.append((diags1, [0], 2, 2, [[1,0],[0,2]]))
+        cases.append((diags1,[-1], 2, 2, [[0,0],[1,0]]))
+        cases.append((diags1, [3], 2, 2, [[0,0],[0,0]]))
+        cases.append((diags1, [0], 3, 4, [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
+        cases.append((diags1, [1], 3, 4, [[0,2,0,0],[0,0,3,0],[0,0,0,4]]))
+        cases.append((diags1, [2], 3, 5, [[0,0,3,0,0],[0,0,0,4,0],[0,0,0,0,5]]))
+
+        cases.append((diags2, [0,2], 3, 3, [[1,0,8],[0,2,0],[0,0,3]]))
+        cases.append((diags2, [-1,0], 3, 4, [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
+        cases.append((diags2, [2,-3], 6, 6, [[0,0,3,0,0,0],
+                                              [0,0,0,4,0,0],
+                                              [0,0,0,0,5,0],
+                                              [6,0,0,0,0,0],
+                                              [0,7,0,0,0,0],
+                                              [0,0,8,0,0,0]]))
+
+        cases.append((diags3, [-1,0,1], 6, 6, [[6,12, 0, 0, 0, 0],
+                                                [1, 7,13, 0, 0, 0],
+                                                [0, 2, 8,14, 0, 0],
+                                                [0, 0, 3, 9,15, 0],
+                                                [0, 0, 0, 4,10, 0],
+                                                [0, 0, 0, 0, 5, 0]]))
+        cases.append((diags3, [-4,2,-1], 6, 5, [[0, 0, 8, 0, 0],
+                                                 [11, 0, 0, 9, 0],
+                                                 [0,12, 0, 0,10],
+                                                 [0, 0,13, 0, 0],
+                                                 [1, 0, 0,14, 0],
+                                                 [0, 2, 0, 0,15]]))
+        cases.append((diags3, [-1, 1, 2], len(diags3[0]), len(diags3[0]),
+                      [[0, 7, 13, 0, 0],
+                       [1, 0, 8, 14, 0],
+                       [0, 2, 0, 9, 15],
+                       [0, 0, 3, 0, 10],
+                       [0, 0, 0, 4, 0]]))
+
+        for d, o, m, n, result in cases:
+            if len(d[0]) == m and m == n:
+                assert_equal(construct.spdiags(d, o).toarray(), result)
+            assert_equal(construct.spdiags(d, o, m, n).toarray(), result)
+            assert_equal(construct.spdiags(d, o, (m, n)).toarray(), result)
+
+    def test_diags(self):
+        a = array([1, 2, 3, 4, 5])
+        b = array([6, 7, 8, 9, 10])
+        c = array([11, 12, 13, 14, 15])
+
+        cases = []
+        cases.append((a[:1], 0, (1, 1), [[1]]))
+        cases.append(([a[:1]], [0], (1, 1), [[1]]))
+        cases.append(([a[:1]], [0], (2, 1), [[1],[0]]))
+        cases.append(([a[:1]], [0], (1, 2), [[1,0]]))
+        cases.append(([a[:1]], [1], (1, 2), [[0,1]]))
+        cases.append(([a[:2]], [0], (2, 2), [[1,0],[0,2]]))
+        cases.append(([a[:1]],[-1], (2, 2), [[0,0],[1,0]]))
+        cases.append(([a[:3]], [0], (3, 4), [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
+        cases.append(([a[:3]], [1], (3, 4), [[0,1,0,0],[0,0,2,0],[0,0,0,3]]))
+        cases.append(([a[:1]], [-2], (3, 5), [[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0]]))
+        cases.append(([a[:2]], [-1], (3, 5), [[0,0,0,0,0],[1,0,0,0,0],[0,2,0,0,0]]))
+        cases.append(([a[:3]], [0], (3, 5), [[1,0,0,0,0],[0,2,0,0,0],[0,0,3,0,0]]))
+        cases.append(([a[:3]], [1], (3, 5), [[0,1,0,0,0],[0,0,2,0,0],[0,0,0,3,0]]))
+        cases.append(([a[:3]], [2], (3, 5), [[0,0,1,0,0],[0,0,0,2,0],[0,0,0,0,3]]))
+        cases.append(([a[:2]], [3], (3, 5), [[0,0,0,1,0],[0,0,0,0,2],[0,0,0,0,0]]))
+        cases.append(([a[:1]], [4], (3, 5), [[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0]]))
+        cases.append(([a[:1]], [-4], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[1,0,0]]))
+        cases.append(([a[:2]], [-3], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[1,0,0],[0,2,0]]))
+        cases.append(([a[:3]], [-2], (5, 3), [[0,0,0],[0,0,0],[1,0,0],[0,2,0],[0,0,3]]))
+        cases.append(([a[:3]], [-1], (5, 3), [[0,0,0],[1,0,0],[0,2,0],[0,0,3],[0,0,0]]))
+        cases.append(([a[:3]], [0], (5, 3), [[1,0,0],[0,2,0],[0,0,3],[0,0,0],[0,0,0]]))
+        cases.append(([a[:2]], [1], (5, 3), [[0,1,0],[0,0,2],[0,0,0],[0,0,0],[0,0,0]]))
+        cases.append(([a[:1]], [2], (5, 3), [[0,0,1],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]))
+
+        cases.append(([a[:3],b[:1]], [0,2], (3, 3), [[1,0,6],[0,2,0],[0,0,3]]))
+        cases.append(([a[:2],b[:3]], [-1,0], (3, 4), [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
+        cases.append(([a[:4],b[:3]], [2,-3], (6, 6), [[0,0,1,0,0,0],
+                                                     [0,0,0,2,0,0],
+                                                     [0,0,0,0,3,0],
+                                                     [6,0,0,0,0,4],
+                                                     [0,7,0,0,0,0],
+                                                     [0,0,8,0,0,0]]))
+
+        cases.append(([a[:4],b,c[:4]], [-1,0,1], (5, 5), [[6,11, 0, 0, 0],
+                                                            [1, 7,12, 0, 0],
+                                                            [0, 2, 8,13, 0],
+                                                            [0, 0, 3, 9,14],
+                                                            [0, 0, 0, 4,10]]))
+        cases.append(([a[:2],b[:3],c], [-4,2,-1], (6, 5), [[0, 0, 6, 0, 0],
+                                                          [11, 0, 0, 7, 0],
+                                                          [0,12, 0, 0, 8],
+                                                          [0, 0,13, 0, 0],
+                                                          [1, 0, 0,14, 0],
+                                                          [0, 2, 0, 0,15]]))
+
+        # too long arrays are OK
+        cases.append(([a], [0], (1, 1), [[1]]))
+        cases.append(([a[:3],b], [0,2], (3, 3), [[1, 0, 6], [0, 2, 0], [0, 0, 3]]))
+        cases.append((
+            np.array([[1, 2, 3], [4, 5, 6]]),
+            [0,-1],
+            (3, 3),
+            [[1, 0, 0], [4, 2, 0], [0, 5, 3]]
+        ))
+
+        # scalar case: broadcasting
+        cases.append(([1,-2,1], [1,0,-1], (3, 3), [[-2, 1, 0],
+                                                    [1, -2, 1],
+                                                    [0, 1, -2]]))
+
+        for d, o, shape, result in cases:
+            err_msg = f"{d!r} {o!r} {shape!r} {result!r}"
+            assert_equal(construct.diags(d, offsets=o, shape=shape).toarray(),
+                         result, err_msg=err_msg)
+
+            if (shape[0] == shape[1]
+                and hasattr(d[0], '__len__')
+                and len(d[0]) <= max(shape)):
+                # should be able to find the shape automatically
+                assert_equal(construct.diags(d, offsets=o).toarray(), result,
+                             err_msg=err_msg)
+
+    def test_diags_default(self):
+        a = array([1, 2, 3, 4, 5])
+        assert_equal(construct.diags(a).toarray(), np.diag(a))
+
+    def test_diags_default_bad(self):
+        a = array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
+        assert_raises(ValueError, construct.diags, a)
+
+    def test_diags_bad(self):
+        a = array([1, 2, 3, 4, 5])
+        b = array([6, 7, 8, 9, 10])
+        c = array([11, 12, 13, 14, 15])
+
+        cases = []
+        cases.append(([a[:0]], 0, (1, 1)))
+        cases.append(([a[:4],b,c[:3]], [-1,0,1], (5, 5)))
+        cases.append(([a[:2],c,b[:3]], [-4,2,-1], (6, 5)))
+        cases.append(([a[:2],c,b[:3]], [-4,2,-1], None))
+        cases.append(([], [-4,2,-1], None))
+        cases.append(([1], [-5], (4, 4)))
+        cases.append(([a], 0, None))
+
+        for d, o, shape in cases:
+            assert_raises(ValueError, construct.diags, d, offsets=o, shape=shape)
+
+        assert_raises(TypeError, construct.diags, [[None]], offsets=[0])
+
+    def test_diags_vs_diag(self):
+        # Check that
+        #
+        #    diags([a, b, ...], [i, j, ...]) == diag(a, i) + diag(b, j) + ...
+        #
+
+        rng = np.random.RandomState(1234)
+
+        for n_diags in [1, 2, 3, 4, 5, 10]:
+            n = 1 + n_diags//2 + rng.randint(0, 10)
+
+            offsets = np.arange(-n+1, n-1)
+            rng.shuffle(offsets)
+            offsets = offsets[:n_diags]
+
+            diagonals = [rng.rand(n - abs(q)) for q in offsets]
+
+            mat = construct.diags(diagonals, offsets=offsets)
+            dense_mat = sum([np.diag(x, j) for x, j in zip(diagonals, offsets)])
+
+            assert_array_almost_equal_nulp(mat.toarray(), dense_mat)
+
+            if len(offsets) == 1:
+                mat = construct.diags(diagonals[0], offsets=offsets[0])
+                dense_mat = np.diag(diagonals[0], offsets[0])
+                assert_array_almost_equal_nulp(mat.toarray(), dense_mat)
+
+    def test_diags_dtype(self):
+        x = construct.diags([2.2], offsets=[0], shape=(2, 2), dtype=int)
+        assert_equal(x.dtype, int)
+        assert_equal(x.toarray(), [[2, 0], [0, 2]])
+
+    def test_diags_one_diagonal(self):
+        d = list(range(5))
+        for k in range(-5, 6):
+            assert_equal(construct.diags(d, offsets=k).toarray(),
+                         construct.diags([d], offsets=[k]).toarray())
+
+    def test_diags_empty(self):
+        x = construct.diags([])
+        assert_equal(x.shape, (0, 0))
+
+    @pytest.mark.parametrize("identity", [construct.identity, construct.eye_array])
+    def test_identity(self, identity):
+        assert_equal(identity(1).toarray(), [[1]])
+        assert_equal(identity(2).toarray(), [[1,0],[0,1]])
+
+        I = identity(3, dtype='int8', format='dia')
+        assert_equal(I.dtype, np.dtype('int8'))
+        assert_equal(I.format, 'dia')
+
+        for fmt in sparse_formats:
+            I = identity(3, format=fmt)
+            assert_equal(I.format, fmt)
+            assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
+
+    @pytest.mark.parametrize("eye", [construct.eye, construct.eye_array])
+    def test_eye(self, eye):
+        assert_equal(eye(1,1).toarray(), [[1]])
+        assert_equal(eye(2,3).toarray(), [[1,0,0],[0,1,0]])
+        assert_equal(eye(3,2).toarray(), [[1,0],[0,1],[0,0]])
+        assert_equal(eye(3,3).toarray(), [[1,0,0],[0,1,0],[0,0,1]])
+
+        assert_equal(eye(3,3,dtype='int16').dtype, np.dtype('int16'))
+
+        for m in [3, 5]:
+            for n in [3, 5]:
+                for k in range(-5,6):
+                    # scipy.sparse.eye deviates from np.eye here. np.eye will
+                    # create arrays of all 0's when the diagonal offset is
+                    # greater than the size of the array. For sparse arrays
+                    # this makes less sense, especially as it results in dia
+                    # arrays with negative diagonals. Therefore sp.sparse.eye
+                    # validates that diagonal offsets fall within the shape of
+                    # the array. See gh-18555.
+                    if (k > 0 and k > n) or (k < 0 and abs(k) > m):
+                        with pytest.raises(
+                            ValueError, match="Offset.*out of bounds"
+                        ):
+                            eye(m, n, k=k)
+
+                    else:
+                        assert_equal(
+                            eye(m, n, k=k).toarray(),
+                            np.eye(m, n, k=k)
+                        )
+                        if m == n:
+                            assert_equal(
+                                eye(m, k=k).toarray(),
+                                np.eye(m, n, k=k)
+                            )
+
+    @pytest.mark.parametrize("eye", [construct.eye, construct.eye_array])
+    def test_eye_one(self, eye):
+        assert_equal(eye(1).toarray(), [[1]])
+        assert_equal(eye(2).toarray(), [[1,0],[0,1]])
+
+        I = eye(3, dtype='int8', format='dia')
+        assert_equal(I.dtype, np.dtype('int8'))
+        assert_equal(I.format, 'dia')
+
+        for fmt in sparse_formats:
+            I = eye(3, format=fmt)
+            assert_equal(I.format, fmt)
+            assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
+
+    def test_eye_array_vs_matrix(self):
+        assert isinstance(construct.eye_array(3), sparray)
+        assert not isinstance(construct.eye(3), sparray)
+
+    def test_kron(self):
+        cases = []
+
+        cases.append(array([[0]]))
+        cases.append(array([[-1]]))
+        cases.append(array([[4]]))
+        cases.append(array([[10]]))
+        cases.append(array([[0],[0]]))
+        cases.append(array([[0,0]]))
+        cases.append(array([[1,2],[3,4]]))
+        cases.append(array([[0,2],[5,0]]))
+        cases.append(array([[0,2,-6],[8,0,14]]))
+        cases.append(array([[5,4],[0,0],[6,0]]))
+        cases.append(array([[5,4,4],[1,0,0],[6,0,8]]))
+        cases.append(array([[0,1,0,2,0,5,8]]))
+        cases.append(array([[0.5,0.125,0,3.25],[0,2.5,0,0]]))
+
+        # test all cases with some formats
+        for a in cases:
+            ca = csr_array(a)
+            for b in cases:
+                cb = csr_array(b)
+                expected = np.kron(a, b)
+                for fmt in sparse_formats[1:4]:
+                    result = construct.kron(ca, cb, format=fmt)
+                    assert_equal(result.format, fmt)
+                    assert_array_equal(result.toarray(), expected)
+                    assert isinstance(result, sparray)
+
+        # test one case with all formats
+        a = cases[-1]
+        b = cases[-3]
+        ca = csr_array(a)
+        cb = csr_array(b)
+
+        expected = np.kron(a, b)
+        for fmt in sparse_formats:
+            result = construct.kron(ca, cb, format=fmt)
+            assert_equal(result.format, fmt)
+            assert_array_equal(result.toarray(), expected)
+            assert isinstance(result, sparray)
+
+        # check that spmatrix returned when both inputs are spmatrix
+        result = construct.kron(csr_matrix(a), csr_matrix(b), format=fmt)
+        assert_equal(result.format, fmt)
+        assert_array_equal(result.toarray(), expected)
+        assert isinstance(result, spmatrix)
+
+    def test_kron_ndim_exceptions(self):
+        with pytest.raises(ValueError, match='requires 2D input'):
+            construct.kron([[0], [1]], csr_array([0, 1]))
+        with pytest.raises(ValueError, match='requires 2D input'):
+            construct.kron(csr_array([0, 1]), [[0], [1]])
+        # no exception if sparse arrays are not input (spmatrix inferred)
+        construct.kron([[0], [1]], [0, 1])
+
+    def test_kron_large(self):
+        n = 2**16
+        a = construct.diags_array([1], shape=(1, n), offsets=n-1)
+        b = construct.diags_array([1], shape=(n, 1), offsets=1-n)
+
+        construct.kron(a, a)
+        construct.kron(b, b)
+
+    def test_kronsum(self):
+        cases = []
+
+        cases.append(array([[0]]))
+        cases.append(array([[-1]]))
+        cases.append(array([[4]]))
+        cases.append(array([[10]]))
+        cases.append(array([[1,2],[3,4]]))
+        cases.append(array([[0,2],[5,0]]))
+        cases.append(array([[0,2,-6],[8,0,14],[0,3,0]]))
+        cases.append(array([[1,0,0],[0,5,-1],[4,-2,8]]))
+
+        # test all cases with default format
+        for a in cases:
+            for b in cases:
+                result = construct.kronsum(csr_array(a), csr_array(b)).toarray()
+                expected = (np.kron(np.eye(b.shape[0]), a)
+                            + np.kron(b, np.eye(a.shape[0])))
+                assert_array_equal(result, expected)
+
+        # check that spmatrix returned when both inputs are spmatrix
+        result = construct.kronsum(csr_matrix(a), csr_matrix(b)).toarray()
+        assert_array_equal(result, expected)
+
+    def test_kronsum_ndim_exceptions(self):
+        with pytest.raises(ValueError, match='requires 2D input'):
+            construct.kronsum([[0], [1]], csr_array([0, 1]))
+        with pytest.raises(ValueError, match='requires 2D input'):
+            construct.kronsum(csr_array([0, 1]), [[0], [1]])
+        # no exception if sparse arrays are not input (spmatrix inferred)
+        construct.kronsum([[0, 1], [1, 0]], [2])
+
+    @pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array])
+    def test_vstack(self, coo_cls):
+        A = coo_cls([[1,2],[3,4]])
+        B = coo_cls([[5,6]])
+
+        expected = array([[1, 2],
+                          [3, 4],
+                          [5, 6]])
+        assert_equal(construct.vstack([A, B]).toarray(), expected)
+        assert_equal(construct.vstack([A, B], dtype=np.float32).dtype,
+                     np.float32)
+
+        assert_equal(construct.vstack([A.todok(), B.todok()]).toarray(), expected)
+
+        assert_equal(construct.vstack([A.tocsr(), B.tocsr()]).toarray(),
+                     expected)
+        result = construct.vstack([A.tocsr(), B.tocsr()],
+                                  format="csr", dtype=np.float32)
+        assert_equal(result.dtype, np.float32)
+        assert_equal(result.indices.dtype, np.int32)
+        assert_equal(result.indptr.dtype, np.int32)
+
+        assert_equal(construct.vstack([A.tocsc(), B.tocsc()]).toarray(),
+                     expected)
+        result = construct.vstack([A.tocsc(), B.tocsc()],
+                                  format="csc", dtype=np.float32)
+        assert_equal(result.dtype, np.float32)
+        assert_equal(result.indices.dtype, np.int32)
+        assert_equal(result.indptr.dtype, np.int32)
+
+    def test_vstack_maintain64bit_idx_dtype(self):
+        # see gh-20389 v/hstack returns int32 idx_dtype with input int64 idx_dtype
+        X = csr_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]])
+        X.indptr = X.indptr.astype(np.int64)
+        X.indices = X.indices.astype(np.int64)
+        assert construct.vstack([X, X]).indptr.dtype == np.int64
+        assert construct.hstack([X, X]).indptr.dtype == np.int64
+
+        X = csc_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]])
+        X.indptr = X.indptr.astype(np.int64)
+        X.indices = X.indices.astype(np.int64)
+        assert construct.vstack([X, X]).indptr.dtype == np.int64
+        assert construct.hstack([X, X]).indptr.dtype == np.int64
+
+        X = coo_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]])
+        X.coords = tuple(co.astype(np.int64) for co in X.coords)
+        assert construct.vstack([X, X]).coords[0].dtype == np.int64
+        assert construct.hstack([X, X]).coords[0].dtype == np.int64
+
+    def test_vstack_matrix_or_array(self):
+        A = [[1,2],[3,4]]
+        B = [[5,6]]
+        assert isinstance(construct.vstack([coo_array(A), coo_array(B)]), sparray)
+        assert isinstance(construct.vstack([coo_array(A), coo_matrix(B)]), sparray)
+        assert isinstance(construct.vstack([coo_matrix(A), coo_array(B)]), sparray)
+        assert isinstance(construct.vstack([coo_matrix(A), coo_matrix(B)]), spmatrix)
+
+    def test_vstack_1d_with_2d(self):
+        # fixes gh-21064
+        arr = csr_array([[1, 0, 0], [0, 1, 0]])
+        arr1d = csr_array([1, 0, 0])
+        arr1dcoo = coo_array([1, 0, 0])
+        assert construct.vstack([arr, np.array([0, 0, 0])]).shape == (3, 3)
+        assert construct.hstack([arr1d, np.array([[0]])]).shape == (1, 4)
+        assert construct.hstack([arr1d, arr1d]).shape == (1, 6)
+        assert construct.vstack([arr1d, arr1d]).shape == (2, 3)
+
+        # check csr specialty stacking code like _stack_along_minor_axis
+        assert construct.hstack([arr, arr]).shape == (2, 6)
+        assert construct.hstack([arr1d, arr1d]).shape == (1, 6)
+
+        assert construct.hstack([arr1d, arr1dcoo]).shape == (1, 6)
+        assert construct.vstack([arr, arr1dcoo]).shape == (3, 3)
+        assert construct.vstack([arr1d, arr1dcoo]).shape == (2, 3)
+
+        with pytest.raises(ValueError, match="incompatible row dimensions"):
+            construct.hstack([arr, np.array([0, 0])])
+        with pytest.raises(ValueError, match="incompatible column dimensions"):
+            construct.vstack([arr, np.array([0, 0])])
+
+    @pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array])
+    def test_hstack(self, coo_cls):
+        A = coo_cls([[1,2],[3,4]])
+        B = coo_cls([[5],[6]])
+
+        expected = array([[1, 2, 5],
+                          [3, 4, 6]])
+        assert_equal(construct.hstack([A, B]).toarray(), expected)
+        assert_equal(construct.hstack([A, B], dtype=np.float32).dtype,
+                     np.float32)
+
+        assert_equal(construct.hstack([A.todok(), B.todok()]).toarray(), expected)
+
+        assert_equal(construct.hstack([A.tocsc(), B.tocsc()]).toarray(),
+                     expected)
+        assert_equal(construct.hstack([A.tocsc(), B.tocsc()],
+                                      dtype=np.float32).dtype,
+                     np.float32)
+        assert_equal(construct.hstack([A.tocsr(), B.tocsr()]).toarray(),
+                     expected)
+        assert_equal(construct.hstack([A.tocsr(), B.tocsr()],
+                                      dtype=np.float32).dtype,
+                     np.float32)
+
+    def test_hstack_matrix_or_array(self):
+        A = [[1,2],[3,4]]
+        B = [[5],[6]]
+        assert isinstance(construct.hstack([coo_array(A), coo_array(B)]), sparray)
+        assert isinstance(construct.hstack([coo_array(A), coo_matrix(B)]), sparray)
+        assert isinstance(construct.hstack([coo_matrix(A), coo_array(B)]), sparray)
+        assert isinstance(construct.hstack([coo_matrix(A), coo_matrix(B)]), spmatrix)
+
+    @pytest.mark.parametrize("block_array", (construct.bmat, construct.block_array))
+    def test_block_creation(self, block_array):
+
+        A = coo_array([[1, 2], [3, 4]])
+        B = coo_array([[5],[6]])
+        C = coo_array([[7]])
+        D = coo_array((0, 0))
+
+        expected = array([[1, 2, 5],
+                          [3, 4, 6],
+                          [0, 0, 7]])
+        assert_equal(block_array([[A, B], [None, C]]).toarray(), expected)
+        E = csr_array((1, 2), dtype=np.int32)
+        assert_equal(block_array([[A.tocsr(), B.tocsr()],
+                                  [E, C.tocsr()]]).toarray(),
+                     expected)
+        assert_equal(block_array([[A.tocsc(), B.tocsc()],
+                                  [E.tocsc(), C.tocsc()]]).toarray(),
+                     expected)
+
+        expected = array([[1, 2, 0],
+                          [3, 4, 0],
+                          [0, 0, 7]])
+        assert_equal(block_array([[A, None], [None, C]]).toarray(), expected)
+        assert_equal(block_array([[A.tocsr(), E.T.tocsr()],
+                                  [E, C.tocsr()]]).toarray(),
+                     expected)
+        assert_equal(block_array([[A.tocsc(), E.T.tocsc()],
+                                  [E.tocsc(), C.tocsc()]]).toarray(),
+                     expected)
+
+        Z = csr_array((1, 1), dtype=np.int32)
+        expected = array([[0, 5],
+                          [0, 6],
+                          [7, 0]])
+        assert_equal(block_array([[None, B], [C, None]]).toarray(), expected)
+        assert_equal(block_array([[E.T.tocsr(), B.tocsr()],
+                                  [C.tocsr(), Z]]).toarray(),
+                     expected)
+        assert_equal(block_array([[E.T.tocsc(), B.tocsc()],
+                                  [C.tocsc(), Z.tocsc()]]).toarray(),
+                     expected)
+
+        expected = np.empty((0, 0))
+        assert_equal(block_array([[None, None]]).toarray(), expected)
+        assert_equal(block_array([[None, D], [D, None]]).toarray(),
+                     expected)
+
+        # test bug reported in gh-5976
+        expected = array([[7]])
+        assert_equal(block_array([[None, D], [C, None]]).toarray(),
+                     expected)
+
+        # test failure cases
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A], [B]])
+        excinfo.match(r'Got blocks\[1,0\]\.shape\[1\] == 1, expected 2')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A.tocsr()], [B.tocsr()]])
+        excinfo.match(r'incompatible dimensions for axis 1')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A.tocsc()], [B.tocsc()]])
+        excinfo.match(r'Mismatching dimensions along axis 1: ({1, 2}|{2, 1})')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A, C]])
+        excinfo.match(r'Got blocks\[0,1\]\.shape\[0\] == 1, expected 2')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A.tocsr(), C.tocsr()]])
+        excinfo.match(r'Mismatching dimensions along axis 0: ({1, 2}|{2, 1})')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A.tocsc(), C.tocsc()]])
+        excinfo.match(r'incompatible dimensions for axis 0')
+
+    def test_block_return_type(self):
+        block = construct.block_array
+
+        # csr format ensures we hit _compressed_sparse_stack
+        # shape of F,G ensure we hit _stack_along_minor_axis
+        # list version ensure we hit the path with neither helper function
+        Fl, Gl = [[1, 2],[3, 4]], [[7], [5]]
+        Fm, Gm = csr_matrix(Fl), csr_matrix(Gl)
+        assert isinstance(block([[None, Fl], [Gl, None]], format="csr"), sparray)
+        assert isinstance(block([[None, Fm], [Gm, None]], format="csr"), sparray)
+        assert isinstance(block([[Fm, Gm]], format="csr"), sparray)
+
+    def test_bmat_return_type(self):
+        """This can be removed after sparse matrix is removed"""
+        bmat = construct.bmat
+        # check return type. if any input _is_array output array, else matrix
+        Fl, Gl = [[1, 2],[3, 4]], [[7], [5]]
+        Fm, Gm = csr_matrix(Fl), csr_matrix(Gl)
+        Fa, Ga = csr_array(Fl), csr_array(Gl)
+        assert isinstance(bmat([[Fa, Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Fm, Gm]], format="csr"), spmatrix)
+        assert isinstance(bmat([[None, Fa], [Ga, None]], format="csr"), sparray)
+        assert isinstance(bmat([[None, Fm], [Ga, None]], format="csr"), sparray)
+        assert isinstance(bmat([[None, Fm], [Gm, None]], format="csr"), spmatrix)
+        assert isinstance(bmat([[None, Fl], [Gl, None]], format="csr"), spmatrix)
+
+        # type returned by _compressed_sparse_stack (all csr)
+        assert isinstance(bmat([[Ga, Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Gm, Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Ga, Gm]], format="csr"), sparray)
+        assert isinstance(bmat([[Gm, Gm]], format="csr"), spmatrix)
+        # shape is 2x2 so no _stack_along_minor_axis
+        assert isinstance(bmat([[Fa, Fm]], format="csr"), sparray)
+        assert isinstance(bmat([[Fm, Fm]], format="csr"), spmatrix)
+
+        # type returned by _compressed_sparse_stack (all csc)
+        assert isinstance(bmat([[Gm.tocsc(), Ga.tocsc()]], format="csc"), sparray)
+        assert isinstance(bmat([[Gm.tocsc(), Gm.tocsc()]], format="csc"), spmatrix)
+        # shape is 2x2 so no _stack_along_minor_axis
+        assert isinstance(bmat([[Fa.tocsc(), Fm.tocsc()]], format="csr"), sparray)
+        assert isinstance(bmat([[Fm.tocsc(), Fm.tocsc()]], format="csr"), spmatrix)
+
+        # type returned when mixed input
+        assert isinstance(bmat([[Gl, Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Gm.tocsc(), Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Gm.tocsc(), Gm]], format="csr"), spmatrix)
+        assert isinstance(bmat([[Gm, Gm]], format="csc"), spmatrix)
+
+    @pytest.mark.slow
+    @pytest.mark.thread_unsafe
+    @pytest.mark.xfail_on_32bit("Can't create large array for test")
+    def test_concatenate_int32_overflow(self):
+        """ test for indptr overflow when concatenating matrices """
+        check_free_memory(30000)
+
+        n = 33000
+        A = csr_array(np.ones((n, n), dtype=bool))
+        B = A.copy()
+        C = construct._compressed_sparse_stack((A, B), axis=0,
+                                               return_spmatrix=False)
+
+        assert_(np.all(np.equal(np.diff(C.indptr), n)))
+        assert_equal(C.indices.dtype, np.int64)
+        assert_equal(C.indptr.dtype, np.int64)
+
+    def test_block_diag_basic(self):
+        """ basic test for block_diag """
+        A = coo_array([[1,2],[3,4]])
+        B = coo_array([[5],[6]])
+        C = coo_array([[7]])
+
+        expected = array([[1, 2, 0, 0],
+                          [3, 4, 0, 0],
+                          [0, 0, 5, 0],
+                          [0, 0, 6, 0],
+                          [0, 0, 0, 7]])
+
+        ABC = construct.block_diag((A, B, C))
+        assert_equal(ABC.toarray(), expected)
+        assert ABC.coords[0].dtype == np.int32
+
+    def test_block_diag_idx_dtype(self):
+        X = coo_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]])
+        X.coords = tuple(co.astype(np.int64) for co in X.coords)
+        assert construct.block_diag([X, X]).coords[0].dtype == np.int64
+
+    def test_block_diag_scalar_1d_args(self):
+        """ block_diag with scalar and 1d arguments """
+        # one 1d matrix and a scalar
+        assert_array_equal(construct.block_diag([[2,3], 4]).toarray(),
+                           [[2, 3, 0], [0, 0, 4]])
+        # 1d sparse arrays
+        A = coo_array([1,0,3])
+        B = coo_array([0,4])
+        assert_array_equal(construct.block_diag([A, B]).toarray(),
+                           [[1, 0, 3, 0, 0], [0, 0, 0, 0, 4]])
+
+    def test_block_diag_1(self):
+        """ block_diag with one matrix """
+        assert_equal(construct.block_diag([[1, 0]]).toarray(),
+                     array([[1, 0]]))
+        assert_equal(construct.block_diag([[[1, 0]]]).toarray(),
+                     array([[1, 0]]))
+        assert_equal(construct.block_diag([[[1], [0]]]).toarray(),
+                     array([[1], [0]]))
+        # just on scalar
+        assert_equal(construct.block_diag([1]).toarray(),
+                     array([[1]]))
+
+    def test_block_diag_sparse_arrays(self):
+        """ block_diag with sparse arrays """
+
+        A = coo_array([[1, 2, 3]], shape=(1, 3))
+        B = coo_array([[4, 5]], shape=(1, 2))
+        assert_equal(construct.block_diag([A, B]).toarray(),
+                     array([[1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]))
+
+        A = coo_array([[1], [2], [3]], shape=(3, 1))
+        B = coo_array([[4], [5]], shape=(2, 1))
+        assert_equal(construct.block_diag([A, B]).toarray(),
+                     array([[1, 0], [2, 0], [3, 0], [0, 4], [0, 5]]))
+
+    def test_block_diag_return_type(self):
+        A, B = coo_array([[1, 2, 3]]), coo_matrix([[2, 3, 4]])
+        assert isinstance(construct.block_diag([A, A]), sparray)
+        assert isinstance(construct.block_diag([A, B]), sparray)
+        assert isinstance(construct.block_diag([B, A]), sparray)
+        assert isinstance(construct.block_diag([B, B]), spmatrix)
+
+    def test_random_sampling(self):
+        # Simple sanity checks for sparse random sampling.
+        for f in sprand, _sprandn:
+            for t in [np.float32, np.float64, np.longdouble,
+                      np.int32, np.int64, np.complex64, np.complex128]:
+                x = f(5, 10, density=0.1, dtype=t)
+                assert_equal(x.dtype, t)
+                assert_equal(x.shape, (5, 10))
+                assert_equal(x.nnz, 5)
+
+            x1 = f(5, 10, density=0.1, rng=4321)
+            assert_equal(x1.dtype, np.float64)
+
+            x2 = f(5, 10, density=0.1, rng=np.random.default_rng(4321))
+
+            assert_array_equal(x1.data, x2.data)
+            assert_array_equal(x1.row, x2.row)
+            assert_array_equal(x1.col, x2.col)
+
+            for density in [0.0, 0.1, 0.5, 1.0]:
+                x = f(5, 10, density=density)
+                assert_equal(x.nnz, int(density * np.prod(x.shape)))
+
+            for fmt in ['coo', 'csc', 'csr', 'lil']:
+                x = f(5, 10, format=fmt)
+                assert_equal(x.format, fmt)
+
+            assert_raises(ValueError, lambda: f(5, 10, 1.1))
+            assert_raises(ValueError, lambda: f(5, 10, -0.1))
+
+    @pytest.mark.parametrize("rng", [None, 4321, np.random.default_rng(4321)])
+    def test_rand(self, rng):
+        # Simple distributional checks for sparse.rand.
+        x = sprand(10, 20, density=0.5, dtype=np.float64, rng=rng)
+        assert_(np.all(np.less_equal(0, x.data)))
+        assert_(np.all(np.less_equal(x.data, 1)))
+
+    @pytest.mark.parametrize("rng", [None, 4321, np.random.default_rng(4321)])
+    def test_randn(self, rng):
+        # Simple distributional checks for sparse.randn.
+        # Statistically, some of these should be negative
+        # and some should be greater than 1.
+        x = _sprandn(10, 20, density=0.5, dtype=np.float64, rng=rng)
+        assert_(np.any(np.less(x.data, 0)))
+        assert_(np.any(np.less(1, x.data)))
+        x = _sprandn_array(10, 20, density=0.5, dtype=np.float64, rng=rng)
+        assert_(np.any(np.less(x.data, 0)))
+        assert_(np.any(np.less(1, x.data)))
+
+    def test_random_accept_str_dtype(self):
+        # anything that np.dtype can convert to a dtype should be accepted
+        # for the dtype
+        construct.random(10, 10, dtype='d')
+        construct.random_array((10, 10), dtype='d')
+        construct.random_array((10, 10, 10), dtype='d')
+        construct.random_array((10, 10, 10, 10, 10), dtype='d')
+
+    def test_random_array_maintains_array_shape(self):
+        # preserve use of old random_state during SPEC 7 transition
+        arr = construct.random_array((0, 4), density=0.3, dtype=int, random_state=0)
+        assert arr.shape == (0, 4)
+
+        arr = construct.random_array((10, 10, 10), density=0.3, dtype=int, rng=0)
+        assert arr.shape == (10, 10, 10)
+
+        arr = construct.random_array((10, 10, 10, 10, 10), density=0.3, dtype=int,
+                                     rng=0)
+        assert arr.shape == (10, 10, 10, 10, 10)
+
+    def test_random_array_idx_dtype(self):
+        A = construct.random_array((10, 10))
+        assert A.coords[0].dtype == np.int32
+
+    def test_random_sparse_matrix_returns_correct_number_of_non_zero_elements(self):
+        # A 10 x 10 matrix, with density of 12.65%, should have 13 nonzero elements.
+        # 10 x 10 x 0.1265 = 12.65, which should be rounded up to 13, not 12.
+        sparse_matrix = construct.random(10, 10, density=0.1265)
+        assert_equal(sparse_matrix.count_nonzero(),13)
+        # check random_array
+        sparse_array = construct.random_array((10, 10), density=0.1265)
+        assert_equal(sparse_array.count_nonzero(),13)
+        assert isinstance(sparse_array, sparray)
+        # check big size
+        shape = (2**33, 2**33)
+        sparse_array = construct.random_array(shape, density=2.7105e-17)
+        assert_equal(sparse_array.count_nonzero(),2000)
+
+        # for n-D
+        # check random_array
+        sparse_array = construct.random_array((10, 10, 10, 10), density=0.12658)
+        assert_equal(sparse_array.count_nonzero(),1266)
+        assert isinstance(sparse_array, sparray)
+        # check big size
+        shape = (2**33, 2**33, 2**33)
+        sparse_array = construct.random_array(shape, density=2.7105e-28)
+        assert_equal(sparse_array.count_nonzero(),172)
+
+
+def test_diags_array():
+    """Tests of diags_array that do not rely on diags wrapper."""
+    diag = np.arange(1, 5)
+
+    assert_array_equal(construct.diags_array(diag).toarray(), np.diag(diag))
+
+    assert_array_equal(
+        construct.diags_array(diag, offsets=2).toarray(), np.diag(diag, k=2)
+    )
+
+    assert_array_equal(
+        construct.diags_array(diag, offsets=2, shape=(4, 4)).toarray(),
+        np.diag(diag, k=2)[:4, :4]
+    )
+
+    # Offset outside bounds when shape specified
+    with pytest.raises(ValueError, match=".*out of bounds"):
+        construct.diags(np.arange(1, 5), 5, shape=(4, 4))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9281748e6fc9ccdcf8aa44d154ada5856bd46a9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py
@@ -0,0 +1,851 @@
+import numpy as np
+from numpy.testing import assert_equal
+import pytest
+from scipy.linalg import block_diag
+from scipy.sparse import coo_array, random_array
+from .._coo import _block_diag, _extract_block_diag
+
+
+def test_shape_constructor():
+    empty1d = coo_array((3,))
+    assert empty1d.shape == (3,)
+    assert_equal(empty1d.toarray(), np.zeros((3,)))
+
+    empty2d = coo_array((3, 2))
+    assert empty2d.shape == (3, 2)
+    assert_equal(empty2d.toarray(), np.zeros((3, 2)))
+
+    empty_nd = coo_array((2,3,4,6,7))
+    assert empty_nd.shape == (2,3,4,6,7)
+    assert_equal(empty_nd.toarray(), np.zeros((2,3,4,6,7)))
+
+
+def test_dense_constructor():
+    # 1d
+    res1d = coo_array([1, 2, 3])
+    assert res1d.shape == (3,)
+    assert_equal(res1d.toarray(), np.array([1, 2, 3]))
+
+    # 2d
+    res2d = coo_array([[1, 2, 3], [4, 5, 6]])
+    assert res2d.shape == (2, 3)
+    assert_equal(res2d.toarray(), np.array([[1, 2, 3], [4, 5, 6]]))
+
+    # 4d
+    arr4d = np.array([[[[3, 7], [1, 0]], [[6, 5], [9, 2]]],
+                      [[[4, 3], [2, 8]], [[7, 5], [1, 6]]],
+                      [[[0, 9], [4, 3]], [[2, 1], [7, 8]]]])
+    res4d = coo_array(arr4d)
+    assert res4d.shape == (3, 2, 2, 2)
+    assert_equal(res4d.toarray(), arr4d)
+
+    # 9d
+    np.random.seed(12)
+    arr9d = np.random.randn(2,3,4,7,6,5,3,2,4)
+    res9d = coo_array(arr9d)
+    assert res9d.shape == (2,3,4,7,6,5,3,2,4)
+    assert_equal(res9d.toarray(), arr9d)
+
+    # storing nan as element of sparse array
+    nan_3d = coo_array([[[1, np.nan]], [[3, 4]], [[5, 6]]])
+    assert nan_3d.shape == (3, 1, 2)
+    assert_equal(nan_3d.toarray(), np.array([[[1, np.nan]], [[3, 4]], [[5, 6]]]))
+
+
+def test_dense_constructor_with_shape():
+    res1d = coo_array([1, 2, 3], shape=(3,))
+    assert res1d.shape == (3,)
+    assert_equal(res1d.toarray(), np.array([1, 2, 3]))
+
+    res2d = coo_array([[1, 2, 3], [4, 5, 6]], shape=(2, 3))
+    assert res2d.shape == (2, 3)
+    assert_equal(res2d.toarray(), np.array([[1, 2, 3], [4, 5, 6]]))
+
+    res3d = coo_array([[[3]], [[4]]], shape=(2, 1, 1))
+    assert res3d.shape == (2, 1, 1)
+    assert_equal(res3d.toarray(), np.array([[[3]], [[4]]]))
+
+    np.random.seed(12)
+    arr7d = np.random.randn(2,4,1,6,5,3,2)
+    res7d = coo_array((arr7d), shape=(2,4,1,6,5,3,2))
+    assert res7d.shape == (2,4,1,6,5,3,2)
+    assert_equal(res7d.toarray(), arr7d)
+
+
+def test_dense_constructor_with_inconsistent_shape():
+    with pytest.raises(ValueError, match='inconsistent shapes'):
+        coo_array([1, 2, 3], shape=(4,))
+
+    with pytest.raises(ValueError, match='inconsistent shapes'):
+        coo_array([1, 2, 3], shape=(3, 1))
+
+    with pytest.raises(ValueError, match='inconsistent shapes'):
+        coo_array([[1, 2, 3]], shape=(3,))
+
+    with pytest.raises(ValueError, match='inconsistent shapes'):
+        coo_array([[[3]], [[4]]], shape=(1, 1, 1))
+
+    with pytest.raises(ValueError,
+                       match='axis 0 index 2 exceeds matrix dimension 2'):
+        coo_array(([1], ([2],)), shape=(2,))
+
+    with pytest.raises(ValueError,
+                       match='axis 1 index 3 exceeds matrix dimension 3'):
+        coo_array(([1,3], ([0, 1], [0, 3], [1, 1])), shape=(2, 3, 2))
+
+    with pytest.raises(ValueError, match='negative axis 0 index: -1'):
+        coo_array(([1], ([-1],)))
+
+    with pytest.raises(ValueError, match='negative axis 2 index: -1'):
+        coo_array(([1], ([0], [2], [-1])))
+
+
+def test_1d_sparse_constructor():
+    empty1d = coo_array((3,))
+    res = coo_array(empty1d)
+    assert res.shape == (3,)
+    assert_equal(res.toarray(), np.zeros((3,)))
+
+
+def test_1d_tuple_constructor():
+    res = coo_array(([9,8], ([1,2],)))
+    assert res.shape == (3,)
+    assert_equal(res.toarray(), np.array([0, 9, 8]))
+
+
+def test_1d_tuple_constructor_with_shape():
+    res = coo_array(([9,8], ([1,2],)), shape=(4,))
+    assert res.shape == (4,)
+    assert_equal(res.toarray(), np.array([0, 9, 8, 0]))
+
+def test_non_subscriptability():
+    coo_2d = coo_array((2, 2))
+
+    with pytest.raises(TypeError,
+                        match="'coo_array' object does not support item assignment"):
+        coo_2d[0, 0] = 1
+
+    with pytest.raises(TypeError,
+                       match="'coo_array' object is not subscriptable"):
+        coo_2d[0, :]
+
+def test_reshape_overflow():
+    # see gh-22353 : new idx_dtype can need to be int64 instead of int32
+    M, N = (1045507, 523266)
+    coords = (np.array([M - 1], dtype='int32'), np.array([N - 1], dtype='int32'))
+    A = coo_array(([3.3], coords), shape=(M, N))
+
+    # need new idx_dtype to not overflow
+    B = A.reshape((M * N, 1))
+    assert B.coords[0].dtype == np.dtype('int64')
+    assert B.coords[0][0] == (M * N) - 1
+
+    # need idx_dtype to stay int32 if before and after can be int32
+    C = A.reshape(N, M)
+    assert C.coords[0].dtype == np.dtype('int32')
+    assert C.coords[0][0] == N - 1
+
+def test_reshape():
+    arr1d = coo_array([1, 0, 3])
+    assert arr1d.shape == (3,)
+
+    col_vec = arr1d.reshape((3, 1))
+    assert col_vec.shape == (3, 1)
+    assert_equal(col_vec.toarray(), np.array([[1], [0], [3]]))
+
+    row_vec = arr1d.reshape((1, 3))
+    assert row_vec.shape == (1, 3)
+    assert_equal(row_vec.toarray(), np.array([[1, 0, 3]]))
+
+    # attempting invalid reshape
+    with pytest.raises(ValueError, match="cannot reshape array"):
+        arr1d.reshape((3,3))
+
+    # attempting reshape with a size 0 dimension
+    with pytest.raises(ValueError, match="cannot reshape array"):
+        arr1d.reshape((3,0))
+
+    arr2d = coo_array([[1, 2, 0], [0, 0, 3]])
+    assert arr2d.shape == (2, 3)
+
+    flat = arr2d.reshape((6,))
+    assert flat.shape == (6,)
+    assert_equal(flat.toarray(), np.array([1, 2, 0, 0, 0, 3]))
+
+    # 2d to 3d
+    to_3d_arr = arr2d.reshape((2, 3, 1))
+    assert to_3d_arr.shape == (2, 3, 1)
+    assert_equal(to_3d_arr.toarray(), np.array([[[1], [2], [0]], [[0], [0], [3]]]))
+
+    # attempting invalid reshape
+    with pytest.raises(ValueError, match="cannot reshape array"):
+        arr2d.reshape((1,3))
+
+
+def test_nnz():
+    arr1d = coo_array([1, 0, 3])
+    assert arr1d.shape == (3,)
+    assert arr1d.nnz == 2
+
+    arr2d = coo_array([[1, 2, 0], [0, 0, 3]])
+    assert arr2d.shape == (2, 3)
+    assert arr2d.nnz == 3
+
+
+def test_transpose():
+    arr1d = coo_array([1, 0, 3]).T
+    assert arr1d.shape == (3,)
+    assert_equal(arr1d.toarray(), np.array([1, 0, 3]))
+
+    arr2d = coo_array([[1, 2, 0], [0, 0, 3]]).T
+    assert arr2d.shape == (3, 2)
+    assert_equal(arr2d.toarray(), np.array([[1, 0], [2, 0], [0, 3]]))
+
+
+def test_transpose_with_axis():
+    arr1d = coo_array([1, 0, 3]).transpose(axes=(0,))
+    assert arr1d.shape == (3,)
+    assert_equal(arr1d.toarray(), np.array([1, 0, 3]))
+
+    arr2d = coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(0, 1))
+    assert arr2d.shape == (2, 3)
+    assert_equal(arr2d.toarray(), np.array([[1, 2, 0], [0, 0, 3]]))
+
+    with pytest.raises(ValueError, match="axes don't match matrix dimensions"):
+        coo_array([1, 0, 3]).transpose(axes=(0, 1))
+
+    with pytest.raises(ValueError, match="repeated axis in transpose"):
+        coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(1, 1))
+
+
+def test_1d_row_and_col():
+    res = coo_array([1, -2, -3])
+    assert_equal(res.col, np.array([0, 1, 2]))
+    assert_equal(res.row, np.zeros_like(res.col))
+    assert res.row.dtype == res.col.dtype
+    assert res.row.flags.writeable is False
+
+    res.col = [1, 2, 3]
+    assert len(res.coords) == 1
+    assert_equal(res.col, np.array([1, 2, 3]))
+    assert res.row.dtype == res.col.dtype
+
+    with pytest.raises(ValueError, match="cannot set row attribute"):
+        res.row = [1, 2, 3]
+
+
+def test_1d_toformats():
+    res = coo_array([1, -2, -3])
+    for f in [res.tobsr, res.tocsc, res.todia, res.tolil]:
+        with pytest.raises(ValueError, match='Cannot convert'):
+            f()
+    for f in [res.tocoo, res.tocsr, res.todok]:
+        assert_equal(f().toarray(), res.toarray())
+
+
+@pytest.mark.parametrize('arg', [1, 2, 4, 5, 8])
+def test_1d_resize(arg: int):
+    den = np.array([1, -2, -3])
+    res = coo_array(den)
+    den.resize(arg, refcheck=False)
+    res.resize(arg)
+    assert res.shape == den.shape
+    assert_equal(res.toarray(), den)
+
+
+@pytest.mark.parametrize('arg', zip([1, 2, 3, 4], [1, 2, 3, 4]))
+def test_1d_to_2d_resize(arg: tuple[int, int]):
+    den = np.array([1, 0, 3])
+    res = coo_array(den)
+
+    den.resize(arg, refcheck=False)
+    res.resize(arg)
+    assert res.shape == den.shape
+    assert_equal(res.toarray(), den)
+
+
+@pytest.mark.parametrize('arg', [1, 4, 6, 8])
+def test_2d_to_1d_resize(arg: int):
+    den = np.array([[1, 0, 3], [4, 0, 0]])
+    res = coo_array(den)
+    den.resize(arg, refcheck=False)
+    res.resize(arg)
+    assert res.shape == den.shape
+    assert_equal(res.toarray(), den)
+
+
+def test_sum_duplicates():
+    # 1d case
+    arr1d = coo_array(([2, 2, 2], ([1, 0, 1],)))
+    assert arr1d.nnz == 3
+    assert_equal(arr1d.toarray(), np.array([2, 4]))
+    arr1d.sum_duplicates()
+    assert arr1d.nnz == 2
+    assert_equal(arr1d.toarray(), np.array([2, 4]))
+
+    # 4d case
+    arr4d = coo_array(([2, 3, 7], ([1, 0, 1], [0, 2, 0], [1, 2, 1], [1, 0, 1])))
+    assert arr4d.nnz == 3
+    expected = np.array(  # noqa: E501
+        [[[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [3, 0]]],
+         [[[0, 0], [0, 9], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]]
+    )
+    assert_equal(arr4d.toarray(), expected)
+    arr4d.sum_duplicates()
+    assert arr4d.nnz == 2
+    assert_equal(arr4d.toarray(), expected)
+
+    # when there are no duplicates
+    arr_nodups = coo_array(([1, 2, 3, 4], ([0, 1, 2, 3],)))
+    assert arr_nodups.nnz == 4
+    arr_nodups.sum_duplicates()
+    assert arr_nodups.nnz == 4
+
+
+def test_eliminate_zeros():
+    arr1d = coo_array(([0, 0, 1], ([1, 0, 1],)))
+    assert arr1d.nnz == 3
+    assert arr1d.count_nonzero() == 1
+    assert_equal(arr1d.toarray(), np.array([0, 1]))
+    arr1d.eliminate_zeros()
+    assert arr1d.nnz == 1
+    assert arr1d.count_nonzero() == 1
+    assert_equal(arr1d.toarray(), np.array([0, 1]))
+    assert_equal(arr1d.col, np.array([1]))
+    assert_equal(arr1d.row, np.array([0]))
+
+
+def test_1d_add_dense():
+    den_a = np.array([0, -2, -3, 0])
+    den_b = np.array([0, 1, 2, 3])
+    exp = den_a + den_b
+    res = coo_array(den_a) + den_b
+    assert type(res) is type(exp)
+    assert_equal(res, exp)
+
+
+def test_1d_add_sparse():
+    den_a = np.array([0, -2, -3, 0])
+    den_b = np.array([0, 1, 2, 3])
+    dense_sum = den_a + den_b
+    # this routes through CSR format
+    sparse_sum = coo_array(den_a) + coo_array(den_b)
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+def test_1d_matmul_vector():
+    den_a = np.array([0, -2, -3, 0])
+    den_b = np.array([0, 1, 2, 3])
+    exp = den_a @ den_b
+    res = coo_array(den_a) @ den_b
+    assert np.ndim(res) == 0
+    assert_equal(res, exp)
+
+
+def test_1d_matmul_multivector():
+    den = np.array([0, -2, -3, 0])
+    other = np.array([[0, 1, 2, 3], [3, 2, 1, 0]]).T
+    exp = den @ other
+    res = coo_array(den) @ other
+    assert type(res) is type(exp)
+    assert_equal(res, exp)
+
+
+def test_2d_matmul_multivector():
+    # sparse-sparse matmul
+    den = np.array([[0, 1, 2, 3], [3, 2, 1, 0]])
+    arr2d = coo_array(den)
+    exp = den @ den.T
+    res = arr2d @ arr2d.T
+    assert_equal(res.toarray(), exp)
+
+    # sparse-dense matmul for self.ndim = 2
+    den = np.array([[0, 4, 3, 0, 5], [1, 0, 7, 3, 4]])
+    arr2d = coo_array(den)
+    exp = den @ den.T
+    res = arr2d @ den.T
+    assert_equal(res, exp)
+
+    # sparse-dense matmul for self.ndim = 1
+    den_a = np.array([[0, 4, 3, 0, 5], [1, 0, 7, 3, 4]])
+    den_b = np.array([0, 1, 6, 0, 4])
+    arr1d = coo_array(den_b)
+    exp = den_b @ den_a.T
+    res = arr1d @ den_a.T
+    assert_equal(res, exp)
+
+    # sparse-dense matmul for self.ndim = 1 and other.ndim = 2
+    den_a = np.array([1, 0, 2])
+    den_b = np.array([[3], [4], [0]])
+    exp = den_a @ den_b
+    res = coo_array(den_a) @ den_b
+    assert_equal(res, exp)
+    res = coo_array(den_a) @ list(den_b)
+    assert_equal(res, exp)
+
+
+def test_1d_diagonal():
+    den = np.array([0, -2, -3, 0])
+    with pytest.raises(ValueError, match='diagonal requires two dimensions'):
+        coo_array(den).diagonal()
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_todense(shape):
+    np.random.seed(12)
+    arr = np.random.randint(low=0, high=5, size=shape)
+    assert_equal(coo_array(arr).todense(), arr)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_sparse_constructor(shape):
+    empty_arr = coo_array(shape)
+    res = coo_array(empty_arr)
+    assert res.shape == (shape)
+    assert_equal(res.toarray(), np.zeros(shape))
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_tuple_constructor(shape):
+    np.random.seed(12)
+    arr = np.random.randn(*shape)
+    res = coo_array(arr)
+    assert res.shape == shape
+    assert_equal(res.toarray(), arr)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_tuple_constructor_with_shape(shape):
+    np.random.seed(12)
+    arr = np.random.randn(*shape)
+    res = coo_array(arr, shape=shape)
+    assert res.shape == shape
+    assert_equal(res.toarray(), arr)
+
+
+def test_tuple_constructor_for_dim_size_zero():
+    # arrays with a dimension of size 0
+    with pytest.raises(ValueError, match='exceeds matrix dimension'):
+        coo_array(([9, 8], ([1, 2], [1, 0], [2, 1])), shape=(3,4,0))
+
+    empty_arr = coo_array(([], ([], [], [], [])), shape=(4,0,2,3))
+    assert_equal(empty_arr.toarray(), np.empty((4,0,2,3)))
+
+
+@pytest.mark.parametrize(('shape', 'new_shape'), [((4,9,6,5), (3,6,15,4)),
+                                                  ((4,9,6,5), (36,30)),
+                                                  ((4,9,6,5), (1080,)),
+                                                  ((4,9,6,5), (2,3,2,2,3,5,3)),])
+def test_nd_reshape(shape, new_shape):
+    # reshaping a 4d sparse array
+    rng = np.random.default_rng(23409823)
+
+    arr4d = random_array(shape, density=0.6, rng=rng, dtype=int)
+    assert arr4d.shape == shape
+    den4d = arr4d.toarray()
+
+    exp_arr = den4d.reshape(new_shape)
+    res_arr = arr4d.reshape(new_shape)
+    assert res_arr.shape == new_shape
+    assert_equal(res_arr.toarray(), exp_arr)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_nnz(shape):
+    rng = np.random.default_rng(23409823)
+
+    arr = random_array(shape, density=0.6, rng=rng, dtype=int)
+    assert arr.nnz == np.count_nonzero(arr.toarray())
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_transpose(shape):
+    rng = np.random.default_rng(23409823)
+
+    arr = random_array(shape, density=0.6, rng=rng, dtype=int)
+    exp_arr = arr.toarray().T
+    trans_arr = arr.transpose()
+    assert trans_arr.shape == shape[::-1]
+    assert_equal(exp_arr, trans_arr.toarray())
+
+
+@pytest.mark.parametrize(('shape', 'axis_perm'), [((3,), (0,)),
+                                                  ((2,3), (0,1)),
+                                                  ((2,4,3,6,5,3), (1,2,0,5,3,4)),])
+def test_nd_transpose_with_axis(shape, axis_perm):
+    rng = np.random.default_rng(23409823)
+
+    arr = random_array(shape, density=0.6, rng=rng, dtype=int)
+    trans_arr = arr.transpose(axes=axis_perm)
+    assert_equal(trans_arr.toarray(), np.transpose(arr.toarray(), axes=axis_perm))
+
+
+def test_transpose_with_inconsistent_axis():
+    with pytest.raises(ValueError, match="axes don't match matrix dimensions"):
+        coo_array([1, 0, 3]).transpose(axes=(0, 1))
+
+    with pytest.raises(ValueError, match="repeated axis in transpose"):
+        coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(1, 1))
+
+
+def test_nd_eliminate_zeros():
+    # for 3d sparse arrays
+    arr3d = coo_array(([1, 0, 0, 4], ([0, 1, 1, 2], [0, 1, 0, 1], [1, 1, 2, 0])))
+    assert arr3d.nnz == 4
+    assert arr3d.count_nonzero() == 2
+    assert_equal(arr3d.toarray(), np.array([[[0, 1, 0], [0, 0, 0]],
+                                    [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [4, 0, 0]]]))
+    arr3d.eliminate_zeros()
+    assert arr3d.nnz == 2
+    assert arr3d.count_nonzero() == 2
+    assert_equal(arr3d.toarray(), np.array([[[0, 1, 0], [0, 0, 0]],
+                                    [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [4, 0, 0]]]))
+
+    # for a 5d sparse array when all elements of data array are 0
+    coords = ([0, 1, 1, 2], [0, 1, 0, 1], [1, 1, 2, 0], [0, 0, 2, 3], [1, 0, 0, 2])
+    arr5d = coo_array(([0, 0, 0, 0], coords))
+    assert arr5d.nnz == 4
+    assert arr5d.count_nonzero() == 0
+    arr5d.eliminate_zeros()
+    assert arr5d.nnz == 0
+    assert arr5d.count_nonzero() == 0
+    assert_equal(arr5d.col, np.array([]))
+    assert_equal(arr5d.row, np.array([]))
+    assert_equal(arr5d.coords, ([], [], [], [], []))
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_add_dense(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array(shape, density=0.6, rng=rng, dtype=int)
+    sp_y = random_array(shape, density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+    exp = den_x + den_y
+    res = sp_x + den_y
+    assert type(res) is type(exp)
+    assert_equal(res, exp)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_add_sparse(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array((shape), density=0.6, rng=rng, dtype=int)
+    sp_y = random_array((shape), density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+
+    dense_sum = den_x + den_y
+    sparse_sum = sp_x + sp_y
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+def test_add_sparse_with_inf():
+    # addition of sparse arrays with an inf element
+    den_a = np.array([[[0], [np.inf]], [[-3], [0]]])
+    den_b = np.array([[[0], [1]], [[2], [3]]])
+    dense_sum = den_a + den_b
+    sparse_sum = coo_array(den_a) + coo_array(den_b)
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+@pytest.mark.parametrize(('a_shape', 'b_shape'), [((7,), (12,)),
+                                                  ((6,4), (6,5)),
+                                                  ((5,9,3,2), (9,5,2,3)),])
+def test_nd_add_sparse_with_inconsistent_shapes(a_shape, b_shape):
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array((a_shape), density=0.6, rng=rng, dtype=int)
+    arr_b = random_array((b_shape), density=0.6, rng=rng, dtype=int)
+    with pytest.raises(ValueError,
+                       match="(Incompatible|inconsistent) shapes|cannot be broadcast"):
+        arr_a + arr_b
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_sub_dense(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array(shape, density=0.6, rng=rng, dtype=int)
+    sp_y = random_array(shape, density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+    exp = den_x - den_y
+    res = sp_x - den_y
+    assert type(res) is type(exp)
+    assert_equal(res, exp)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_sub_sparse(shape):
+    rng = np.random.default_rng(23409823)
+
+    sp_x = random_array(shape, density=0.6, rng=rng, dtype=int)
+    sp_y = random_array(shape, density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+
+    dense_sum = den_x - den_y
+    sparse_sum = sp_x - sp_y
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+def test_nd_sub_sparse_with_nan():
+    # subtraction of sparse arrays with a nan element
+    den_a = np.array([[[0], [np.nan]], [[-3], [0]]])
+    den_b = np.array([[[0], [1]], [[2], [3]]])
+    dense_sum = den_a - den_b
+    sparse_sum = coo_array(den_a) - coo_array(den_b)
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+@pytest.mark.parametrize(('a_shape', 'b_shape'), [((7,), (12,)),
+                                                  ((6,4), (6,5)),
+                                                  ((5,9,3,2), (9,5,2,3)),])
+def test_nd_sub_sparse_with_inconsistent_shapes(a_shape, b_shape):
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array((a_shape), density=0.6, rng=rng, dtype=int)
+    arr_b = random_array((b_shape), density=0.6, rng=rng, dtype=int)
+    with pytest.raises(ValueError, match="inconsistent shapes"):
+        arr_a - arr_b
+
+
+mat_vec_shapes = [
+    ((2, 3, 4, 5), (5,)),
+    ((0, 0), (0,)),
+    ((2, 3, 4, 7, 8), (8,)),
+    ((4, 4, 2, 0), (0,)),
+    ((6, 5, 3, 2, 4), (4, 1)),
+    ((2,5), (5,)),
+    ((2, 5), (5, 1)),
+    ((3,), (3, 1)),
+    ((4,), (4,))
+]
+@pytest.mark.parametrize(('mat_shape', 'vec_shape'), mat_vec_shapes)
+def test_nd_matmul_vector(mat_shape, vec_shape):
+    rng = np.random.default_rng(23409823)
+
+    sp_x = random_array(mat_shape, density=0.6, rng=rng, dtype=int)
+    sp_y = random_array(vec_shape, density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+    exp = den_x @ den_y
+    res = sp_x @ den_y
+    assert_equal(res,exp)
+    res = sp_x @ list(den_y)
+    assert_equal(res,exp)
+
+
+mat_mat_shapes = [
+    ((2, 3, 4, 5), (2, 3, 5, 7)),
+    ((0, 0), (0,)),
+    ((4, 4, 2, 0), (0,)),
+    ((7, 8, 3), (3,)),
+    ((7, 8, 3), (3, 1)),
+    ((6, 5, 3, 2, 4), (4, 3)),
+    ((1, 3, 2, 4), (6, 5, 1, 4, 3)),
+    ((6, 1, 1, 2, 4), (1, 3, 4, 3)),
+    ((4,), (2, 4, 3)),
+    ((3,), (5, 6, 7, 3, 2)),
+    ((4,), (4, 3)),
+    ((2, 5), (5, 1)),
+]
+@pytest.mark.parametrize(('mat_shape1', 'mat_shape2'), mat_mat_shapes)
+def test_nd_matmul(mat_shape1, mat_shape2):
+    rng = np.random.default_rng(23409823)
+
+    sp_x = random_array(mat_shape1, density=0.6, random_state=rng, dtype=int)
+    sp_y = random_array(mat_shape2, density=0.6, random_state=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+    exp = den_x @ den_y
+    # sparse-sparse
+    res = sp_x @ sp_y
+    assert_equal(res.toarray(), exp)
+    # sparse-dense
+    res = sp_x @ den_y
+    assert_equal(res, exp)
+    res = sp_x @ list(den_y)
+    assert_equal(res, exp)
+
+    # dense-sparse
+    res = den_x @ sp_y
+    assert_equal(res, exp)
+
+
+def test_nd_matmul_sparse_with_inconsistent_arrays():
+    rng = np.random.default_rng(23409823)
+
+    sp_x = random_array((4,5,7,6,3), density=0.6, random_state=rng, dtype=int)
+    sp_y = random_array((1,5,3,2,5), density=0.6, random_state=rng, dtype=int)
+    with pytest.raises(ValueError, match="matmul: dimension mismatch with signature"):
+        sp_x @ sp_y
+    with pytest.raises(ValueError, match="matmul: dimension mismatch with signature"):
+        sp_x @ (sp_y.toarray())
+
+    sp_z = random_array((1,5,3,2), density=0.6, random_state=rng, dtype=int)
+    with pytest.raises(ValueError, match="Batch dimensions are not broadcastable"):
+        sp_x @ sp_z
+    with pytest.raises(ValueError, match="Batch dimensions are not broadcastable"):
+        sp_x @ (sp_z.toarray())
+
+
+def test_dot_1d_1d(): # 1-D inner product
+    a = coo_array([1,2,3])
+    b = coo_array([4,5,6])
+    exp = np.dot(a.toarray(), b.toarray())
+    res = a.dot(b)
+    assert_equal(res, exp)
+    res = a.dot(b.toarray())
+    assert_equal(res, exp)
+
+
+def test_dot_sparse_scalar():
+    a = coo_array([[1, 2], [3, 4], [5, 6]])
+    b = 3
+    res = a.dot(b)
+    exp = np.dot(a.toarray(), b)
+    assert_equal(res.toarray(), exp)
+
+
+def test_dot_with_inconsistent_shapes():
+    arr_a = coo_array([[[1, 2]], [[3, 4]]])
+    arr_b = coo_array([4, 5, 6])
+    with pytest.raises(ValueError, match="not aligned for n-D dot"):
+        arr_a.dot(arr_b)
+
+
+def test_matmul_dot_not_implemented():
+    arr_a = coo_array([[1, 2], [3, 4]])
+    with pytest.raises(TypeError, match="argument not supported type"):
+        arr_a.dot(None)
+    with pytest.raises(TypeError, match="arg not supported type"):
+        arr_a.tensordot(None)
+    with pytest.raises(TypeError, match="unsupported operand type"):
+        arr_a @ None
+    with pytest.raises(TypeError, match="unsupported operand type"):
+        None @ arr_a
+
+
+dot_shapes = [
+    ((3,3), (3,3)), ((4,6), (6,7)), ((1,4), (4,1)), # matrix multiplication 2-D
+    ((3,2,4,7), (7,)), ((5,), (6,3,5,2)), # dot of n-D and 1-D arrays
+    ((3,2,4,7), (7,1)), ((1,5,), (6,3,5,2)),
+    ((4,6), (3,2,6,4)), ((2,8,7), (4,5,7,7,2)), # dot of n-D and m-D arrays
+    ((4,5,7,6), (3,2,6,4)),
+]
+@pytest.mark.parametrize(('a_shape', 'b_shape'), dot_shapes)
+def test_dot_nd(a_shape, b_shape):
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array(a_shape, density=0.6, random_state=rng, dtype=int)
+    arr_b = random_array(b_shape, density=0.6, random_state=rng, dtype=int)
+
+    exp = np.dot(arr_a.toarray(), arr_b.toarray())
+    # sparse-dense
+    res = arr_a.dot(arr_b.toarray())
+    assert_equal(res, exp)
+    res = arr_a.dot(list(arr_b.toarray()))
+    assert_equal(res, exp)
+    # sparse-sparse
+    res = arr_a.dot(arr_b)
+    assert_equal(res.toarray(), exp)
+
+
+tensordot_shapes_and_axes = [
+    ((4,6), (6,7), ([1], [0])),
+    ((3,2,4,7), (7,), ([3], [0])),
+    ((5,), (6,3,5,2), ([0], [2])),
+    ((4,5,7,6), (3,2,6,4), ([0, 3], [3, 2])),
+    ((2,8,7), (4,5,7,8,2), ([0, 1, 2], [4, 3, 2])),
+    ((4,5,3,2,6), (3,2,6,7,8), 3),
+    ((4,5,7), (7,3,7), 1),
+    ((2,3,4), (2,3,4), ([0, 1, 2], [0, 1, 2])),
+]
+@pytest.mark.parametrize(('a_shape', 'b_shape', 'axes'), tensordot_shapes_and_axes)
+def test_tensordot(a_shape, b_shape, axes):
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array(a_shape, density=0.6, random_state=rng, dtype=int)
+    arr_b = random_array(b_shape, density=0.6, random_state=rng, dtype=int)
+
+    exp = np.tensordot(arr_a.toarray(), arr_b.toarray(), axes=axes)
+
+    # sparse-dense
+    res = arr_a.tensordot(arr_b.toarray(), axes=axes)
+    assert_equal(res, exp)
+    res = arr_a.tensordot(list(arr_b.toarray()), axes=axes)
+    assert_equal(res, exp)
+
+    # sparse-sparse
+    res = arr_a.tensordot(arr_b, axes=axes)
+    if type(res) is coo_array:
+        assert_equal(res.toarray(), exp)
+    else:
+        assert_equal(res, exp)
+
+
+def test_tensordot_with_invalid_args():
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array((3,4,5), density=0.6, random_state=rng, dtype=int)
+    arr_b = random_array((3,4,6), density=0.6, random_state=rng, dtype=int)
+
+    axes = ([2], [2]) # sizes of 2nd axes of both shapes do not match
+    with pytest.raises(ValueError, match="sizes of the corresponding axes must match"):
+        arr_a.tensordot(arr_b, axes=axes)
+
+    arr_a = random_array((5,4,2,3,7), density=0.6, random_state=rng, dtype=int)
+    arr_b = random_array((4,6,3,2), density=0.6, random_state=rng, dtype=int)
+
+    axes = ([2,0,1], [1,3]) # lists have different lengths
+    with pytest.raises(ValueError, match="axes lists/tuples must be of the"
+                       " same length"):
+        arr_a.tensordot(arr_b, axes=axes)
+
+
+@pytest.mark.parametrize(('actual_shape', 'broadcast_shape'),
+                         [((1,3,5,4), (2,3,5,4)), ((2,1,5,4), (6,2,3,5,4)),
+                          ((1,1,7,8,9), (4,5,6,7,8,9)), ((1,3), (4,5,3)),
+                          ((7,8,1), (7,8,5)), ((3,1), (3,4)), ((1,), (5,)),
+                          ((1,1,1), (4,5,6)), ((1,3,1,5,4), (8,2,3,9,5,4)),])
+def test_broadcast_to(actual_shape, broadcast_shape):
+    rng = np.random.default_rng(23409823)
+
+    arr = random_array(actual_shape, density=0.6, random_state=rng, dtype=int)
+    res = arr._broadcast_to(broadcast_shape)
+    exp = np.broadcast_to(arr.toarray(), broadcast_shape)
+    assert_equal(res.toarray(), exp)
+
+
+@pytest.mark.parametrize(('shape'), [(4,5,6,7,8), (6,4),
+                                     (5,9,3,2), (9,5,2,3,4),])
+def test_block_diag(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array(shape, density=0.6, random_state=rng, dtype=int)
+    den_x = sp_x.toarray()
+
+    # converting n-d numpy array to an array of slices of 2-D matrices,
+    # to pass as argument into scipy.linalg.block_diag
+    num_slices = int(np.prod(den_x.shape[:-2]))
+    reshaped_array = den_x.reshape((num_slices,) + den_x.shape[-2:])
+    matrices = [reshaped_array[i, :, :] for i in range(num_slices)]
+    exp = block_diag(*matrices)
+
+    res = _block_diag(sp_x)
+
+    assert_equal(res.toarray(), exp)
+
+
+@pytest.mark.parametrize(('shape'), [(4,5,6,7,8), (6,4),
+                                     (5,9,3,2), (9,5,2,3,4),])
+def test_extract_block_diag(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array(shape, density=0.6, random_state=rng, dtype=int)
+    res = _extract_block_diag(_block_diag(sp_x), shape)
+
+    assert_equal(res.toarray(), sp_x.toarray())
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..6313751e41899ae7c5daf01fbdbbacdc1f303fa1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py
@@ -0,0 +1,98 @@
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_
+from scipy.sparse import csr_matrix, csc_matrix, lil_matrix
+
+import pytest
+
+
+def test_csc_getrow():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsc = csc_matrix(X)
+
+    for i in range(N):
+        arr_row = X[i:i + 1, :]
+        csc_row = Xcsc.getrow(i)
+
+        assert_array_almost_equal(arr_row, csc_row.toarray())
+        assert_(type(csc_row) is csr_matrix)
+
+
+def test_csc_getcol():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsc = csc_matrix(X)
+
+    for i in range(N):
+        arr_col = X[:, i:i + 1]
+        csc_col = Xcsc.getcol(i)
+
+        assert_array_almost_equal(arr_col, csc_col.toarray())
+        assert_(type(csc_col) is csc_matrix)
+
+@pytest.mark.parametrize("matrix_input, axis, expected_shape",
+    [(csc_matrix([[1, 0],
+                [0, 0],
+                [0, 2]]),
+      0, (0, 2)),
+     (csc_matrix([[1, 0],
+                [0, 0],
+                [0, 2]]),
+      1, (3, 0)),
+     (csc_matrix([[1, 0],
+                [0, 0],
+                [0, 2]]),
+      'both', (0, 0)),
+     (csc_matrix([[0, 1, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0],
+                [0, 0, 2, 3, 0, 1]]),
+      0, (0, 6))])
+def test_csc_empty_slices(matrix_input, axis, expected_shape):
+    # see gh-11127 for related discussion
+    slice_1 = matrix_input.toarray().shape[0] - 1
+    slice_2 = slice_1
+    slice_3 = slice_2 - 1
+
+    if axis == 0:
+        actual_shape_1 = matrix_input[slice_1:slice_2, :].toarray().shape
+        actual_shape_2 = matrix_input[slice_1:slice_3, :].toarray().shape
+    elif axis == 1:
+        actual_shape_1 = matrix_input[:, slice_1:slice_2].toarray().shape
+        actual_shape_2 = matrix_input[:, slice_1:slice_3].toarray().shape
+    elif axis == 'both':
+        actual_shape_1 = matrix_input[slice_1:slice_2, slice_1:slice_2].toarray().shape
+        actual_shape_2 = matrix_input[slice_1:slice_3, slice_1:slice_3].toarray().shape
+
+    assert actual_shape_1 == expected_shape
+    assert actual_shape_1 == actual_shape_2
+
+
+@pytest.mark.parametrize('ax', (-2, -1, 0, 1, None))
+def test_argmax_overflow(ax):
+    # See gh-13646: Windows integer overflow for large sparse matrices.
+    dim = (100000, 100000)
+    A = lil_matrix(dim)
+    A[-2, -2] = 42
+    A[-3, -3] = 0.1234
+    A = csc_matrix(A)
+    idx = A.argmax(axis=ax)
+
+    if ax is None:
+        # idx is a single flattened index
+        # that we need to convert to a 2d index pair;
+        # can't do this with np.unravel_index because
+        # the dimensions are too large
+        ii = idx % dim[0]
+        jj = idx // dim[0]
+    else:
+        # idx is an array of size of A.shape[ax];
+        # check the max index to make sure no overflows
+        # we encountered
+        assert np.count_nonzero(idx) == A.nnz
+        ii, jj = np.max(idx), np.argmax(idx)
+
+    assert A[ii, jj] == A[-2, -2]
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b011ad4fdce93c0fac36e58381da0bb554ba3be
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py
@@ -0,0 +1,214 @@
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_, assert_array_equal
+from scipy.sparse import csr_matrix, csc_matrix, csr_array, csc_array, hstack
+from scipy import sparse
+import pytest
+
+
+def _check_csr_rowslice(i, sl, X, Xcsr):
+    np_slice = X[i, sl]
+    csr_slice = Xcsr[i, sl]
+    assert_array_almost_equal(np_slice, csr_slice.toarray()[0])
+    assert_(type(csr_slice) is csr_matrix)
+
+
+def test_csr_rowslice():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsr = csr_matrix(X)
+
+    slices = [slice(None, None, None),
+              slice(None, None, -1),
+              slice(1, -2, 2),
+              slice(-2, 1, -2)]
+
+    for i in range(N):
+        for sl in slices:
+            _check_csr_rowslice(i, sl, X, Xcsr)
+
+
+def test_csr_getrow():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsr = csr_matrix(X)
+
+    for i in range(N):
+        arr_row = X[i:i + 1, :]
+        csr_row = Xcsr.getrow(i)
+
+        assert_array_almost_equal(arr_row, csr_row.toarray())
+        assert_(type(csr_row) is csr_matrix)
+
+
+def test_csr_getcol():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsr = csr_matrix(X)
+
+    for i in range(N):
+        arr_col = X[:, i:i + 1]
+        csr_col = Xcsr.getcol(i)
+
+        assert_array_almost_equal(arr_col, csr_col.toarray())
+        assert_(type(csr_col) is csr_matrix)
+
+@pytest.mark.parametrize("matrix_input, axis, expected_shape",
+    [(csr_matrix([[1, 0, 0, 0],
+                [0, 0, 0, 0],
+                [0, 2, 3, 0]]),
+      0, (0, 4)),
+     (csr_matrix([[1, 0, 0, 0],
+                [0, 0, 0, 0],
+                [0, 2, 3, 0]]),
+      1, (3, 0)),
+     (csr_matrix([[1, 0, 0, 0],
+                [0, 0, 0, 0],
+                [0, 2, 3, 0]]),
+      'both', (0, 0)),
+     (csr_matrix([[0, 1, 0, 0, 0],
+                [0, 0, 0, 0, 0],
+                [0, 0, 2, 3, 0]]),
+      0, (0, 5))])
+def test_csr_empty_slices(matrix_input, axis, expected_shape):
+    # see gh-11127 for related discussion
+    slice_1 = matrix_input.toarray().shape[0] - 1
+    slice_2 = slice_1
+    slice_3 = slice_2 - 1
+
+    if axis == 0:
+        actual_shape_1 = matrix_input[slice_1:slice_2, :].toarray().shape
+        actual_shape_2 = matrix_input[slice_1:slice_3, :].toarray().shape
+    elif axis == 1:
+        actual_shape_1 = matrix_input[:, slice_1:slice_2].toarray().shape
+        actual_shape_2 = matrix_input[:, slice_1:slice_3].toarray().shape
+    elif axis == 'both':
+        actual_shape_1 = matrix_input[slice_1:slice_2, slice_1:slice_2].toarray().shape
+        actual_shape_2 = matrix_input[slice_1:slice_3, slice_1:slice_3].toarray().shape
+
+    assert actual_shape_1 == expected_shape
+    assert actual_shape_1 == actual_shape_2
+
+
+def test_csr_bool_indexing():
+    data = csr_matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
+    list_indices1 = [False, True, False]
+    array_indices1 = np.array(list_indices1)
+    list_indices2 = [[False, True, False], [False, True, False], [False, True, False]]
+    array_indices2 = np.array(list_indices2)
+    list_indices3 = ([False, True, False], [False, True, False])
+    array_indices3 = (np.array(list_indices3[0]), np.array(list_indices3[1]))
+    slice_list1 = data[list_indices1].toarray()
+    slice_array1 = data[array_indices1].toarray()
+    slice_list2 = data[list_indices2]
+    slice_array2 = data[array_indices2]
+    slice_list3 = data[list_indices3]
+    slice_array3 = data[array_indices3]
+    assert (slice_list1 == slice_array1).all()
+    assert (slice_list2 == slice_array2).all()
+    assert (slice_list3 == slice_array3).all()
+
+
+def test_csr_hstack_int64():
+    """
+    Tests if hstack properly promotes to indices and indptr arrays to np.int64
+    when using np.int32 during concatenation would result in either array
+    overflowing.
+    """
+    max_int32 = np.iinfo(np.int32).max
+
+    # First case: indices would overflow with int32
+    data = [1.0]
+    row = [0]
+
+    max_indices_1 = max_int32 - 1
+    max_indices_2 = 3
+
+    # Individual indices arrays are representable with int32
+    col_1 = [max_indices_1 - 1]
+    col_2 = [max_indices_2 - 1]
+
+    X_1 = csr_matrix((data, (row, col_1)))
+    X_2 = csr_matrix((data, (row, col_2)))
+
+    assert max(max_indices_1 - 1, max_indices_2 - 1) < max_int32
+    assert X_1.indices.dtype == X_1.indptr.dtype == np.int32
+    assert X_2.indices.dtype == X_2.indptr.dtype == np.int32
+
+    # ... but when concatenating their CSR matrices, the resulting indices
+    # array can't be represented with int32 and must be promoted to int64.
+    X_hs = hstack([X_1, X_2], format="csr")
+
+    assert X_hs.indices.max() == max_indices_1 + max_indices_2 - 1
+    assert max_indices_1 + max_indices_2 - 1 > max_int32
+    assert X_hs.indices.dtype == X_hs.indptr.dtype == np.int64
+
+    # Even if the matrices are empty, we must account for their size
+    # contribution so that we may safely set the final elements.
+    X_1_empty = csr_matrix(X_1.shape)
+    X_2_empty = csr_matrix(X_2.shape)
+    X_hs_empty = hstack([X_1_empty, X_2_empty], format="csr")
+
+    assert X_hs_empty.shape == X_hs.shape
+    assert X_hs_empty.indices.dtype == np.int64
+
+    # Should be just small enough to stay in int32 after stack. Note that
+    # we theoretically could support indices.max() == max_int32, but due to an
+    # edge-case in the underlying sparsetools code
+    # (namely the `coo_tocsr` routine),
+    # we require that max(X_hs_32.shape) < max_int32 as well.
+    # Hence we can only support max_int32 - 1.
+    col_3 = [max_int32 - max_indices_1 - 1]
+    X_3 = csr_matrix((data, (row, col_3)))
+    X_hs_32 = hstack([X_1, X_3], format="csr")
+    assert X_hs_32.indices.dtype == np.int32
+    assert X_hs_32.indices.max() == max_int32 - 1
+
+@pytest.mark.parametrize("cls", [csr_matrix, csr_array, csc_matrix, csc_array])
+def test_mixed_index_dtype_int_indexing(cls):
+    # https://github.com/scipy/scipy/issues/20182
+    rng = np.random.default_rng(0)
+    base_mtx = cls(sparse.random(50, 50, random_state=rng, density=0.1))
+    indptr_64bit = base_mtx.copy()
+    indices_64bit = base_mtx.copy()
+    indptr_64bit.indptr = base_mtx.indptr.astype(np.int64)
+    indices_64bit.indices = base_mtx.indices.astype(np.int64)
+
+    for mtx in [base_mtx, indptr_64bit, indices_64bit]:
+        np.testing.assert_array_equal(
+            mtx[[1,2], :].toarray(),
+            base_mtx[[1, 2], :].toarray()
+        )
+        np.testing.assert_array_equal(
+            mtx[:, [1, 2]].toarray(),
+            base_mtx[:, [1, 2]].toarray()
+        )
+
+def test_broadcast_to():
+    a = np.array([1, 0, 2])
+    b = np.array([3])
+    e = np.zeros((0,))
+    res_a = csr_array(a)._broadcast_to((2,3))
+    res_b = csr_array(b)._broadcast_to((4,))
+    res_c = csr_array(b)._broadcast_to((2,4))
+    res_d = csr_array(b)._broadcast_to((1,))
+    res_e = csr_array(e)._broadcast_to((4,0))
+    assert_array_equal(res_a.toarray(), np.broadcast_to(a, (2,3)))
+    assert_array_equal(res_b.toarray(), np.broadcast_to(b, (4,)))
+    assert_array_equal(res_c.toarray(), np.broadcast_to(b, (2,4)))
+    assert_array_equal(res_d.toarray(), np.broadcast_to(b, (1,)))
+    assert_array_equal(res_e.toarray(), np.broadcast_to(e, (4,0)))
+
+    with pytest.raises(ValueError, match="cannot be broadcast"):
+        csr_matrix([[1, 2, 0], [3, 0, 1]])._broadcast_to(shape=(2, 1))
+
+    with pytest.raises(ValueError, match="cannot be broadcast"):
+        csr_matrix([[0, 1, 2]])._broadcast_to(shape=(3, 2))
+
+    with pytest.raises(ValueError, match="cannot be broadcast"):
+        csr_array([0, 1, 2])._broadcast_to(shape=(3, 2))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3deda1668c3f526cfb205131a1348c620f25d20
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py
@@ -0,0 +1,209 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_equal
+import scipy as sp
+from scipy.sparse import dok_array, dok_matrix
+
+
+pytestmark = pytest.mark.thread_unsafe
+
+
+@pytest.fixture
+def d():
+    return {(0, 1): 1, (0, 2): 2}
+
+@pytest.fixture
+def A():
+    return np.array([[0, 1, 2], [0, 0, 0], [0, 0, 0]])
+
+@pytest.fixture(params=[dok_array, dok_matrix])
+def Asp(request):
+    A = request.param((3, 3))
+    A[(0, 1)] = 1
+    A[(0, 2)] = 2
+    yield A
+
+# Note: __iter__ and comparison dunders act like ndarrays for DOK, not dict.
+# Dunders reversed, or, ror, ior work as dict for dok_matrix, raise for dok_array
+# All other dict methods on DOK format act like dict methods (with extra checks).
+
+# Start of tests
+################
+def test_dict_methods_covered(d, Asp):
+    d_methods = set(dir(d)) - {"__class_getitem__"}
+    asp_methods = set(dir(Asp))
+    assert d_methods < asp_methods
+
+def test_clear(d, Asp):
+    assert d.items() == Asp.items()
+    d.clear()
+    Asp.clear()
+    assert d.items() == Asp.items()
+
+def test_copy(d, Asp):
+    assert d.items() == Asp.items()
+    dd = d.copy()
+    asp = Asp.copy()
+    assert dd.items() == asp.items()
+    assert asp.items() == Asp.items()
+    asp[(0, 1)] = 3
+    assert Asp[(0, 1)] == 1
+
+def test_fromkeys_default():
+    # test with default value
+    edges = [(0, 2), (1, 0), (2, 1)]
+    Xdok = dok_array.fromkeys(edges)
+    X = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]
+    assert_equal(Xdok.toarray(), X)
+
+def test_fromkeys_positional():
+    # test with positional value
+    edges = [(0, 2), (1, 0), (2, 1)]
+    Xdok = dok_array.fromkeys(edges, -1)
+    X = [[0, 0, -1], [-1, 0, 0], [0, -1, 0]]
+    assert_equal(Xdok.toarray(), X)
+
+def test_fromkeys_iterator():
+    it = ((a, a % 2) for a in range(4))
+    Xdok = dok_array.fromkeys(it)
+    X = [[1, 0], [0, 1], [1, 0], [0, 1]]
+    assert_equal(Xdok.toarray(), X)
+
+def test_get(d, Asp):
+    assert Asp.get((0, 1)) == d.get((0, 1))
+    assert Asp.get((0, 0), 99) == d.get((0, 0), 99)
+    with pytest.raises(IndexError, match="out of bounds"):
+        Asp.get((0, 4), 99)
+
+def test_items(d, Asp):
+    assert Asp.items() == d.items()
+
+def test_keys(d, Asp):
+    assert Asp.keys() == d.keys()
+
+def test_pop(d, Asp):
+    assert d.pop((0, 1)) == 1
+    assert Asp.pop((0, 1)) == 1
+    assert d.items() == Asp.items()
+
+    assert Asp.pop((22, 21), None) is None
+    assert Asp.pop((22, 21), "other") == "other"
+    with pytest.raises(KeyError, match="(22, 21)"):
+        Asp.pop((22, 21))
+    with pytest.raises(TypeError, match="got an unexpected keyword argument"):
+        Asp.pop((22, 21), default=5)
+
+def test_popitem(d, Asp):
+    assert d.popitem() == Asp.popitem()
+    assert d.items() == Asp.items()
+
+def test_setdefault(d, Asp):
+    assert Asp.setdefault((0, 1), 4) == 1
+    assert Asp.setdefault((2, 2), 4) == 4
+    d.setdefault((0, 1), 4)
+    d.setdefault((2, 2), 4)
+    assert d.items() == Asp.items()
+
+def test_update(d, Asp):
+    with pytest.raises(NotImplementedError):
+        Asp.update(Asp)
+
+def test_values(d, Asp):
+    # Note: dict.values are strange: d={1: 1}; d.values() == d.values() is False
+    # Using list(d.values()) makes them comparable.
+    assert list(Asp.values()) == list(d.values())
+
+def test_dunder_getitem(d, Asp):
+    assert Asp[(0, 1)] == d[(0, 1)]
+
+def test_dunder_setitem(d, Asp):
+    Asp[(1, 1)] = 5
+    d[(1, 1)] = 5
+    assert d.items() == Asp.items()
+
+def test_dunder_delitem(d, Asp):
+    del Asp[(0, 1)]
+    del d[(0, 1)]
+    assert d.items() == Asp.items()
+
+def test_dunder_contains(d, Asp):
+    assert ((0, 1) in d) == ((0, 1) in Asp)
+    assert ((0, 0) in d) == ((0, 0) in Asp)
+
+def test_dunder_len(d, Asp):
+    assert len(d) == len(Asp)
+
+# Note: dunders reversed, or, ror, ior work as dict for dok_matrix, raise for dok_array
+def test_dunder_reversed(d, Asp):
+    if isinstance(Asp, dok_array):
+        with pytest.raises(TypeError):
+            list(reversed(Asp))
+    else:
+        assert list(reversed(Asp)) == list(reversed(d))
+
+def test_dunder_ior(d, Asp):
+    if isinstance(Asp, dok_array):
+        with pytest.raises(TypeError):
+            Asp |= Asp
+    else:
+        dd = {(0, 0): 5}
+        Asp |= dd
+        assert Asp[(0, 0)] == 5
+        d |= dd
+        assert d.items() == Asp.items()
+        dd |= Asp
+        assert dd.items() == Asp.items()
+
+def test_dunder_or(d, Asp):
+    if isinstance(Asp, dok_array):
+        with pytest.raises(TypeError):
+            Asp | Asp
+    else:
+        assert d | d == Asp | d
+        assert d | d == Asp | Asp
+
+def test_dunder_ror(d, Asp):
+    if isinstance(Asp, dok_array):
+        with pytest.raises(TypeError):
+            Asp | Asp
+        with pytest.raises(TypeError):
+            d | Asp
+    else:
+        assert Asp.__ror__(d) == Asp.__ror__(Asp)
+        assert d.__ror__(d) == Asp.__ror__(d)
+        assert d | Asp
+
+# Note: comparison dunders, e.g. ==, >=, etc follow np.array not dict
+def test_dunder_eq(A, Asp):
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(sp.sparse.SparseEfficiencyWarning)
+        assert (Asp == Asp).toarray().all()
+        assert (A == Asp).all()
+
+def test_dunder_ne(A, Asp):
+    assert not (Asp != Asp).toarray().any()
+    assert not (A != Asp).any()
+
+def test_dunder_lt(A, Asp):
+    assert not (Asp < Asp).toarray().any()
+    assert not (A < Asp).any()
+
+def test_dunder_gt(A, Asp):
+    assert not (Asp > Asp).toarray().any()
+    assert not (A > Asp).any()
+
+def test_dunder_le(A, Asp):
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(sp.sparse.SparseEfficiencyWarning)
+        assert (Asp <= Asp).toarray().all()
+        assert (A <= Asp).all()
+
+def test_dunder_ge(A, Asp):
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(sp.sparse.SparseEfficiencyWarning)
+        assert (Asp >= Asp).toarray().all()
+        assert (A >= Asp).all()
+
+# Note: iter dunder follows np.array not dict
+def test_dunder_iter(A, Asp):
+    assert all((a == asp).all() for a, asp in zip(A, Asp))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7c9f68bb2bde76d74ca767abba3c99b89d6e771
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py
@@ -0,0 +1,51 @@
+"""test sparse matrix construction functions"""
+
+from numpy.testing import assert_equal
+from scipy.sparse import csr_matrix, csr_array, sparray
+
+import numpy as np
+from scipy.sparse import _extract
+
+
+class TestExtract:
+    def setup_method(self):
+        self.cases = [
+            csr_array([[1,2]]),
+            csr_array([[1,0]]),
+            csr_array([[0,0]]),
+            csr_array([[1],[2]]),
+            csr_array([[1],[0]]),
+            csr_array([[0],[0]]),
+            csr_array([[1,2],[3,4]]),
+            csr_array([[0,1],[0,0]]),
+            csr_array([[0,0],[1,0]]),
+            csr_array([[0,0],[0,0]]),
+            csr_array([[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]]),
+            csr_array([[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]]).T,
+        ]
+
+    def test_find(self):
+        for A in self.cases:
+            I,J,V = _extract.find(A)
+            B = csr_array((V,(I,J)), shape=A.shape)
+            assert_equal(A.toarray(), B.toarray())
+
+    def test_tril(self):
+        for A in self.cases:
+            B = A.toarray()
+            for k in [-3,-2,-1,0,1,2,3]:
+                assert_equal(_extract.tril(A,k=k).toarray(), np.tril(B,k=k))
+
+    def test_triu(self):
+        for A in self.cases:
+            B = A.toarray()
+            for k in [-3,-2,-1,0,1,2,3]:
+                assert_equal(_extract.triu(A,k=k).toarray(), np.triu(B,k=k))
+
+    def test_array_vs_matrix(self):
+        for A in self.cases:
+            assert isinstance(_extract.tril(A), sparray)
+            assert isinstance(_extract.triu(A), sparray)
+            M = csr_matrix(A)
+            assert not isinstance(_extract.tril(M), sparray)
+            assert not isinstance(_extract.triu(M), sparray)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..99934c455b796511b9f48243da044a9cee8a4d53
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py
@@ -0,0 +1,603 @@
+import contextlib
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+
+from scipy.sparse import csr_array, dok_array, SparseEfficiencyWarning
+from .test_arithmetic1d import toarray
+
+
+formats_for_index1d = [csr_array, dok_array]
+
+
+@contextlib.contextmanager
+def check_remains_sorted(X):
+    """Checks that sorted indices property is retained through an operation"""
+    yield
+    if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices:
+        return
+    indices = X.indices.copy()
+    X.has_sorted_indices = False
+    X.sort_indices()
+    assert_equal(indices, X.indices, 'Expected sorted indices, found unsorted')
+
+
+@pytest.mark.parametrize("spcreator", formats_for_index1d)
+class TestGetSet1D:
+    def test_None_index(self, spcreator):
+        D = np.array([4, 3, 0])
+        A = spcreator(D)
+
+        N = D.shape[0]
+        for j in range(-N, N):
+            assert_equal(A[j, None].toarray(), D[j, None])
+            assert_equal(A[None, j].toarray(), D[None, j])
+            assert_equal(A[None, None, j].toarray(), D[None, None, j])
+
+    def test_getitem_shape(self, spcreator):
+        A = spcreator(np.arange(3 * 4).reshape(3, 4))
+        assert A[1, 2].ndim == 0
+        assert A[1, 2:3].shape == (1,)
+        assert A[None, 1, 2:3].shape == (1, 1)
+        assert A[None, 1, 2].shape == (1,)
+        assert A[None, 1, 2, None].shape == (1, 1)
+
+        # see gh-22458
+        assert A[None, 1].shape == (1, 4)
+        assert A[1, None].shape == (1, 4)
+        assert A[None, 1, :].shape == (1, 4)
+        assert A[1, None, :].shape == (1, 4)
+        assert A[1, :, None].shape == (4, 1)
+
+        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
+            A[None, 2, 1, None, None]
+        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
+            A[None, 0:2, None, 1]
+        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
+            A[0:1, 1:, None]
+        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
+            A[1:, 1, None, None]
+
+    def test_getelement(self, spcreator):
+        D = np.array([4, 3, 0])
+        A = spcreator(D)
+
+        N = D.shape[0]
+        for j in range(-N, N):
+            assert_equal(A[j], D[j])
+
+        for ij in [3, -4]:
+            with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'):
+                A.__getitem__(ij)
+
+        # single element tuples unwrapped
+        assert A[(0,)] == 4
+
+        with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'):
+            A.__getitem__((4,))
+
+    def test_setelement(self, spcreator):
+        dtype = np.float64
+        A = spcreator((12,), dtype=dtype)
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            A[0] = dtype(0)
+            A[1] = dtype(3)
+            A[8] = dtype(9.0)
+            A[-2] = dtype(7)
+            A[5] = 9
+
+            A[-9,] = dtype(8)
+            A[1,] = dtype(5)  # overwrite using 1-tuple index
+
+            for ij in [13, -14, (13,), (14,)]:
+                with pytest.raises(IndexError, match='out of (range|bounds)'):
+                    A.__setitem__(ij, 123.0)
+
+
+@pytest.mark.parametrize("spcreator", formats_for_index1d)
+class TestSlicingAndFancy1D:
+    #######################
+    #  Int-like Array Index
+    #######################
+    def test_get_array_index(self, spcreator):
+        D = np.array([4, 3, 0])
+        A = spcreator(D)
+
+        assert_equal(A[()].toarray(), D[()])
+        for ij in [(0, 3), (3,)]:
+            with pytest.raises(IndexError, match='out of (range|bounds)|many indices'):
+                A.__getitem__(ij)
+
+    def test_set_array_index(self, spcreator):
+        dtype = np.float64
+        A = spcreator((12,), dtype=dtype)
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            A[np.array(6)] = dtype(4.0)  # scalar index
+            A[np.array(6)] = dtype(2.0)  # overwrite with scalar index
+            assert_equal(A.toarray(), [0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0])
+
+            for ij in [(13,), (-14,)]:
+                with pytest.raises(IndexError, match='index .* out of (range|bounds)'):
+                    A.__setitem__(ij, 123.0)
+
+            for v in [(), (0, 3), [1, 2, 3], np.array([1, 2, 3])]:
+                msg = 'Trying to assign a sequence to an item'
+                with pytest.raises(ValueError, match=msg):
+                    A.__setitem__(0, v)
+
+    ####################
+    #  1d Slice as index
+    ####################
+    def test_dtype_preservation(self, spcreator):
+        assert_equal(spcreator((10,), dtype=np.int16)[1:5].dtype, np.int16)
+        assert_equal(spcreator((6,), dtype=np.int32)[0:0:2].dtype, np.int32)
+        assert_equal(spcreator((6,), dtype=np.int64)[:].dtype, np.int64)
+
+    def test_get_1d_slice(self, spcreator):
+        B = np.arange(50.)
+        A = spcreator(B)
+        assert_equal(B[:], A[:].toarray())
+        assert_equal(B[2:5], A[2:5].toarray())
+
+        C = np.array([4, 0, 6, 0, 0, 0, 0, 0, 1])
+        D = spcreator(C)
+        assert_equal(C[1:3], D[1:3].toarray())
+
+        # Now test slicing when a row contains only zeros
+        E = np.array([0, 0, 0, 0, 0])
+        F = spcreator(E)
+        assert_equal(E[1:3], F[1:3].toarray())
+        assert_equal(E[-2:], F[-2:].toarray())
+        assert_equal(E[:], F[:].toarray())
+        assert_equal(E[slice(None)], F[slice(None)].toarray())
+
+    def test_slicing_idx_slice(self, spcreator):
+        B = np.arange(50)
+        A = spcreator(B)
+
+        # [i]
+        assert_equal(A[2], B[2])
+        assert_equal(A[-1], B[-1])
+        assert_equal(A[np.array(-2)], B[-2])
+
+        # [1:2]
+        assert_equal(A[:].toarray(), B[:])
+        assert_equal(A[5:-2].toarray(), B[5:-2])
+        assert_equal(A[5:12:3].toarray(), B[5:12:3])
+
+        # int8 slice
+        s = slice(np.int8(2), np.int8(4), None)
+        assert_equal(A[s].toarray(), B[2:4])
+
+        # np.s_
+        s_ = np.s_
+        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
+                  s_[15:20], s_[3:2],
+                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
+                  0, 1, s_[:], s_[1:5], -1, -2, -5,
+                  np.array(-1), np.int8(-3)]
+
+        for j, a in enumerate(slices):
+            x = A[a]
+            y = B[a]
+            if y.shape == ():
+                assert_equal(x, y, repr(a))
+            else:
+                if x.size == 0 and y.size == 0:
+                    pass
+                else:
+                    assert_equal(x.toarray(), y, repr(a))
+
+    def test_ellipsis_1d_slicing(self, spcreator):
+        B = np.arange(50)
+        A = spcreator(B)
+        assert_equal(A[...].toarray(), B[...])
+        assert_equal(A[...,].toarray(), B[...,])
+
+    ##########################
+    #  Assignment with Slicing
+    ##########################
+    def test_slice_scalar_assign(self, spcreator):
+        A = spcreator((5,))
+        B = np.zeros((5,))
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            for C in [A, B]:
+                C[0:1] = 1
+                C[2:0] = 4
+                C[2:3] = 9
+                C[3:] = 1
+                C[3::-1] = 9
+        assert_equal(A.toarray(), B)
+
+    def test_slice_assign_2(self, spcreator):
+        shape = (10,)
+
+        for idx in [slice(3), slice(None, 10, 4), slice(5, -2)]:
+            A = spcreator(shape)
+            with np.testing.suppress_warnings() as sup:
+                sup.filter(
+                    SparseEfficiencyWarning,
+                    "Changing the sparsity structure of .* is expensive",
+                )
+                A[idx] = 1
+            B = np.zeros(shape)
+            B[idx] = 1
+            msg = f"idx={idx!r}"
+            assert_allclose(A.toarray(), B, err_msg=msg)
+
+    def test_self_self_assignment(self, spcreator):
+        # Tests whether a row of one lil_matrix can be assigned to another.
+        B = spcreator((5,))
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            B[0] = 2
+            B[1] = 0
+            B[2] = 3
+            B[3] = 10
+
+            A = B / 10
+            B[:] = A[:]
+            assert_equal(A[:].toarray(), B[:].toarray())
+
+            A = B / 10
+            B[:] = A[:1]
+            assert_equal(np.zeros((5,)) + A[0], B.toarray())
+
+            A = B / 10
+            B[:-1] = A[1:]
+            assert_equal(A[1:].toarray(), B[:-1].toarray())
+
+    def test_slice_assignment(self, spcreator):
+        B = spcreator((4,))
+        expected = np.array([10, 0, 14, 0])
+        block = [2, 1]
+
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            B[0] = 5
+            B[2] = 7
+            B[:] = B + B
+            assert_equal(B.toarray(), expected)
+
+            B[:2] = csr_array(block)
+            assert_equal(B.toarray()[:2], block)
+
+    def test_set_slice(self, spcreator):
+        A = spcreator((5,))
+        B = np.zeros(5, float)
+        s_ = np.s_
+        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
+                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
+                  0, 1, s_[:], s_[1:5], -1, -2, -5,
+                  np.array(-1), np.int8(-3)]
+
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            for j, a in enumerate(slices):
+                A[a] = j
+                B[a] = j
+                assert_equal(A.toarray(), B, repr(a))
+
+            A[1:10:2] = range(1, 5, 2)
+            B[1:10:2] = range(1, 5, 2)
+            assert_equal(A.toarray(), B)
+
+        # The next commands should raise exceptions
+        toobig = list(range(100))
+        with pytest.raises(ValueError, match='Trying to assign a sequence to an item'):
+            A.__setitem__(0, toobig)
+        with pytest.raises(ValueError, match='could not be broadcast together'):
+            A.__setitem__(slice(None), toobig)
+
+    def test_assign_empty(self, spcreator):
+        A = spcreator(np.ones(3))
+        B = spcreator((2,))
+        A[:2] = B
+        assert_equal(A.toarray(), [0, 0, 1])
+
+    ####################
+    #  1d Fancy Indexing
+    ####################
+    def test_dtype_preservation_empty_index(self, spcreator):
+        A = spcreator((2,), dtype=np.int16)
+        assert_equal(A[[False, False]].dtype, np.int16)
+        assert_equal(A[[]].dtype, np.int16)
+
+    def test_bad_index(self, spcreator):
+        A = spcreator(np.zeros(5))
+        with pytest.raises(
+            (IndexError, ValueError, TypeError),
+            match='Index dimension must be 1 or 2|only integers',
+        ):
+            A.__getitem__("foo")
+        with pytest.raises(
+            (IndexError, ValueError, TypeError),
+            match='tuple index out of range|only integers',
+        ):
+            A.__getitem__((2, "foo"))
+
+    def test_fancy_indexing_2darray(self, spcreator):
+        B = np.arange(50).reshape((5, 10))
+        A = spcreator(B)
+
+        # [i]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+
+        # [i,[1,2]]
+        assert_equal(A[3, [1, 3]].toarray(), B[3, [1, 3]])
+        assert_equal(A[-1, [2, -5]].toarray(), B[-1, [2, -5]])
+        assert_equal(A[np.array(-1), [2, -5]].toarray(), B[-1, [2, -5]])
+        assert_equal(A[-1, np.array([2, -5])].toarray(), B[-1, [2, -5]])
+        assert_equal(A[np.array(-1), np.array([2, -5])].toarray(), B[-1, [2, -5]])
+
+        # [1:2,[1,2]]
+        assert_equal(A[:, [2, 8, 3, -1]].toarray(), B[:, [2, 8, 3, -1]])
+        assert_equal(A[3:4, [9]].toarray(), B[3:4, [9]])
+        assert_equal(A[1:4, [-1, -5]].toarray(), B[1:4, [-1, -5]])
+        assert_equal(A[1:4, np.array([-1, -5])].toarray(), B[1:4, [-1, -5]])
+
+        # [[1,2],j]
+        assert_equal(A[[1, 3], 3].toarray(), B[[1, 3], 3])
+        assert_equal(A[[2, -5], -4].toarray(), B[[2, -5], -4])
+        assert_equal(A[np.array([2, -5]), -4].toarray(), B[[2, -5], -4])
+        assert_equal(A[[2, -5], np.array(-4)].toarray(), B[[2, -5], -4])
+        assert_equal(A[np.array([2, -5]), np.array(-4)].toarray(), B[[2, -5], -4])
+
+        # [[1,2],1:2]
+        assert_equal(A[[1, 3], :].toarray(), B[[1, 3], :])
+        assert_equal(A[[2, -5], 8:-1].toarray(), B[[2, -5], 8:-1])
+        assert_equal(A[np.array([2, -5]), 8:-1].toarray(), B[[2, -5], 8:-1])
+
+        # [[1,2],[1,2]]
+        assert_equal(toarray(A[[1, 3], [2, 4]]), B[[1, 3], [2, 4]])
+        assert_equal(toarray(A[[-1, -3], [2, -4]]), B[[-1, -3], [2, -4]])
+        assert_equal(
+            toarray(A[np.array([-1, -3]), [2, -4]]), B[[-1, -3], [2, -4]]
+        )
+        assert_equal(
+            toarray(A[[-1, -3], np.array([2, -4])]), B[[-1, -3], [2, -4]]
+        )
+        assert_equal(
+            toarray(A[np.array([-1, -3]), np.array([2, -4])]), B[[-1, -3], [2, -4]]
+        )
+
+        # [[[1],[2]],[1,2]]
+        assert_equal(A[[[1], [3]], [2, 4]].toarray(), B[[[1], [3]], [2, 4]])
+        assert_equal(
+            A[[[-1], [-3], [-2]], [2, -4]].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[np.array([[-1], [-3], [-2]]), [2, -4]].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[[[-1], [-3], [-2]], np.array([2, -4])].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[np.array([[-1], [-3], [-2]]), np.array([2, -4])].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+
+        # [[1,2]]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+        assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
+        assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]])
+
+        # [[1,2],:][:,[1,2]]
+        assert_equal(
+            A[[1, 3], :][:, [2, 4]].toarray(), B[[1, 3], :][:, [2, 4]]
+        )
+        assert_equal(
+            A[[-1, -3], :][:, [2, -4]].toarray(), B[[-1, -3], :][:, [2, -4]]
+        )
+        assert_equal(
+            A[np.array([-1, -3]), :][:, np.array([2, -4])].toarray(),
+            B[[-1, -3], :][:, [2, -4]]
+        )
+
+        # [:,[1,2]][[1,2],:]
+        assert_equal(
+            A[:, [1, 3]][[2, 4], :].toarray(), B[:, [1, 3]][[2, 4], :]
+        )
+        assert_equal(
+            A[:, [-1, -3]][[2, -4], :].toarray(), B[:, [-1, -3]][[2, -4], :]
+        )
+        assert_equal(
+            A[:, np.array([-1, -3])][np.array([2, -4]), :].toarray(),
+            B[:, [-1, -3]][[2, -4], :]
+        )
+
+    def test_fancy_indexing(self, spcreator):
+        B = np.arange(50)
+        A = spcreator(B)
+
+        # [i]
+        assert_equal(A[[3]].toarray(), B[[3]])
+
+        # [np.array]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+        assert_equal(A[[2, -5]].toarray(), B[[2, -5]])
+        assert_equal(A[np.array(-1)], B[-1])
+        assert_equal(A[np.array([-1, 2])].toarray(), B[[-1, 2]])
+        assert_equal(A[np.array(5)], B[np.array(5)])
+
+        # [[[1],[2]]]
+        ind = np.array([[1], [3]])
+        assert_equal(A[ind].toarray(), B[ind])
+        ind = np.array([[-1], [-3], [-2]])
+        assert_equal(A[ind].toarray(), B[ind])
+
+        # [[1, 2]]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+        assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
+        assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]])
+
+        # [[1, 2]][[1, 2]]
+        assert_equal(A[[1, 5, 2, 8]][[1, 3]].toarray(),
+                     B[[1, 5, 2, 8]][[1, 3]])
+        assert_equal(A[[-1, -5, 2, 8]][[1, -4]].toarray(),
+                     B[[-1, -5, 2, 8]][[1, -4]])
+
+    def test_fancy_indexing_boolean(self, spcreator):
+        np.random.seed(1234)  # make runs repeatable
+
+        B = np.arange(50)
+        A = spcreator(B)
+
+        I = np.array(np.random.randint(0, 2, size=50), dtype=bool)
+
+        assert_equal(toarray(A[I]), B[I])
+        assert_equal(toarray(A[B > 9]), B[B > 9])
+
+        Z1 = np.zeros(51, dtype=bool)
+        Z2 = np.zeros(51, dtype=bool)
+        Z2[-1] = True
+        Z3 = np.zeros(51, dtype=bool)
+        Z3[0] = True
+
+        msg = 'bool index .* has shape|boolean index did not match'
+        with pytest.raises(IndexError, match=msg):
+            A.__getitem__(Z1)
+        with pytest.raises(IndexError, match=msg):
+            A.__getitem__(Z2)
+        with pytest.raises(IndexError, match=msg):
+            A.__getitem__(Z3)
+
+    def test_fancy_indexing_sparse_boolean(self, spcreator):
+        np.random.seed(1234)  # make runs repeatable
+
+        B = np.arange(20)
+        A = spcreator(B)
+
+        X = np.array(np.random.randint(0, 2, size=20), dtype=bool)
+        Xsp = csr_array(X)
+
+        assert_equal(toarray(A[Xsp]), B[X])
+        assert_equal(toarray(A[A > 9]), B[B > 9])
+
+        Y = np.array(np.random.randint(0, 2, size=60), dtype=bool)
+
+        Ysp = csr_array(Y)
+
+        with pytest.raises(IndexError, match='bool index .* has shape|only integers'):
+            A.__getitem__(Ysp)
+        with pytest.raises(IndexError, match='tuple index out of range|only integers'):
+            A.__getitem__((Xsp, 1))
+
+    def test_fancy_indexing_seq_assign(self, spcreator):
+        mat = spcreator(np.array([1, 0]))
+        with pytest.raises(ValueError, match='Trying to assign a sequence to an item'):
+            mat.__setitem__(0, np.array([1, 2]))
+
+    def test_fancy_indexing_empty(self, spcreator):
+        B = np.arange(50)
+        B[3:9] = 0
+        B[30] = 0
+        A = spcreator(B)
+
+        K = np.array([False] * 50)
+        assert_equal(toarray(A[K]), B[K])
+        K = np.array([], dtype=int)
+        assert_equal(toarray(A[K]), B[K])
+        J = np.array([0, 1, 2, 3, 4], dtype=int)
+        assert_equal(toarray(A[J]), B[J])
+
+    ############################
+    #  1d Fancy Index Assignment
+    ############################
+    def test_bad_index_assign(self, spcreator):
+        A = spcreator(np.zeros(5))
+        msg = 'Index dimension must be 1 or 2|only integers'
+        with pytest.raises((IndexError, ValueError, TypeError), match=msg):
+            A.__setitem__("foo", 2)
+
+    def test_fancy_indexing_set(self, spcreator):
+        M = (5,)
+
+        # [1:2]
+        for j in [[2, 3, 4], slice(None, 10, 4), np.arange(3),
+                     slice(5, -2), slice(2, 5)]:
+            A = spcreator(M)
+            B = np.zeros(M)
+            with np.testing.suppress_warnings() as sup:
+                sup.filter(
+                    SparseEfficiencyWarning,
+                    "Changing the sparsity structure of .* is expensive",
+                )
+                B[j] = 1
+                with check_remains_sorted(A):
+                    A[j] = 1
+            assert_allclose(A.toarray(), B)
+
+    def test_sequence_assignment(self, spcreator):
+        A = spcreator((4,))
+        B = spcreator((3,))
+
+        i0 = [0, 1, 2]
+        i1 = (0, 1, 2)
+        i2 = np.array(i0)
+
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            with check_remains_sorted(A):
+                A[i0] = B[i0]
+                msg = "too many indices for array|tuple index out of range"
+                with pytest.raises(IndexError, match=msg):
+                    B.__getitem__(i1)
+                A[i2] = B[i2]
+            assert_equal(A[:3].toarray(), B.toarray())
+            assert A.shape == (4,)
+
+            # slice
+            A = spcreator((4,))
+            with check_remains_sorted(A):
+                A[1:3] = [10, 20]
+            assert_equal(A.toarray(), [0, 10, 20, 0])
+
+            # array
+            A = spcreator((4,))
+            B = np.zeros(4)
+            with check_remains_sorted(A):
+                for C in [A, B]:
+                    C[[0, 1, 2]] = [4, 5, 6]
+            assert_equal(A.toarray(), B)
+
+    def test_fancy_assign_empty(self, spcreator):
+        B = np.arange(50)
+        B[2] = 0
+        B[[3, 6]] = 0
+        A = spcreator(B)
+
+        K = np.array([False] * 50)
+        A[K] = 42
+        assert_equal(A.toarray(), B)
+
+        K = np.array([], dtype=int)
+        A[K] = 42
+        assert_equal(A.toarray(), B)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b4ea64a8928073eb5dd3f1b2752379f57327d9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py
@@ -0,0 +1,109 @@
+import os
+import numpy as np
+import tempfile
+
+from pytest import raises as assert_raises
+from numpy.testing import assert_equal, assert_
+
+from scipy.sparse import (sparray, csc_matrix, csr_matrix, bsr_matrix, dia_matrix,
+                          coo_matrix, dok_matrix, csr_array, save_npz, load_npz)
+
+
+DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
+
+
+def _save_and_load(matrix):
+    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
+    os.close(fd)
+    try:
+        save_npz(tmpfile, matrix)
+        loaded_matrix = load_npz(tmpfile)
+    finally:
+        os.remove(tmpfile)
+    return loaded_matrix
+
+def _check_save_and_load(dense_matrix):
+    for matrix_class in [csc_matrix, csr_matrix, bsr_matrix, dia_matrix, coo_matrix]:
+        matrix = matrix_class(dense_matrix)
+        loaded_matrix = _save_and_load(matrix)
+        assert_(type(loaded_matrix) is matrix_class)
+        assert_(loaded_matrix.shape == dense_matrix.shape)
+        assert_(loaded_matrix.dtype == dense_matrix.dtype)
+        assert_equal(loaded_matrix.toarray(), dense_matrix)
+
+def test_save_and_load_random():
+    N = 10
+    np.random.seed(0)
+    dense_matrix = np.random.random((N, N))
+    dense_matrix[dense_matrix > 0.7] = 0
+    _check_save_and_load(dense_matrix)
+
+def test_save_and_load_empty():
+    dense_matrix = np.zeros((4,6))
+    _check_save_and_load(dense_matrix)
+
+def test_save_and_load_one_entry():
+    dense_matrix = np.zeros((4,6))
+    dense_matrix[1,2] = 1
+    _check_save_and_load(dense_matrix)
+
+def test_sparray_vs_spmatrix():
+    #save/load matrix
+    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
+    os.close(fd)
+    try:
+        save_npz(tmpfile, csr_matrix([[1.2, 0, 0.9], [0, 0.3, 0]]))
+        loaded_matrix = load_npz(tmpfile)
+    finally:
+        os.remove(tmpfile)
+
+    #save/load array
+    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
+    os.close(fd)
+    try:
+        save_npz(tmpfile, csr_array([[1.2, 0, 0.9], [0, 0.3, 0]]))
+        loaded_array = load_npz(tmpfile)
+    finally:
+        os.remove(tmpfile)
+
+    assert not isinstance(loaded_matrix, sparray)
+    assert isinstance(loaded_array, sparray)
+    assert_(loaded_matrix.dtype == loaded_array.dtype)
+    assert_equal(loaded_matrix.toarray(), loaded_array.toarray())
+
+def test_malicious_load():
+    class Executor:
+        def __reduce__(self):
+            return (assert_, (False, 'unexpected code execution'))
+
+    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
+    os.close(fd)
+    try:
+        np.savez(tmpfile, format=Executor())
+
+        # Should raise a ValueError, not execute code
+        assert_raises(ValueError, load_npz, tmpfile)
+    finally:
+        os.remove(tmpfile)
+
+
+def test_py23_compatibility():
+    # Try loading files saved on Python 2 and Python 3.  They are not
+    # the same, since files saved with SciPy versions < 1.0.0 may
+    # contain unicode.
+
+    a = load_npz(os.path.join(DATA_DIR, 'csc_py2.npz'))
+    b = load_npz(os.path.join(DATA_DIR, 'csc_py3.npz'))
+    c = csc_matrix([[0]])
+
+    assert_equal(a.toarray(), c.toarray())
+    assert_equal(b.toarray(), c.toarray())
+
+def test_implemented_error():
+    # Attempts to save an unsupported type and checks that an
+    # NotImplementedError is raised.
+
+    x = dok_matrix((2,3))
+    x[0,1] = 1
+
+    assert_raises(NotImplementedError, save_npz, 'x.npz', x)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..dca3f44fa485070805995c2f76c0c511123ce355
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py
@@ -0,0 +1,128 @@
+"""Test of min-max 1D features of sparse array classes"""
+
+import pytest
+
+import numpy as np
+
+from numpy.testing import assert_equal, assert_array_equal
+
+from scipy.sparse import coo_array, csr_array, csc_array, bsr_array
+from scipy.sparse import coo_matrix, csr_matrix, csc_matrix, bsr_matrix
+from scipy.sparse._sputils import isscalarlike
+
+
+def toarray(a):
+    if isinstance(a, np.ndarray) or isscalarlike(a):
+        return a
+    return a.toarray()
+
+
+formats_for_minmax = [bsr_array, coo_array, csc_array, csr_array]
+formats_for_minmax_supporting_1d = [coo_array, csr_array]
+
+
+@pytest.mark.parametrize("spcreator", formats_for_minmax_supporting_1d)
+class Test_MinMaxMixin1D:
+    def test_minmax(self, spcreator):
+        D = np.arange(5)
+        X = spcreator(D)
+
+        assert_equal(X.min(), 0)
+        assert_equal(X.max(), 4)
+        assert_equal((-X).min(), -4)
+        assert_equal((-X).max(), 0)
+
+    def test_minmax_axis(self, spcreator):
+        D = np.arange(50)
+        X = spcreator(D)
+
+        for axis in [0, -1]:
+            assert_array_equal(
+                toarray(X.max(axis=axis)), D.max(axis=axis, keepdims=True)
+            )
+            assert_array_equal(
+                toarray(X.min(axis=axis)), D.min(axis=axis, keepdims=True)
+            )
+        for axis in [-2, 1]:
+            with pytest.raises(ValueError, match="axis out of range"):
+                X.min(axis=axis)
+            with pytest.raises(ValueError, match="axis out of range"):
+                X.max(axis=axis)
+
+    def test_numpy_minmax(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+        assert_array_equal(np.min(datsp), np.min(dat))
+        assert_array_equal(np.max(datsp), np.max(dat))
+
+
+    def test_argmax(self, spcreator):
+        D1 = np.array([-1, 5, 2, 3])
+        D2 = np.array([0, 0, -1, -2])
+        D3 = np.array([-1, -2, -3, -4])
+        D4 = np.array([1, 2, 3, 4])
+        D5 = np.array([1, 2, 0, 0])
+
+        for D in [D1, D2, D3, D4, D5]:
+            mat = spcreator(D)
+
+            assert_equal(mat.argmax(), np.argmax(D))
+            assert_equal(mat.argmin(), np.argmin(D))
+
+            assert_equal(mat.argmax(axis=0), np.argmax(D, axis=0))
+            assert_equal(mat.argmin(axis=0), np.argmin(D, axis=0))
+
+        D6 = np.empty((0,))
+
+        for axis in [None, 0]:
+            mat = spcreator(D6)
+            with pytest.raises(ValueError, match="to an empty matrix"):
+                mat.argmin(axis=axis)
+            with pytest.raises(ValueError, match="to an empty matrix"):
+                mat.argmax(axis=axis)
+
+
+@pytest.mark.parametrize("spcreator", formats_for_minmax)
+class Test_ShapeMinMax2DWithAxis:
+    def test_minmax(self, spcreator):
+        dat = np.array([[-1, 5, 0, 3], [0, 0, -1, -2], [0, 0, 1, 2]])
+        datsp = spcreator(dat)
+
+        for (spminmax, npminmax) in [
+            (datsp.min, np.min),
+            (datsp.max, np.max),
+            (datsp.nanmin, np.nanmin),
+            (datsp.nanmax, np.nanmax),
+        ]:
+            for ax, result_shape in [(0, (4,)), (1, (3,))]:
+                assert_equal(toarray(spminmax(axis=ax)), npminmax(dat, axis=ax))
+                assert_equal(spminmax(axis=ax).shape, result_shape)
+                assert spminmax(axis=ax).format == "coo"
+
+        for spminmax in [datsp.argmin, datsp.argmax]:
+            for ax in [0, 1]:
+                assert isinstance(spminmax(axis=ax), np.ndarray)
+
+        # verify spmatrix behavior
+        spmat_form = {
+            'coo': coo_matrix,
+            'csr': csr_matrix,
+            'csc': csc_matrix,
+            'bsr': bsr_matrix,
+        }
+        datspm = spmat_form[datsp.format](dat)
+
+        for spm, npm in [
+            (datspm.min, np.min),
+            (datspm.max, np.max),
+            (datspm.nanmin, np.nanmin),
+            (datspm.nanmax, np.nanmax),
+        ]:
+            for ax, result_shape in [(0, (1, 4)), (1, (3, 1))]:
+                assert_equal(toarray(spm(axis=ax)), npm(dat, axis=ax, keepdims=True))
+                assert_equal(spm(axis=ax).shape, result_shape)
+                assert spm(axis=ax).format == "coo"
+
+        for spminmax in [datspm.argmin, datspm.argmax]:
+            for ax in [0, 1]:
+                assert isinstance(spminmax(axis=ax), np.ndarray)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a8b94796116a22c210104fc446c5a17045ed21c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py
@@ -0,0 +1,339 @@
+import sys
+import os
+import gc
+import threading
+
+import numpy as np
+from numpy.testing import assert_equal, assert_, assert_allclose
+from scipy.sparse import (_sparsetools, coo_matrix, csr_matrix, csc_matrix,
+                          bsr_matrix, dia_matrix)
+from scipy.sparse._sputils import supported_dtypes
+from scipy._lib._testutils import check_free_memory
+
+import pytest
+from pytest import raises as assert_raises
+
+
+def int_to_int8(n):
+    """
+    Wrap an integer to the interval [-128, 127].
+    """
+    return (n + 128) % 256 - 128
+
+
+def test_exception():
+    assert_raises(MemoryError, _sparsetools.test_throw_error)
+
+
+def test_threads():
+    # Smoke test for parallel threaded execution; doesn't actually
+    # check that code runs in parallel, but just that it produces
+    # expected results.
+    nthreads = 10
+    niter = 100
+
+    n = 20
+    a = csr_matrix(np.ones([n, n]))
+    bres = []
+
+    class Worker(threading.Thread):
+        def run(self):
+            b = a.copy()
+            for j in range(niter):
+                _sparsetools.csr_plus_csr(n, n,
+                                          a.indptr, a.indices, a.data,
+                                          a.indptr, a.indices, a.data,
+                                          b.indptr, b.indices, b.data)
+            bres.append(b)
+
+    threads = [Worker() for _ in range(nthreads)]
+    for thread in threads:
+        thread.start()
+    for thread in threads:
+        thread.join()
+
+    for b in bres:
+        assert_(np.all(b.toarray() == 2))
+
+
+def test_regression_std_vector_dtypes():
+    # Regression test for gh-3780, checking the std::vector typemaps
+    # in sparsetools.cxx are complete.
+    for dtype in supported_dtypes:
+        ad = np.array([[1, 2], [3, 4]]).astype(dtype)
+        a = csr_matrix(ad, dtype=dtype)
+
+        # getcol is one function using std::vector typemaps, and should not fail
+        assert_equal(a.getcol(0).toarray(), ad[:, :1])
+
+
+@pytest.mark.slow
+@pytest.mark.xfail_on_32bit("Can't create large array for test")
+def test_nnz_overflow():
+    # Regression test for gh-7230 / gh-7871, checking that coo_toarray
+    # with nnz > int32max doesn't overflow.
+    nnz = np.iinfo(np.int32).max + 1
+    # Ensure ~20 GB of RAM is free to run this test.
+    check_free_memory((4 + 4 + 1) * nnz / 1e6 + 0.5)
+
+    # Use nnz duplicate entries to keep the dense version small.
+    row = np.zeros(nnz, dtype=np.int32)
+    col = np.zeros(nnz, dtype=np.int32)
+    data = np.zeros(nnz, dtype=np.int8)
+    data[-1] = 4
+    s = coo_matrix((data, (row, col)), shape=(1, 1), copy=False)
+    # Sums nnz duplicates to produce a 1x1 array containing 4.
+    d = s.toarray()
+
+    assert_allclose(d, [[4]])
+
+
+@pytest.mark.skipif(
+    not (sys.platform.startswith('linux') and np.dtype(np.intp).itemsize >= 8),
+    reason="test requires 64-bit Linux"
+)
+class TestInt32Overflow:
+    """
+    Some of the sparsetools routines use dense 2D matrices whose
+    total size is not bounded by the nnz of the sparse matrix. These
+    routines used to suffer from int32 wraparounds; here, we try to
+    check that the wraparounds don't occur any more.
+    """
+    # choose n large enough
+    n = 50000
+
+    def setup_method(self):
+        assert self.n**2 > np.iinfo(np.int32).max
+
+        # check there's enough memory even if everything is run at the
+        # same time
+        try:
+            parallel_count = int(os.environ.get('PYTEST_XDIST_WORKER_COUNT', '1'))
+        except ValueError:
+            parallel_count = np.inf
+
+        check_free_memory(3000 * parallel_count)
+
+    def teardown_method(self):
+        gc.collect()
+
+    def test_coo_todense(self):
+        # Check *_todense routines (cf. gh-2179)
+        #
+        # All of them in the end call coo_matrix.todense
+
+        n = self.n
+
+        i = np.array([0, n-1])
+        j = np.array([0, n-1])
+        data = np.array([1, 2], dtype=np.int8)
+        m = coo_matrix((data, (i, j)))
+
+        r = m.todense()
+        assert_equal(r[0,0], 1)
+        assert_equal(r[-1,-1], 2)
+        del r
+        gc.collect()
+
+    @pytest.mark.slow
+    def test_matvecs(self):
+        # Check *_matvecs routines
+        n = self.n
+
+        i = np.array([0, n-1])
+        j = np.array([0, n-1])
+        data = np.array([1, 2], dtype=np.int8)
+        m = coo_matrix((data, (i, j)))
+
+        b = np.ones((n, n), dtype=np.int8)
+        for sptype in (csr_matrix, csc_matrix, bsr_matrix):
+            m2 = sptype(m)
+            r = m2.dot(b)
+            assert_equal(r[0,0], 1)
+            assert_equal(r[-1,-1], 2)
+            del r
+            gc.collect()
+
+        del b
+        gc.collect()
+
+    @pytest.mark.slow
+    def test_dia_matvec(self):
+        # Check: huge dia_matrix _matvec
+        n = self.n
+        data = np.ones((n, n), dtype=np.int8)
+        offsets = np.arange(n)
+        m = dia_matrix((data, offsets), shape=(n, n))
+        v = np.ones(m.shape[1], dtype=np.int8)
+        r = m.dot(v)
+        assert_equal(r[0], int_to_int8(n))
+        del data, offsets, m, v, r
+        gc.collect()
+
+    _bsr_ops = [pytest.param("matmat", marks=pytest.mark.xslow),
+                pytest.param("matvecs", marks=pytest.mark.xslow),
+                "matvec",
+                "diagonal",
+                "sort_indices",
+                pytest.param("transpose", marks=pytest.mark.xslow)]
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize("op", _bsr_ops)
+    def test_bsr_1_block(self, op):
+        # Check: huge bsr_matrix (1-block)
+        #
+        # The point here is that indices inside a block may overflow.
+
+        def get_matrix():
+            n = self.n
+            data = np.ones((1, n, n), dtype=np.int8)
+            indptr = np.array([0, 1], dtype=np.int32)
+            indices = np.array([0], dtype=np.int32)
+            m = bsr_matrix((data, indices, indptr), blocksize=(n, n), copy=False)
+            del data, indptr, indices
+            return m
+
+        gc.collect()
+        try:
+            getattr(self, "_check_bsr_" + op)(get_matrix)
+        finally:
+            gc.collect()
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize("op", _bsr_ops)
+    def test_bsr_n_block(self, op):
+        # Check: huge bsr_matrix (n-block)
+        #
+        # The point here is that while indices within a block don't
+        # overflow, accumulators across many block may.
+
+        def get_matrix():
+            n = self.n
+            data = np.ones((n, n, 1), dtype=np.int8)
+            indptr = np.array([0, n], dtype=np.int32)
+            indices = np.arange(n, dtype=np.int32)
+            m = bsr_matrix((data, indices, indptr), blocksize=(n, 1), copy=False)
+            del data, indptr, indices
+            return m
+
+        gc.collect()
+        try:
+            getattr(self, "_check_bsr_" + op)(get_matrix)
+        finally:
+            gc.collect()
+
+    def _check_bsr_matvecs(self, m):  # skip name check
+        m = m()
+        n = self.n
+
+        # _matvecs
+        r = m.dot(np.ones((n, 2), dtype=np.int8))
+        assert_equal(r[0, 0], int_to_int8(n))
+
+    def _check_bsr_matvec(self, m):  # skip name check
+        m = m()
+        n = self.n
+
+        # _matvec
+        r = m.dot(np.ones((n,), dtype=np.int8))
+        assert_equal(r[0], int_to_int8(n))
+
+    def _check_bsr_diagonal(self, m):  # skip name check
+        m = m()
+        n = self.n
+
+        # _diagonal
+        r = m.diagonal()
+        assert_equal(r, np.ones(n))
+
+    def _check_bsr_sort_indices(self, m):  # skip name check
+        # _sort_indices
+        m = m()
+        m.sort_indices()
+
+    def _check_bsr_transpose(self, m):  # skip name check
+        # _transpose
+        m = m()
+        m.transpose()
+
+    def _check_bsr_matmat(self, m):  # skip name check
+        m = m()
+        n = self.n
+
+        # _bsr_matmat
+        m2 = bsr_matrix(np.ones((n, 2), dtype=np.int8), blocksize=(m.blocksize[1], 2))
+        m.dot(m2)  # shouldn't SIGSEGV
+        del m2
+
+        # _bsr_matmat
+        m2 = bsr_matrix(np.ones((2, n), dtype=np.int8), blocksize=(2, m.blocksize[0]))
+        m2.dot(m)  # shouldn't SIGSEGV
+
+
+@pytest.mark.skip(reason="64-bit indices in sparse matrices not available")
+def test_csr_matmat_int64_overflow():
+    n = 3037000500
+    assert n**2 > np.iinfo(np.int64).max
+
+    # the test would take crazy amounts of memory
+    check_free_memory(n * (8*2 + 1) * 3 / 1e6)
+
+    # int64 overflow
+    data = np.ones((n,), dtype=np.int8)
+    indptr = np.arange(n+1, dtype=np.int64)
+    indices = np.zeros(n, dtype=np.int64)
+    a = csr_matrix((data, indices, indptr))
+    b = a.T
+
+    assert_raises(RuntimeError, a.dot, b)
+
+
+def test_upcast():
+    a0 = csr_matrix([[np.pi, np.pi*1j], [3, 4]], dtype=complex)
+    b0 = np.array([256+1j, 2**32], dtype=complex)
+
+    for a_dtype in supported_dtypes:
+        for b_dtype in supported_dtypes:
+            msg = f"({a_dtype!r}, {b_dtype!r})"
+
+            if np.issubdtype(a_dtype, np.complexfloating):
+                a = a0.copy().astype(a_dtype)
+            else:
+                a = a0.real.copy().astype(a_dtype)
+
+            if np.issubdtype(b_dtype, np.complexfloating):
+                b = b0.copy().astype(b_dtype)
+            else:
+                with np.errstate(invalid="ignore"):
+                    # Casting a large value (2**32) to int8 causes a warning in
+                    # numpy >1.23
+                    b = b0.real.copy().astype(b_dtype)
+
+            if not (a_dtype == np.bool_ and b_dtype == np.bool_):
+                c = np.zeros((2,), dtype=np.bool_)
+                assert_raises(ValueError, _sparsetools.csr_matvec,
+                              2, 2, a.indptr, a.indices, a.data, b, c)
+
+            if ((np.issubdtype(a_dtype, np.complexfloating) and
+                 not np.issubdtype(b_dtype, np.complexfloating)) or
+                (not np.issubdtype(a_dtype, np.complexfloating) and
+                 np.issubdtype(b_dtype, np.complexfloating))):
+                c = np.zeros((2,), dtype=np.float64)
+                assert_raises(ValueError, _sparsetools.csr_matvec,
+                              2, 2, a.indptr, a.indices, a.data, b, c)
+
+            c = np.zeros((2,), dtype=np.result_type(a_dtype, b_dtype))
+            _sparsetools.csr_matvec(2, 2, a.indptr, a.indices, a.data, b, c)
+            assert_allclose(c, np.dot(a.toarray(), b), err_msg=msg)
+
+
+def test_endianness():
+    d = np.ones((3,4))
+    offsets = [-1,0,1]
+
+    a = dia_matrix((d.astype('f8'), offsets), (4, 4))
+    v = np.arange(4)
+
+    assert_allclose(a.dot(v), [1, 3, 6, 5])
+    assert_allclose(b.dot(v), [1, 3, 6, 5])
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..75bc2d92c369be5799a904bc0938617f30321f12
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py
@@ -0,0 +1,97 @@
+from numpy import array, kron, diag
+from numpy.testing import assert_, assert_equal
+
+from scipy.sparse import _spfuncs as spfuncs
+from scipy.sparse import csr_matrix, csc_matrix, bsr_matrix
+from scipy.sparse._sparsetools import (csr_scale_rows, csr_scale_columns,
+                                       bsr_scale_rows, bsr_scale_columns)
+
+
+class TestSparseFunctions:
+    def test_scale_rows_and_cols(self):
+        D = array([[1, 0, 0, 2, 3],
+                   [0, 4, 0, 5, 0],
+                   [0, 0, 6, 7, 0]])
+
+        #TODO expose through function
+        S = csr_matrix(D)
+        v = array([1,2,3])
+        csr_scale_rows(3,5,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), diag(v)@D)
+
+        S = csr_matrix(D)
+        v = array([1,2,3,4,5])
+        csr_scale_columns(3,5,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), D@diag(v))
+
+        # blocks
+        E = kron(D,[[1,2],[3,4]])
+        S = bsr_matrix(E,blocksize=(2,2))
+        v = array([1,2,3,4,5,6])
+        bsr_scale_rows(3,5,2,2,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), diag(v)@E)
+
+        S = bsr_matrix(E,blocksize=(2,2))
+        v = array([1,2,3,4,5,6,7,8,9,10])
+        bsr_scale_columns(3,5,2,2,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), E@diag(v))
+
+        E = kron(D,[[1,2,3],[4,5,6]])
+        S = bsr_matrix(E,blocksize=(2,3))
+        v = array([1,2,3,4,5,6])
+        bsr_scale_rows(3,5,2,3,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), diag(v)@E)
+
+        S = bsr_matrix(E,blocksize=(2,3))
+        v = array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
+        bsr_scale_columns(3,5,2,3,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), E@diag(v))
+
+    def test_estimate_blocksize(self):
+        mats = []
+        mats.append([[0,1],[1,0]])
+        mats.append([[1,1,0],[0,0,1],[1,0,1]])
+        mats.append([[0],[0],[1]])
+        mats = [array(x) for x in mats]
+
+        blks = []
+        blks.append([[1]])
+        blks.append([[1,1],[1,1]])
+        blks.append([[1,1],[0,1]])
+        blks.append([[1,1,0],[1,0,1],[1,1,1]])
+        blks = [array(x) for x in blks]
+
+        for A in mats:
+            for B in blks:
+                X = kron(A,B)
+                r,c = spfuncs.estimate_blocksize(X)
+                assert_(r >= B.shape[0])
+                assert_(c >= B.shape[1])
+
+    def test_count_blocks(self):
+        def gold(A,bs):
+            R,C = bs
+            I,J = A.nonzero()
+            return len(set(zip(I//R,J//C)))
+
+        mats = []
+        mats.append([[0]])
+        mats.append([[1]])
+        mats.append([[1,0]])
+        mats.append([[1,1]])
+        mats.append([[0,1],[1,0]])
+        mats.append([[1,1,0],[0,0,1],[1,0,1]])
+        mats.append([[0],[0],[1]])
+
+        for A in mats:
+            for B in mats:
+                X = kron(A,B)
+                Y = csr_matrix(X)
+                for R in range(1,6):
+                    for C in range(1,6):
+                        assert_equal(spfuncs.count_blocks(Y, (R, C)), gold(X, (R, C)))
+
+        X = kron([[1,1,0],[0,0,1],[1,0,1]],[[1,1]])
+        Y = csc_matrix(X)
+        assert_equal(spfuncs.count_blocks(X, (1, 2)), gold(X, (1, 2)))
+        assert_equal(spfuncs.count_blocks(Y, (1, 2)), gold(X, (1, 2)))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb328e3f6512081f76604c4b92fe3d407819e448
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py
@@ -0,0 +1,395 @@
+"""unit tests for sparse utility functions"""
+
+import numpy as np
+from numpy.testing import assert_equal
+import pytest
+from pytest import raises as assert_raises
+from scipy.sparse import _sputils as sputils, csr_array, bsr_array, dia_array, coo_array
+from scipy.sparse._sputils import matrix
+
+
+class TestSparseUtils:
+
+    def test_upcast(self):
+        assert_equal(sputils.upcast('intc'), np.intc)
+        assert_equal(sputils.upcast('int32', 'float32'), np.float64)
+        assert_equal(sputils.upcast('bool', complex, float), np.complex128)
+        assert_equal(sputils.upcast('i', 'd'), np.float64)
+
+    def test_getdtype(self):
+        A = np.array([1], dtype='int8')
+
+        assert_equal(sputils.getdtype(None, default=float), float)
+        assert_equal(sputils.getdtype(None, a=A), np.int8)
+
+        with assert_raises(
+            ValueError,
+            match="scipy.sparse does not support dtype object. .*",
+        ):
+            sputils.getdtype("O")
+
+        with assert_raises(
+            ValueError,
+            match="scipy.sparse does not support dtype float16. .*",
+        ):
+            sputils.getdtype(None, default=np.float16)
+
+    def test_isscalarlike(self):
+        assert_equal(sputils.isscalarlike(3.0), True)
+        assert_equal(sputils.isscalarlike(-4), True)
+        assert_equal(sputils.isscalarlike(2.5), True)
+        assert_equal(sputils.isscalarlike(1 + 3j), True)
+        assert_equal(sputils.isscalarlike(np.array(3)), True)
+        assert_equal(sputils.isscalarlike("16"), True)
+
+        assert_equal(sputils.isscalarlike(np.array([3])), False)
+        assert_equal(sputils.isscalarlike([[3]]), False)
+        assert_equal(sputils.isscalarlike((1,)), False)
+        assert_equal(sputils.isscalarlike((1, 2)), False)
+
+    def test_isintlike(self):
+        assert_equal(sputils.isintlike(-4), True)
+        assert_equal(sputils.isintlike(np.array(3)), True)
+        assert_equal(sputils.isintlike(np.array([3])), False)
+        with assert_raises(
+            ValueError,
+            match="Inexact indices into sparse matrices are not allowed"
+        ):
+            sputils.isintlike(3.0)
+
+        assert_equal(sputils.isintlike(2.5), False)
+        assert_equal(sputils.isintlike(1 + 3j), False)
+        assert_equal(sputils.isintlike((1,)), False)
+        assert_equal(sputils.isintlike((1, 2)), False)
+
+    def test_isshape(self):
+        assert_equal(sputils.isshape((1, 2)), True)
+        assert_equal(sputils.isshape((5, 2)), True)
+
+        assert_equal(sputils.isshape((1.5, 2)), False)
+        assert_equal(sputils.isshape((2, 2, 2)), False)
+        assert_equal(sputils.isshape(([2], 2)), False)
+        assert_equal(sputils.isshape((-1, 2), nonneg=False),True)
+        assert_equal(sputils.isshape((2, -1), nonneg=False),True)
+        assert_equal(sputils.isshape((-1, 2), nonneg=True),False)
+        assert_equal(sputils.isshape((2, -1), nonneg=True),False)
+
+        assert_equal(sputils.isshape((1.5, 2), allow_nd=(1, 2)), False)
+        assert_equal(sputils.isshape(([2], 2), allow_nd=(1, 2)), False)
+        assert_equal(sputils.isshape((2, 2, -2), nonneg=True, allow_nd=(1, 2)),
+                     False)
+        assert_equal(sputils.isshape((2,), allow_nd=(1, 2)), True)
+        assert_equal(sputils.isshape((2, 2,), allow_nd=(1, 2)), True)
+        assert_equal(sputils.isshape((2, 2, 2), allow_nd=(1, 2)), False)
+
+    def test_issequence(self):
+        assert_equal(sputils.issequence((1,)), True)
+        assert_equal(sputils.issequence((1, 2, 3)), True)
+        assert_equal(sputils.issequence([1]), True)
+        assert_equal(sputils.issequence([1, 2, 3]), True)
+        assert_equal(sputils.issequence(np.array([1, 2, 3])), True)
+
+        assert_equal(sputils.issequence(np.array([[1], [2], [3]])), False)
+        assert_equal(sputils.issequence(3), False)
+
+    def test_ismatrix(self):
+        assert_equal(sputils.ismatrix(((),)), True)
+        assert_equal(sputils.ismatrix([[1], [2]]), True)
+        assert_equal(sputils.ismatrix(np.arange(3)[None]), True)
+
+        assert_equal(sputils.ismatrix([1, 2]), False)
+        assert_equal(sputils.ismatrix(np.arange(3)), False)
+        assert_equal(sputils.ismatrix([[[1]]]), False)
+        assert_equal(sputils.ismatrix(3), False)
+
+    def test_isdense(self):
+        assert_equal(sputils.isdense(np.array([1])), True)
+        assert_equal(sputils.isdense(matrix([1])), True)
+
+    def test_validateaxis(self):
+        assert_raises(TypeError, sputils.validateaxis, (0, 1))
+        assert_raises(TypeError, sputils.validateaxis, 1.5)
+        assert_raises(ValueError, sputils.validateaxis, 3)
+
+        # These function calls should not raise errors
+        for axis in (-2, -1, 0, 1, None):
+            sputils.validateaxis(axis)
+
+    @pytest.mark.parametrize("container", [csr_array, bsr_array])
+    def test_safely_cast_index_compressed(self, container):
+        # This is slow to test completely as nnz > imax is big
+        # and indptr is big for some shapes
+        # So we don't test large nnz, nor csc_array (same code as csr_array)
+        imax = np.int64(np.iinfo(np.int32).max)
+
+        # Shape 32bit
+        A32 = container((1, imax))
+        # indices big type, small values
+        B32 = A32.copy()
+        B32.indices = B32.indices.astype(np.int64)
+        B32.indptr = B32.indptr.astype(np.int64)
+
+        # Shape 64bit
+        # indices big type, small values
+        A64 = csr_array((1, imax + 1))
+        # indices small type, small values
+        B64 = A64.copy()
+        B64.indices = B64.indices.astype(np.int32)
+        B64.indptr = B64.indptr.astype(np.int32)
+        # indices big type, big values
+        C64 = A64.copy()
+        C64.indices = np.array([imax + 1], dtype=np.int64)
+        C64.indptr = np.array([0, 1], dtype=np.int64)
+        C64.data = np.array([2.2])
+
+        assert (A32.indices.dtype, A32.indptr.dtype) == (np.int32, np.int32)
+        assert (B32.indices.dtype, B32.indptr.dtype) == (np.int64, np.int64)
+        assert (A64.indices.dtype, A64.indptr.dtype) == (np.int64, np.int64)
+        assert (B64.indices.dtype, B64.indptr.dtype) == (np.int32, np.int32)
+        assert (C64.indices.dtype, C64.indptr.dtype) == (np.int64, np.int64)
+
+        for A in [A32, B32, A64, B64]:
+            indices, indptr = sputils.safely_cast_index_arrays(A, np.int32)
+            assert (indices.dtype, indptr.dtype) == (np.int32, np.int32)
+            indices, indptr = sputils.safely_cast_index_arrays(A, np.int64)
+            assert (indices.dtype, indptr.dtype) == (np.int64, np.int64)
+
+            indices, indptr = sputils.safely_cast_index_arrays(A, A.indices.dtype)
+            assert indices is A.indices
+            assert indptr is A.indptr
+
+        with assert_raises(ValueError):
+            sputils.safely_cast_index_arrays(C64, np.int32)
+        indices, indptr = sputils.safely_cast_index_arrays(C64, np.int64)
+        assert indices is C64.indices
+        assert indptr is C64.indptr
+
+    def test_safely_cast_index_coo(self):
+        # This is slow to test completely as nnz > imax is big
+        # So we don't test large nnz
+        imax = np.int64(np.iinfo(np.int32).max)
+
+        # Shape 32bit
+        A32 = coo_array((1, imax))
+        # coords big type, small values
+        B32 = A32.copy()
+        B32.coords = tuple(co.astype(np.int64) for co in B32.coords)
+
+        # Shape 64bit
+        # coords big type, small values
+        A64 = coo_array((1, imax + 1))
+        # coords small type, small values
+        B64 = A64.copy()
+        B64.coords = tuple(co.astype(np.int32) for co in B64.coords)
+        # coords big type, big values
+        C64 = A64.copy()
+        C64.coords = (np.array([imax + 1]), np.array([0]))
+        C64.data = np.array([2.2])
+
+        assert A32.coords[0].dtype == np.int32
+        assert B32.coords[0].dtype == np.int64
+        assert A64.coords[0].dtype == np.int64
+        assert B64.coords[0].dtype == np.int32
+        assert C64.coords[0].dtype == np.int64
+
+        for A in [A32, B32, A64, B64]:
+            coords = sputils.safely_cast_index_arrays(A, np.int32)
+            assert coords[0].dtype == np.int32
+            coords = sputils.safely_cast_index_arrays(A, np.int64)
+            assert coords[0].dtype == np.int64
+
+            coords = sputils.safely_cast_index_arrays(A, A.coords[0].dtype)
+            assert coords[0] is A.coords[0]
+
+        with assert_raises(ValueError):
+            sputils.safely_cast_index_arrays(C64, np.int32)
+        coords = sputils.safely_cast_index_arrays(C64, np.int64)
+        assert coords[0] is C64.coords[0]
+
+    def test_safely_cast_index_dia(self):
+        # This is slow to test completely as nnz > imax is big
+        # So we don't test large nnz
+        imax = np.int64(np.iinfo(np.int32).max)
+
+        # Shape 32bit
+        A32 = dia_array((1, imax))
+        # offsets big type, small values
+        B32 = A32.copy()
+        B32.offsets = B32.offsets.astype(np.int64)
+
+        # Shape 64bit
+        # offsets big type, small values
+        A64 = dia_array((1, imax + 2))
+        # offsets small type, small values
+        B64 = A64.copy()
+        B64.offsets = B64.offsets.astype(np.int32)
+        # offsets big type, big values
+        C64 = A64.copy()
+        C64.offsets = np.array([imax + 1])
+        C64.data = np.array([2.2])
+
+        assert A32.offsets.dtype == np.int32
+        assert B32.offsets.dtype == np.int64
+        assert A64.offsets.dtype == np.int64
+        assert B64.offsets.dtype == np.int32
+        assert C64.offsets.dtype == np.int64
+
+        for A in [A32, B32, A64, B64]:
+            offsets = sputils.safely_cast_index_arrays(A, np.int32)
+            assert offsets.dtype == np.int32
+            offsets = sputils.safely_cast_index_arrays(A, np.int64)
+            assert offsets.dtype == np.int64
+
+            offsets = sputils.safely_cast_index_arrays(A, A.offsets.dtype)
+            assert offsets is A.offsets
+
+        with assert_raises(ValueError):
+            sputils.safely_cast_index_arrays(C64, np.int32)
+        offsets = sputils.safely_cast_index_arrays(C64, np.int64)
+        assert offsets is C64.offsets
+
+    def test_get_index_dtype(self):
+        imax = np.int64(np.iinfo(np.int32).max)
+        too_big = imax + 1
+
+        # Check that uint32's with no values too large doesn't return
+        # int64
+        a1 = np.ones(90, dtype='uint32')
+        a2 = np.ones(90, dtype='uint32')
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)),
+            np.dtype('int32')
+        )
+
+        # Check that if we can not convert but all values are less than or
+        # equal to max that we can just convert to int32
+        a1[-1] = imax
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)),
+            np.dtype('int32')
+        )
+
+        # Check that if it can not convert directly and the contents are
+        # too large that we return int64
+        a1[-1] = too_big
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)),
+            np.dtype('int64')
+        )
+
+        # test that if can not convert and didn't specify to check_contents
+        # we return int64
+        a1 = np.ones(89, dtype='uint32')
+        a2 = np.ones(89, dtype='uint32')
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2))),
+            np.dtype('int64')
+        )
+
+        # Check that even if we have arrays that can be converted directly
+        # that if we specify a maxval directly it takes precedence
+        a1 = np.ones(12, dtype='uint32')
+        a2 = np.ones(12, dtype='uint32')
+        assert_equal(
+            np.dtype(sputils.get_index_dtype(
+                (a1, a2), maxval=too_big, check_contents=True
+            )),
+            np.dtype('int64')
+        )
+
+        # Check that an array with a too max size and maxval set
+        # still returns int64
+        a1[-1] = too_big
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2), maxval=too_big)),
+            np.dtype('int64')
+        )
+
+    # tests public broadcast_shapes largely from
+    # numpy/numpy/lib/tests/test_stride_tricks.py
+    # first 3 cause np.broadcast to raise index too large, but not sputils
+    @pytest.mark.parametrize("input_shapes,target_shape", [
+        [((6, 5, 1, 4, 1, 1), (1, 2**32), (2**32, 1)), (6, 5, 1, 4, 2**32, 2**32)],
+        [((6, 5, 1, 4, 1, 1), (1, 2**32)), (6, 5, 1, 4, 1, 2**32)],
+        [((1, 2**32), (2**32, 1)), (2**32, 2**32)],
+        [[2, 2, 2], (2,)],
+        [[], ()],
+        [[()], ()],
+        [[(7,)], (7,)],
+        [[(1, 2), (2,)], (1, 2)],
+        [[(2,), (1, 2)], (1, 2)],
+        [[(1, 1)], (1, 1)],
+        [[(1, 1), (3, 4)], (3, 4)],
+        [[(6, 7), (5, 6, 1), (7,), (5, 1, 7)], (5, 6, 7)],
+        [[(5, 6, 1)], (5, 6, 1)],
+        [[(1, 3), (3, 1)], (3, 3)],
+        [[(1, 0), (0, 0)], (0, 0)],
+        [[(0, 1), (0, 0)], (0, 0)],
+        [[(1, 0), (0, 1)], (0, 0)],
+        [[(1, 1), (0, 0)], (0, 0)],
+        [[(1, 1), (1, 0)], (1, 0)],
+        [[(1, 1), (0, 1)], (0, 1)],
+        [[(), (0,)], (0,)],
+        [[(0,), (0, 0)], (0, 0)],
+        [[(0,), (0, 1)], (0, 0)],
+        [[(1,), (0, 0)], (0, 0)],
+        [[(), (0, 0)], (0, 0)],
+        [[(1, 1), (0,)], (1, 0)],
+        [[(1,), (0, 1)], (0, 1)],
+        [[(1,), (1, 0)], (1, 0)],
+        [[(), (1, 0)], (1, 0)],
+        [[(), (0, 1)], (0, 1)],
+        [[(1,), (3,)], (3,)],
+        [[2, (3, 2)], (3, 2)],
+        [[(1, 2)] * 32, (1, 2)],
+        [[(1, 2)] * 100, (1, 2)],
+        [[(2,)] * 32, (2,)],
+    ])
+    def test_broadcast_shapes_successes(self, input_shapes, target_shape):
+        assert_equal(sputils.broadcast_shapes(*input_shapes), target_shape)
+
+    # tests public broadcast_shapes failures
+    @pytest.mark.parametrize("input_shapes", [
+        [(3,), (4,)],
+        [(2, 3), (2,)],
+        [2, (2, 3)],
+        [(3,), (3,), (4,)],
+        [(2, 5), (3, 5)],
+        [(2, 4), (2, 5)],
+        [(1, 3, 4), (2, 3, 3)],
+        [(1, 2), (3, 1), (3, 2), (10, 5)],
+        [(2,)] * 32 + [(3,)] * 32,
+    ])
+    def test_broadcast_shapes_failures(self, input_shapes):
+        with assert_raises(ValueError, match="cannot be broadcast"):
+            sputils.broadcast_shapes(*input_shapes)
+
+    def test_check_shape_overflow(self):
+        new_shape = sputils.check_shape([(10, -1)], (65535, 131070))
+        assert_equal(new_shape, (10, 858967245))
+
+    def test_matrix(self):
+        a = [[1, 2, 3]]
+        b = np.array(a)
+
+        assert isinstance(sputils.matrix(a), np.matrix)
+        assert isinstance(sputils.matrix(b), np.matrix)
+
+        c = sputils.matrix(b)
+        c[:, :] = 123
+        assert_equal(b, a)
+
+        c = sputils.matrix(b, copy=False)
+        c[:, :] = 123
+        assert_equal(b, [[123, 123, 123]])
+
+    def test_asmatrix(self):
+        a = [[1, 2, 3]]
+        b = np.array(a)
+
+        assert isinstance(sputils.asmatrix(a), np.matrix)
+        assert isinstance(sputils.asmatrix(b), np.matrix)
+
+        c = sputils.asmatrix(b)
+        c[:, :] = 123
+        assert_equal(b, [[123, 123, 123]])
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..1daa9fb379572aac4bc9b6d74330a18c5c52bf79
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd
@@ -0,0 +1 @@
+from scipy.special cimport cython_special
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8993f522a0fac00e243d361835a42b89a82d11ef
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/__init__.py
@@ -0,0 +1,887 @@
+"""
+========================================
+Special functions (:mod:`scipy.special`)
+========================================
+
+.. currentmodule:: scipy.special
+
+Almost all of the functions below accept NumPy arrays as input
+arguments as well as single numbers. This means they follow
+broadcasting and automatic array-looping rules. Technically,
+they are `NumPy universal functions
+`_.
+Functions which do not accept NumPy arrays are marked by a warning
+in the section description.
+
+.. seealso::
+
+   `scipy.special.cython_special` -- Typed Cython versions of special functions
+
+
+Error handling
+==============
+
+Errors are handled by returning NaNs or other appropriate values.
+Some of the special function routines can emit warnings or raise
+exceptions when an error occurs. By default this is disabled, except
+for memory allocation errors, which result in an exception being raised.
+To query and control the current error handling state the following
+functions are provided.
+
+.. autosummary::
+   :toctree: generated/
+
+   geterr                 -- Get the current way of handling special-function errors.
+   seterr                 -- Set how special-function errors are handled.
+   errstate               -- Context manager for special-function error handling.
+   SpecialFunctionWarning -- Warning that can be emitted by special functions.
+   SpecialFunctionError   -- Exception that can be raised by special functions.
+
+Available functions
+===================
+
+Airy functions
+--------------
+
+.. autosummary::
+   :toctree: generated/
+
+   airy     -- Airy functions and their derivatives.
+   airye    -- Exponentially scaled Airy functions and their derivatives.
+   ai_zeros -- Compute `nt` zeros and values of the Airy function Ai and its derivative.
+   bi_zeros -- Compute `nt` zeros and values of the Airy function Bi and its derivative.
+   itairy   -- Integrals of Airy functions
+
+
+Elliptic functions and integrals
+--------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   ellipj    -- Jacobian elliptic functions.
+   ellipk    -- Complete elliptic integral of the first kind.
+   ellipkm1  -- Complete elliptic integral of the first kind around `m` = 1.
+   ellipkinc -- Incomplete elliptic integral of the first kind.
+   ellipe    -- Complete elliptic integral of the second kind.
+   ellipeinc -- Incomplete elliptic integral of the second kind.
+   elliprc   -- Degenerate symmetric integral RC.
+   elliprd   -- Symmetric elliptic integral of the second kind.
+   elliprf   -- Completely-symmetric elliptic integral of the first kind.
+   elliprg   -- Completely-symmetric elliptic integral of the second kind.
+   elliprj   -- Symmetric elliptic integral of the third kind.
+
+Bessel functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   jv                -- Bessel function of the first kind of real order and \
+                        complex argument.
+   jve               -- Exponentially scaled Bessel function of order `v`.
+   yn                -- Bessel function of the second kind of integer order and \
+                        real argument.
+   yv                -- Bessel function of the second kind of real order and \
+                        complex argument.
+   yve               -- Exponentially scaled Bessel function of the second kind \
+                        of real order.
+   kn                -- Modified Bessel function of the second kind of integer \
+                        order `n`
+   kv                -- Modified Bessel function of the second kind of real order \
+                        `v`
+   kve               -- Exponentially scaled modified Bessel function of the \
+                        second kind.
+   iv                -- Modified Bessel function of the first kind of real order.
+   ive               -- Exponentially scaled modified Bessel function of the \
+                        first kind.
+   hankel1           -- Hankel function of the first kind.
+   hankel1e          -- Exponentially scaled Hankel function of the first kind.
+   hankel2           -- Hankel function of the second kind.
+   hankel2e          -- Exponentially scaled Hankel function of the second kind.
+   wright_bessel     -- Wright's generalized Bessel function.
+   log_wright_bessel -- Logarithm of Wright's generalized Bessel function.
+
+The following function does not accept NumPy arrays (it is not a
+universal function):
+
+.. autosummary::
+   :toctree: generated/
+
+   lmbda -- Jahnke-Emden Lambda function, Lambdav(x).
+
+Zeros of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   jnjnp_zeros -- Compute zeros of integer-order Bessel functions Jn and Jn'.
+   jnyn_zeros  -- Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
+   jn_zeros    -- Compute zeros of integer-order Bessel function Jn(x).
+   jnp_zeros   -- Compute zeros of integer-order Bessel function derivative Jn'(x).
+   yn_zeros    -- Compute zeros of integer-order Bessel function Yn(x).
+   ynp_zeros   -- Compute zeros of integer-order Bessel function derivative Yn'(x).
+   y0_zeros    -- Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
+   y1_zeros    -- Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
+   y1p_zeros   -- Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
+
+Faster versions of common Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   j0  -- Bessel function of the first kind of order 0.
+   j1  -- Bessel function of the first kind of order 1.
+   y0  -- Bessel function of the second kind of order 0.
+   y1  -- Bessel function of the second kind of order 1.
+   i0  -- Modified Bessel function of order 0.
+   i0e -- Exponentially scaled modified Bessel function of order 0.
+   i1  -- Modified Bessel function of order 1.
+   i1e -- Exponentially scaled modified Bessel function of order 1.
+   k0  -- Modified Bessel function of the second kind of order 0, :math:`K_0`.
+   k0e -- Exponentially scaled modified Bessel function K of order 0
+   k1  -- Modified Bessel function of the second kind of order 1, :math:`K_1(x)`.
+   k1e -- Exponentially scaled modified Bessel function K of order 1.
+
+Integrals of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   itj0y0     -- Integrals of Bessel functions of order 0.
+   it2j0y0    -- Integrals related to Bessel functions of order 0.
+   iti0k0     -- Integrals of modified Bessel functions of order 0.
+   it2i0k0    -- Integrals related to modified Bessel functions of order 0.
+   besselpoly -- Weighted integral of a Bessel function.
+
+Derivatives of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   jvp  -- Compute nth derivative of Bessel function Jv(z) with respect to `z`.
+   yvp  -- Compute nth derivative of Bessel function Yv(z) with respect to `z`.
+   kvp  -- Compute nth derivative of real-order modified Bessel function Kv(z)
+   ivp  -- Compute nth derivative of modified Bessel function Iv(z) with respect to `z`.
+   h1vp -- Compute nth derivative of Hankel function H1v(z) with respect to `z`.
+   h2vp -- Compute nth derivative of Hankel function H2v(z) with respect to `z`.
+
+Spherical Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   spherical_jn -- Spherical Bessel function of the first kind or its derivative.
+   spherical_yn -- Spherical Bessel function of the second kind or its derivative.
+   spherical_in -- Modified spherical Bessel function of the first kind or its derivative.
+   spherical_kn -- Modified spherical Bessel function of the second kind or its derivative.
+
+Riccati-Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   riccati_jn -- Compute Ricatti-Bessel function of the first kind and its derivative.
+   riccati_yn -- Compute Ricatti-Bessel function of the second kind and its derivative.
+
+Struve functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   struve       -- Struve function.
+   modstruve    -- Modified Struve function.
+   itstruve0    -- Integral of the Struve function of order 0.
+   it2struve0   -- Integral related to the Struve function of order 0.
+   itmodstruve0 -- Integral of the modified Struve function of order 0.
+
+
+Raw statistical functions
+-------------------------
+
+.. seealso:: :mod:`scipy.stats`: Friendly versions of these functions.
+
+Binomial distribution
+^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   bdtr         -- Binomial distribution cumulative distribution function.
+   bdtrc        -- Binomial distribution survival function.
+   bdtri        -- Inverse function to `bdtr` with respect to `p`.
+   bdtrik       -- Inverse function to `bdtr` with respect to `k`.
+   bdtrin       -- Inverse function to `bdtr` with respect to `n`.
+
+Beta distribution
+^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   btdtria      -- Inverse of `betainc` with respect to `a`.
+   btdtrib      -- Inverse of `betainc` with respect to `b`.
+
+F distribution
+^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   fdtr         -- F cumulative distribution function.
+   fdtrc        -- F survival function.
+   fdtri        -- The `p`-th quantile of the F-distribution.
+   fdtridfd     -- Inverse to `fdtr` vs dfd.
+
+Gamma distribution
+^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   gdtr         -- Gamma distribution cumulative distribution function.
+   gdtrc        -- Gamma distribution survival function.
+   gdtria       -- Inverse of `gdtr` vs a.
+   gdtrib       -- Inverse of `gdtr` vs b.
+   gdtrix       -- Inverse of `gdtr` vs x.
+
+Negative binomial distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nbdtr        -- Negative binomial cumulative distribution function.
+   nbdtrc       -- Negative binomial survival function.
+   nbdtri       -- Inverse of `nbdtr` vs `p`.
+   nbdtrik      -- Inverse of `nbdtr` vs `k`.
+   nbdtrin      -- Inverse of `nbdtr` vs `n`.
+
+Noncentral F distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   ncfdtr       -- Cumulative distribution function of the non-central F distribution.
+   ncfdtridfd   -- Calculate degrees of freedom (denominator) for the noncentral F-distribution.
+   ncfdtridfn   -- Calculate degrees of freedom (numerator) for the noncentral F-distribution.
+   ncfdtri      -- Inverse cumulative distribution function of the non-central F distribution.
+   ncfdtrinc    -- Calculate non-centrality parameter for non-central F distribution.
+
+Noncentral t distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nctdtr       -- Cumulative distribution function of the non-central `t` distribution.
+   nctdtridf    -- Calculate degrees of freedom for non-central t distribution.
+   nctdtrit     -- Inverse cumulative distribution function of the non-central t distribution.
+   nctdtrinc    -- Calculate non-centrality parameter for non-central t distribution.
+
+Normal distribution
+^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nrdtrimn     -- Calculate mean of normal distribution given other params.
+   nrdtrisd     -- Calculate standard deviation of normal distribution given other params.
+   ndtr         -- Normal cumulative distribution function.
+   log_ndtr     -- Logarithm of normal cumulative distribution function.
+   ndtri        -- Inverse of `ndtr` vs x.
+   ndtri_exp    -- Inverse of `log_ndtr` vs x.
+
+Poisson distribution
+^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   pdtr         -- Poisson cumulative distribution function.
+   pdtrc        -- Poisson survival function.
+   pdtri        -- Inverse to `pdtr` vs m.
+   pdtrik       -- Inverse to `pdtr` vs k.
+
+Student t distribution
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   stdtr        -- Student t distribution cumulative distribution function.
+   stdtridf     -- Inverse of `stdtr` vs df.
+   stdtrit      -- Inverse of `stdtr` vs `t`.
+
+Chi square distribution
+^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   chdtr        -- Chi square cumulative distribution function.
+   chdtrc       -- Chi square survival function.
+   chdtri       -- Inverse to `chdtrc`.
+   chdtriv      -- Inverse to `chdtr` vs `v`.
+
+Non-central chi square distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   chndtr       -- Non-central chi square cumulative distribution function.
+   chndtridf    -- Inverse to `chndtr` vs `df`.
+   chndtrinc    -- Inverse to `chndtr` vs `nc`.
+   chndtrix     -- Inverse to `chndtr` vs `x`.
+
+Kolmogorov distribution
+^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   smirnov      -- Kolmogorov-Smirnov complementary cumulative distribution function.
+   smirnovi     -- Inverse to `smirnov`.
+   kolmogorov   -- Complementary cumulative distribution function of Kolmogorov distribution.
+   kolmogi      -- Inverse function to `kolmogorov`.
+
+Box-Cox transformation
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   boxcox       -- Compute the Box-Cox transformation.
+   boxcox1p     -- Compute the Box-Cox transformation of 1 + `x`.
+   inv_boxcox   -- Compute the inverse of the Box-Cox transformation.
+   inv_boxcox1p -- Compute the inverse of the Box-Cox transformation.
+
+
+Sigmoidal functions
+^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   logit        -- Logit ufunc for ndarrays.
+   expit        -- Logistic sigmoid function.
+   log_expit    -- Logarithm of the logistic sigmoid function.
+
+Miscellaneous
+^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   tklmbda      -- Tukey-Lambda cumulative distribution function.
+   owens_t      -- Owen's T Function.
+
+
+Information Theory functions
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   entr         -- Elementwise function for computing entropy.
+   rel_entr     -- Elementwise function for computing relative entropy.
+   kl_div       -- Elementwise function for computing Kullback-Leibler divergence.
+   huber        -- Huber loss function.
+   pseudo_huber -- Pseudo-Huber loss function.
+
+
+Gamma and related functions
+---------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   gamma        -- Gamma function.
+   gammaln      -- Logarithm of the absolute value of the Gamma function for real inputs.
+   loggamma     -- Principal branch of the logarithm of the Gamma function.
+   gammasgn     -- Sign of the gamma function.
+   gammainc     -- Regularized lower incomplete gamma function.
+   gammaincinv  -- Inverse to `gammainc`.
+   gammaincc    -- Regularized upper incomplete gamma function.
+   gammainccinv -- Inverse to `gammaincc`.
+   beta         -- Beta function.
+   betaln       -- Natural logarithm of absolute value of beta function.
+   betainc      -- Incomplete beta integral.
+   betaincc     -- Complemented incomplete beta integral.
+   betaincinv   -- Inverse function to beta integral.
+   betainccinv  -- Inverse of the complemented incomplete beta integral.
+   psi          -- The digamma function.
+   rgamma       -- Gamma function inverted.
+   polygamma    -- Polygamma function n.
+   multigammaln -- Returns the log of multivariate gamma, also sometimes called the generalized gamma.
+   digamma      -- psi(x[, out]).
+   poch         -- Rising factorial (z)_m.
+
+Error function and Fresnel integrals
+------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   erf           -- Returns the error function of complex argument.
+   erfc          -- Complementary error function, ``1 - erf(x)``.
+   erfcx         -- Scaled complementary error function, ``exp(x**2) * erfc(x)``.
+   erfi          -- Imaginary error function, ``-i erf(i z)``.
+   erfinv        -- Inverse function for erf.
+   erfcinv       -- Inverse function for erfc.
+   wofz          -- Faddeeva function.
+   dawsn         -- Dawson's integral.
+   fresnel       -- Fresnel sin and cos integrals.
+   fresnel_zeros -- Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
+   modfresnelp   -- Modified Fresnel positive integrals.
+   modfresnelm   -- Modified Fresnel negative integrals.
+   voigt_profile -- Voigt profile.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   erf_zeros      -- Compute nt complex zeros of error function erf(z).
+   fresnelc_zeros -- Compute nt complex zeros of cosine Fresnel integral C(z).
+   fresnels_zeros -- Compute nt complex zeros of sine Fresnel integral S(z).
+
+Legendre functions
+------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   legendre_p                 -- Legendre polynomials of the first kind.
+   legendre_p_all             -- All Legendre polynomials of the first kind up to a specified order.
+   assoc_legendre_p           -- Associated Legendre polynomials of the first kind.
+   assoc_legendre_p_all       -- All associated Legendre polynomials of the first kind up to a specified order and degree.
+   sph_legendre_p             -- Spherical Legendre polynomials of the first kind.
+   sph_legendre_p_all         -- All spherical Legendre polynomials of the first kind up to a specified order and degree.
+   sph_harm_y                 -- Spherical harmonics.
+   sph_harm_y_all             -- All spherical harmonics up to a specified order and degree.
+
+The following functions are in the process of being deprecated in favor of the above,
+which provide a more flexible and consistent interface.
+
+.. autosummary::
+   :toctree: generated/
+
+   lpmv                       -- Associated Legendre function of integer order and real degree.
+   sph_harm                   -- Compute spherical harmonics.
+   clpmn                      -- Associated Legendre function of the first kind for complex arguments.
+   lpn                        -- Legendre function of the first kind.
+   lqn                        -- Legendre function of the second kind.
+   lpmn                       -- Sequence of associated Legendre functions of the first kind.
+   lqmn                       -- Sequence of associated Legendre functions of the second kind.
+
+Ellipsoidal harmonics
+---------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   ellip_harm   -- Ellipsoidal harmonic functions E^p_n(l).
+   ellip_harm_2 -- Ellipsoidal harmonic functions F^p_n(l).
+   ellip_normal -- Ellipsoidal harmonic normalization constants gamma^p_n.
+
+Orthogonal polynomials
+----------------------
+
+The following functions evaluate values of orthogonal polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   assoc_laguerre   -- Compute the generalized (associated) Laguerre polynomial of degree n and order k.
+   eval_legendre    -- Evaluate Legendre polynomial at a point.
+   eval_chebyt      -- Evaluate Chebyshev polynomial of the first kind at a point.
+   eval_chebyu      -- Evaluate Chebyshev polynomial of the second kind at a point.
+   eval_chebyc      -- Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a point.
+   eval_chebys      -- Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a point.
+   eval_jacobi      -- Evaluate Jacobi polynomial at a point.
+   eval_laguerre    -- Evaluate Laguerre polynomial at a point.
+   eval_genlaguerre -- Evaluate generalized Laguerre polynomial at a point.
+   eval_hermite     -- Evaluate physicist's Hermite polynomial at a point.
+   eval_hermitenorm -- Evaluate probabilist's (normalized) Hermite polynomial at a point.
+   eval_gegenbauer  -- Evaluate Gegenbauer polynomial at a point.
+   eval_sh_legendre -- Evaluate shifted Legendre polynomial at a point.
+   eval_sh_chebyt   -- Evaluate shifted Chebyshev polynomial of the first kind at a point.
+   eval_sh_chebyu   -- Evaluate shifted Chebyshev polynomial of the second kind at a point.
+   eval_sh_jacobi   -- Evaluate shifted Jacobi polynomial at a point.
+
+The following functions compute roots and quadrature weights for
+orthogonal polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   roots_legendre    -- Gauss-Legendre quadrature.
+   roots_chebyt      -- Gauss-Chebyshev (first kind) quadrature.
+   roots_chebyu      -- Gauss-Chebyshev (second kind) quadrature.
+   roots_chebyc      -- Gauss-Chebyshev (first kind) quadrature.
+   roots_chebys      -- Gauss-Chebyshev (second kind) quadrature.
+   roots_jacobi      -- Gauss-Jacobi quadrature.
+   roots_laguerre    -- Gauss-Laguerre quadrature.
+   roots_genlaguerre -- Gauss-generalized Laguerre quadrature.
+   roots_hermite     -- Gauss-Hermite (physicist's) quadrature.
+   roots_hermitenorm -- Gauss-Hermite (statistician's) quadrature.
+   roots_gegenbauer  -- Gauss-Gegenbauer quadrature.
+   roots_sh_legendre -- Gauss-Legendre (shifted) quadrature.
+   roots_sh_chebyt   -- Gauss-Chebyshev (first kind, shifted) quadrature.
+   roots_sh_chebyu   -- Gauss-Chebyshev (second kind, shifted) quadrature.
+   roots_sh_jacobi   -- Gauss-Jacobi (shifted) quadrature.
+
+The functions below, in turn, return the polynomial coefficients in
+``orthopoly1d`` objects, which function similarly as `numpy.poly1d`.
+The ``orthopoly1d`` class also has an attribute ``weights``, which returns
+the roots, weights, and total weights for the appropriate form of Gaussian
+quadrature. These are returned in an ``n x 3`` array with roots in the first
+column, weights in the second column, and total weights in the final column.
+Note that ``orthopoly1d`` objects are converted to `~numpy.poly1d` when doing
+arithmetic, and lose information of the original orthogonal polynomial.
+
+.. autosummary::
+   :toctree: generated/
+
+   legendre    -- Legendre polynomial.
+   chebyt      -- Chebyshev polynomial of the first kind.
+   chebyu      -- Chebyshev polynomial of the second kind.
+   chebyc      -- Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+   chebys      -- Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+   jacobi      -- Jacobi polynomial.
+   laguerre    -- Laguerre polynomial.
+   genlaguerre -- Generalized (associated) Laguerre polynomial.
+   hermite     -- Physicist's Hermite polynomial.
+   hermitenorm -- Normalized (probabilist's) Hermite polynomial.
+   gegenbauer  -- Gegenbauer (ultraspherical) polynomial.
+   sh_legendre -- Shifted Legendre polynomial.
+   sh_chebyt   -- Shifted Chebyshev polynomial of the first kind.
+   sh_chebyu   -- Shifted Chebyshev polynomial of the second kind.
+   sh_jacobi   -- Shifted Jacobi polynomial.
+
+.. warning::
+
+   Computing values of high-order polynomials (around ``order > 20``) using
+   polynomial coefficients is numerically unstable. To evaluate polynomial
+   values, the ``eval_*`` functions should be used instead.
+
+
+Hypergeometric functions
+------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   hyp2f1 -- Gauss hypergeometric function 2F1(a, b; c; z).
+   hyp1f1 -- Confluent hypergeometric function 1F1(a, b; x).
+   hyperu -- Confluent hypergeometric function U(a, b, x) of the second kind.
+   hyp0f1 -- Confluent hypergeometric limit function 0F1.
+
+
+Parabolic cylinder functions
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   pbdv -- Parabolic cylinder function D.
+   pbvv -- Parabolic cylinder function V.
+   pbwa -- Parabolic cylinder function W.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   pbdv_seq -- Parabolic cylinder functions Dv(x) and derivatives.
+   pbvv_seq -- Parabolic cylinder functions Vv(x) and derivatives.
+   pbdn_seq -- Parabolic cylinder functions Dn(z) and derivatives.
+
+Mathieu and related functions
+-----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_a -- Characteristic value of even Mathieu functions.
+   mathieu_b -- Characteristic value of odd Mathieu functions.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_even_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions.
+   mathieu_odd_coef  -- Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+The following return both function and first derivative:
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_cem     -- Even Mathieu function and its derivative.
+   mathieu_sem     -- Odd Mathieu function and its derivative.
+   mathieu_modcem1 -- Even modified Mathieu function of the first kind and its derivative.
+   mathieu_modcem2 -- Even modified Mathieu function of the second kind and its derivative.
+   mathieu_modsem1 -- Odd modified Mathieu function of the first kind and its derivative.
+   mathieu_modsem2 -- Odd modified Mathieu function of the second kind and its derivative.
+
+Spheroidal wave functions
+-------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   pro_ang1   -- Prolate spheroidal angular function of the first kind and its derivative.
+   pro_rad1   -- Prolate spheroidal radial function of the first kind and its derivative.
+   pro_rad2   -- Prolate spheroidal radial function of the second kind and its derivative.
+   obl_ang1   -- Oblate spheroidal angular function of the first kind and its derivative.
+   obl_rad1   -- Oblate spheroidal radial function of the first kind and its derivative.
+   obl_rad2   -- Oblate spheroidal radial function of the second kind and its derivative.
+   pro_cv     -- Characteristic value of prolate spheroidal function.
+   obl_cv     -- Characteristic value of oblate spheroidal function.
+   pro_cv_seq -- Characteristic values for prolate spheroidal wave functions.
+   obl_cv_seq -- Characteristic values for oblate spheroidal wave functions.
+
+The following functions require pre-computed characteristic value:
+
+.. autosummary::
+   :toctree: generated/
+
+   pro_ang1_cv -- Prolate spheroidal angular function pro_ang1 for precomputed characteristic value.
+   pro_rad1_cv -- Prolate spheroidal radial function pro_rad1 for precomputed characteristic value.
+   pro_rad2_cv -- Prolate spheroidal radial function pro_rad2 for precomputed characteristic value.
+   obl_ang1_cv -- Oblate spheroidal angular function obl_ang1 for precomputed characteristic value.
+   obl_rad1_cv -- Oblate spheroidal radial function obl_rad1 for precomputed characteristic value.
+   obl_rad2_cv -- Oblate spheroidal radial function obl_rad2 for precomputed characteristic value.
+
+Kelvin functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   kelvin       -- Kelvin functions as complex numbers.
+   kelvin_zeros -- Compute nt zeros of all Kelvin functions.
+   ber          -- Kelvin function ber.
+   bei          -- Kelvin function bei
+   berp         -- Derivative of the Kelvin function `ber`.
+   beip         -- Derivative of the Kelvin function `bei`.
+   ker          -- Kelvin function ker.
+   kei          -- Kelvin function ker.
+   kerp         -- Derivative of the Kelvin function ker.
+   keip         -- Derivative of the Kelvin function kei.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   ber_zeros  -- Compute nt zeros of the Kelvin function ber(x).
+   bei_zeros  -- Compute nt zeros of the Kelvin function bei(x).
+   berp_zeros -- Compute nt zeros of the Kelvin function ber'(x).
+   beip_zeros -- Compute nt zeros of the Kelvin function bei'(x).
+   ker_zeros  -- Compute nt zeros of the Kelvin function ker(x).
+   kei_zeros  -- Compute nt zeros of the Kelvin function kei(x).
+   kerp_zeros -- Compute nt zeros of the Kelvin function ker'(x).
+   keip_zeros -- Compute nt zeros of the Kelvin function kei'(x).
+
+Combinatorics
+-------------
+
+.. autosummary::
+   :toctree: generated/
+
+   comb -- The number of combinations of N things taken k at a time.
+   perm -- Permutations of N things taken k at a time, i.e., k-permutations of N.
+   stirling2 -- Stirling numbers of the second kind.
+
+Lambert W and related functions
+-------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   lambertw    -- Lambert W function.
+   wrightomega -- Wright Omega function.
+
+Other special functions
+-----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   agm         -- Arithmetic, Geometric Mean.
+   bernoulli   -- Bernoulli numbers B0..Bn (inclusive).
+   binom       -- Binomial coefficient
+   diric       -- Periodic sinc function, also called the Dirichlet function.
+   euler       -- Euler numbers E0..En (inclusive).
+   expn        -- Exponential integral E_n.
+   exp1        -- Exponential integral E_1 of complex argument z.
+   expi        -- Exponential integral Ei.
+   factorial   -- The factorial of a number or array of numbers.
+   factorial2  -- Double factorial.
+   factorialk  -- Multifactorial of n of order k, n(!!...!).
+   shichi      -- Hyperbolic sine and cosine integrals.
+   sici        -- Sine and cosine integrals.
+   softmax     -- Softmax function.
+   log_softmax -- Logarithm of softmax function.
+   spence      -- Spence's function, also known as the dilogarithm.
+   zeta        -- Riemann zeta function.
+   zetac       -- Riemann zeta function minus 1.
+   softplus    -- Softplus function.
+
+Convenience functions
+---------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   cbrt      -- Cube root of `x`.
+   exp10     -- 10**x.
+   exp2      -- 2**x.
+   radian    -- Convert from degrees to radians.
+   cosdg     -- Cosine of the angle `x` given in degrees.
+   sindg     -- Sine of angle given in degrees.
+   tandg     -- Tangent of angle x given in degrees.
+   cotdg     -- Cotangent of the angle `x` given in degrees.
+   log1p     -- Calculates log(1+x) for use when `x` is near zero.
+   expm1     -- ``exp(x) - 1`` for use when `x` is near zero.
+   cosm1     -- ``cos(x) - 1`` for use when `x` is near zero.
+   powm1     -- ``x**y - 1`` for use when `y` is near zero or `x` is near 1.
+   round     -- Round to nearest integer.
+   xlogy     -- Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.
+   xlog1py   -- Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.
+   logsumexp -- Compute the log of the sum of exponentials of input elements.
+   exprel    -- Relative error exponential, (exp(x)-1)/x, for use when `x` is near zero.
+   sinc      -- Return the sinc function.
+
+"""  # noqa: E501
+
+import os
+import warnings
+
+
+def _load_libsf_error_state():
+    """Load libsf_error_state.dll shared library on Windows
+
+    libsf_error_state manages shared state used by
+    ``scipy.special.seterr`` and ``scipy.special.geterr`` so that these
+    can work consistently between special functions provided by different
+    extension modules. This shared library is installed in scipy/special
+    alongside this __init__.py file. Due to lack of rpath support, Windows
+    cannot find shared libraries installed within wheels. To circumvent this,
+    we pre-load ``lib_sf_error_state.dll`` when on Windows.
+
+    The logic for this function was borrowed from the function ``make_init``
+    in `scipy/tools/openblas_support.py`:
+    https://github.com/scipy/scipy/blob/bb92c8014e21052e7dde67a76b28214dd1dcb94a/tools/openblas_support.py#L239-L274
+    """  # noqa: E501
+    if os.name == "nt":
+        try:
+            from ctypes import WinDLL
+            basedir = os.path.dirname(__file__)
+        except:  # noqa: E722
+            pass
+        else:
+            dll_path = os.path.join(basedir, "libsf_error_state.dll")
+            if os.path.exists(dll_path):
+                WinDLL(dll_path)
+
+
+_load_libsf_error_state()
+
+
+from ._sf_error import SpecialFunctionWarning, SpecialFunctionError
+
+from . import _ufuncs
+from ._ufuncs import *
+
+# Replace some function definitions from _ufuncs to add Array API support
+from ._support_alternative_backends import (
+    log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, gammaln,
+    gammainc, gammaincc, logit, expit, entr, rel_entr, xlogy,
+    chdtr, chdtrc, betainc, betaincc, stdtr)
+
+from . import _basic
+from ._basic import *
+
+from ._logsumexp import logsumexp, softmax, log_softmax
+
+from . import _multiufuncs
+from ._multiufuncs import *
+
+from . import _orthogonal
+from ._orthogonal import *
+
+from ._spfun_stats import multigammaln
+from ._ellip_harm import (
+    ellip_harm,
+    ellip_harm_2,
+    ellip_normal
+)
+from ._lambertw import lambertw
+from ._spherical_bessel import (
+    spherical_jn,
+    spherical_yn,
+    spherical_in,
+    spherical_kn
+)
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import add_newdocs, basic, orthogonal, specfun, sf_error, spfun_stats
+
+# We replace some function definitions from _ufuncs with those from
+# _support_alternative_backends above, but those are all listed in _ufuncs.__all__,
+# so there is no need to consider _support_alternative_backends.__all__ here.
+__all__ = _ufuncs.__all__ + _basic.__all__ + _orthogonal.__all__ + _multiufuncs.__all__
+__all__ += [
+    'SpecialFunctionWarning',
+    'SpecialFunctionError',
+    'logsumexp',
+    'softmax',
+    'log_softmax',
+    'multigammaln',
+    'ellip_harm',
+    'ellip_harm_2',
+    'ellip_normal',
+    'lambertw',
+    'spherical_jn',
+    'spherical_yn',
+    'spherical_in',
+    'spherical_kn',
+]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
+
+
+def _get_include():
+    """This function is for development purposes only.
+
+    This function could disappear or its behavior could change at any time.
+    """
+    import os
+    return os.path.dirname(__file__)
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..134604c90128a59d48dee66318fa6fd02308f80c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py
@@ -0,0 +1,10699 @@
+# Docstrings for generated ufuncs
+#
+# The syntax is designed to look like the function add_newdoc is being
+# called from numpy.lib, but in this file add_newdoc puts the
+# docstrings in a dictionary. This dictionary is used in
+# _generate_pyx.py to generate the docstrings for the ufuncs in
+# scipy.special at the C level when the ufuncs are created at compile
+# time.
+
+docdict: dict[str, str] = {}
+
+
+def get(name):
+    return docdict.get(name)
+
+
+def add_newdoc(name, doc):
+    docdict[name] = doc
+
+
+add_newdoc("_sf_error_test_function",
+    """
+    Private function; do not use.
+    """)
+
+
+add_newdoc("_cosine_cdf",
+    """
+    _cosine_cdf(x)
+
+    Cumulative distribution function (CDF) of the cosine distribution::
+
+                 {             0,              x < -pi
+        cdf(x) = { (pi + x + sin(x))/(2*pi),   -pi <= x <= pi
+                 {             1,              x > pi
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+
+    Returns
+    -------
+    scalar or ndarray
+        The cosine distribution CDF evaluated at `x`.
+
+    """)
+
+add_newdoc("_cosine_invcdf",
+    """
+    _cosine_invcdf(p)
+
+    Inverse of the cumulative distribution function (CDF) of the cosine
+    distribution.
+
+    The CDF of the cosine distribution is::
+
+        cdf(x) = (pi + x + sin(x))/(2*pi)
+
+    This function computes the inverse of cdf(x).
+
+    Parameters
+    ----------
+    p : array_like
+        `p` must contain real numbers in the interval ``0 <= p <= 1``.
+        `nan` is returned for values of `p` outside the interval [0, 1].
+
+    Returns
+    -------
+    scalar or ndarray
+        The inverse of the cosine distribution CDF evaluated at `p`.
+
+    """)
+
+add_newdoc("_ellip_harm",
+    """
+    Internal function, use `ellip_harm` instead.
+    """)
+
+add_newdoc("_ellip_norm",
+    """
+    Internal function, use `ellip_norm` instead.
+    """)
+
+add_newdoc("voigt_profile",
+    r"""
+    voigt_profile(x, sigma, gamma, out=None)
+
+    Voigt profile.
+
+    The Voigt profile is a convolution of a 1-D Normal distribution with
+    standard deviation ``sigma`` and a 1-D Cauchy distribution with half-width at
+    half-maximum ``gamma``.
+
+    If ``sigma = 0``, PDF of Cauchy distribution is returned.
+    Conversely, if ``gamma = 0``, PDF of Normal distribution is returned.
+    If ``sigma = gamma = 0``, the return value is ``Inf`` for ``x = 0``,
+    and ``0`` for all other ``x``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument
+    sigma : array_like
+        The standard deviation of the Normal distribution part
+    gamma : array_like
+        The half-width at half-maximum of the Cauchy distribution part
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The Voigt profile at the given arguments
+
+    See Also
+    --------
+    wofz : Faddeeva function
+
+    Notes
+    -----
+    It can be expressed in terms of Faddeeva function
+
+    .. math:: V(x; \sigma, \gamma) = \frac{Re[w(z)]}{\sigma\sqrt{2\pi}},
+    .. math:: z = \frac{x + i\gamma}{\sqrt{2}\sigma}
+
+    where :math:`w(z)` is the Faddeeva function.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Voigt_profile
+
+    Examples
+    --------
+    Calculate the function at point 2 for ``sigma=1`` and ``gamma=1``.
+
+    >>> from scipy.special import voigt_profile
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> voigt_profile(2, 1., 1.)
+    0.09071519942627544
+
+    Calculate the function at several points by providing a NumPy array
+    for `x`.
+
+    >>> values = np.array([-2., 0., 5])
+    >>> voigt_profile(values, 1., 1.)
+    array([0.0907152 , 0.20870928, 0.01388492])
+
+    Plot the function for different parameter sets.
+
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> x = np.linspace(-10, 10, 500)
+    >>> parameters_list = [(1.5, 0., "solid"), (1.3, 0.5, "dashed"),
+    ...                    (0., 1.8, "dotted"), (1., 1., "dashdot")]
+    >>> for params in parameters_list:
+    ...     sigma, gamma, linestyle = params
+    ...     voigt = voigt_profile(x, sigma, gamma)
+    ...     ax.plot(x, voigt, label=rf"$\sigma={sigma},\, \gamma={gamma}$",
+    ...             ls=linestyle)
+    >>> ax.legend()
+    >>> plt.show()
+
+    Verify visually that the Voigt profile indeed arises as the convolution
+    of a normal and a Cauchy distribution.
+
+    >>> from scipy.signal import convolve
+    >>> x, dx = np.linspace(-10, 10, 500, retstep=True)
+    >>> def gaussian(x, sigma):
+    ...     return np.exp(-0.5 * x**2/sigma**2)/(sigma * np.sqrt(2*np.pi))
+    >>> def cauchy(x, gamma):
+    ...     return gamma/(np.pi * (np.square(x)+gamma**2))
+    >>> sigma = 2
+    >>> gamma = 1
+    >>> gauss_profile = gaussian(x, sigma)
+    >>> cauchy_profile = cauchy(x, gamma)
+    >>> convolved = dx * convolve(cauchy_profile, gauss_profile, mode="same")
+    >>> voigt = voigt_profile(x, sigma, gamma)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> ax.plot(x, gauss_profile, label="Gauss: $G$", c='b')
+    >>> ax.plot(x, cauchy_profile, label="Cauchy: $C$", c='y', ls="dashed")
+    >>> xx = 0.5*(x[1:] + x[:-1])  # midpoints
+    >>> ax.plot(xx, convolved[1:], label="Convolution: $G * C$", ls='dashdot',
+    ...         c='k')
+    >>> ax.plot(x, voigt, label="Voigt", ls='dotted', c='r')
+    >>> ax.legend()
+    >>> plt.show()
+    """)
+
+add_newdoc("wrightomega",
+    r"""
+    wrightomega(z, out=None)
+
+    Wright Omega function.
+
+    Defined as the solution to
+
+    .. math::
+
+        \omega + \log(\omega) = z
+
+    where :math:`\log` is the principal branch of the complex logarithm.
+
+    Parameters
+    ----------
+    z : array_like
+        Points at which to evaluate the Wright Omega function
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    omega : scalar or ndarray
+        Values of the Wright Omega function
+
+    See Also
+    --------
+    lambertw : The Lambert W function
+
+    Notes
+    -----
+    .. versionadded:: 0.19.0
+
+    The function can also be defined as
+
+    .. math::
+
+        \omega(z) = W_{K(z)}(e^z)
+
+    where :math:`K(z) = \lceil (\Im(z) - \pi)/(2\pi) \rceil` is the
+    unwinding number and :math:`W` is the Lambert W function.
+
+    The implementation here is taken from [1]_.
+
+    References
+    ----------
+    .. [1] Lawrence, Corless, and Jeffrey, "Algorithm 917: Complex
+           Double-Precision Evaluation of the Wright :math:`\omega`
+           Function." ACM Transactions on Mathematical Software,
+           2012. :doi:`10.1145/2168773.2168779`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import wrightomega, lambertw
+
+    >>> wrightomega([-2, -1, 0, 1, 2])
+    array([0.12002824, 0.27846454, 0.56714329, 1.        , 1.5571456 ])
+
+    Complex input:
+
+    >>> wrightomega(3 + 5j)
+    (1.5804428632097158+3.8213626783287937j)
+
+    Verify that ``wrightomega(z)`` satisfies ``w + log(w) = z``:
+
+    >>> w = -5 + 4j
+    >>> wrightomega(w + np.log(w))
+    (-5+4j)
+
+    Verify the connection to ``lambertw``:
+
+    >>> z = 0.5 + 3j
+    >>> wrightomega(z)
+    (0.0966015889280649+1.4937828458191993j)
+    >>> lambertw(np.exp(z))
+    (0.09660158892806493+1.4937828458191993j)
+
+    >>> z = 0.5 + 4j
+    >>> wrightomega(z)
+    (-0.3362123489037213+2.282986001579032j)
+    >>> lambertw(np.exp(z), k=1)
+    (-0.33621234890372115+2.282986001579032j)
+    """)
+
+
+add_newdoc("agm",
+    """
+    agm(a, b, out=None)
+
+    Compute the arithmetic-geometric mean of `a` and `b`.
+
+    Start with a_0 = a and b_0 = b and iteratively compute::
+
+        a_{n+1} = (a_n + b_n)/2
+        b_{n+1} = sqrt(a_n*b_n)
+
+    a_n and b_n converge to the same limit as n increases; their common
+    limit is agm(a, b).
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real values only. If the values are both negative, the result
+        is negative. If one value is negative and the other is positive,
+        `nan` is returned.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The arithmetic-geometric mean of `a` and `b`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import agm
+    >>> a, b = 24.0, 6.0
+    >>> agm(a, b)
+    13.458171481725614
+
+    Compare that result to the iteration:
+
+    >>> while a != b:
+    ...     a, b = (a + b)/2, np.sqrt(a*b)
+    ...     print("a = %19.16f  b=%19.16f" % (a, b))
+    ...
+    a = 15.0000000000000000  b=12.0000000000000000
+    a = 13.5000000000000000  b=13.4164078649987388
+    a = 13.4582039324993694  b=13.4581390309909850
+    a = 13.4581714817451772  b=13.4581714817060547
+    a = 13.4581714817256159  b=13.4581714817256159
+
+    When array-like arguments are given, broadcasting applies:
+
+    >>> a = np.array([[1.5], [3], [6]])  # a has shape (3, 1).
+    >>> b = np.array([6, 12, 24, 48])    # b has shape (4,).
+    >>> agm(a, b)
+    array([[  3.36454287,   5.42363427,   9.05798751,  15.53650756],
+           [  4.37037309,   6.72908574,  10.84726853,  18.11597502],
+           [  6.        ,   8.74074619,  13.45817148,  21.69453707]])
+    """)
+
+add_newdoc("airy",
+    r"""
+    airy(z, out=None)
+
+    Airy functions and their derivatives.
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex argument.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    Ai, Aip, Bi, Bip : 4-tuple of scalar or ndarray
+        Airy functions Ai and Bi, and their derivatives Aip and Bip.
+
+    See Also
+    --------
+    airye : exponentially scaled Airy functions.
+
+    Notes
+    -----
+    The Airy functions Ai and Bi are two independent solutions of
+
+    .. math:: y''(x) = x y(x).
+
+    For real `z` in [-10, 10], the computation is carried out by calling
+    the Cephes [1]_ `airy` routine, which uses power series summation
+    for small `z` and rational minimax approximations for large `z`.
+
+    Outside this range, the AMOS [2]_ `zairy` and `zbiry` routines are
+    employed.  They are computed using power series for :math:`|z| < 1` and
+    the following relations to modified Bessel functions for larger `z`
+    (where :math:`t \equiv 2 z^{3/2}/3`):
+
+    .. math::
+
+        Ai(z) = \frac{1}{\pi \sqrt{3}} K_{1/3}(t)
+
+        Ai'(z) = -\frac{z}{\pi \sqrt{3}} K_{2/3}(t)
+
+        Bi(z) = \sqrt{\frac{z}{3}} \left(I_{-1/3}(t) + I_{1/3}(t) \right)
+
+        Bi'(z) = \frac{z}{\sqrt{3}} \left(I_{-2/3}(t) + I_{2/3}(t)\right)
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compute the Airy functions on the interval [-15, 5].
+
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> x = np.linspace(-15, 5, 201)
+    >>> ai, aip, bi, bip = special.airy(x)
+
+    Plot Ai(x) and Bi(x).
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(x, ai, 'r', label='Ai(x)')
+    >>> plt.plot(x, bi, 'b--', label='Bi(x)')
+    >>> plt.ylim(-0.5, 1.0)
+    >>> plt.grid()
+    >>> plt.legend(loc='upper left')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("airye",
+    """
+    airye(z, out=None)
+
+    Exponentially scaled Airy functions and their derivatives.
+
+    Scaling::
+
+        eAi  = Ai  * exp(2.0/3.0*z*sqrt(z))
+        eAip = Aip * exp(2.0/3.0*z*sqrt(z))
+        eBi  = Bi  * exp(-abs(2.0/3.0*(z*sqrt(z)).real))
+        eBip = Bip * exp(-abs(2.0/3.0*(z*sqrt(z)).real))
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex argument.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    eAi, eAip, eBi, eBip : 4-tuple of scalar or ndarray
+        Exponentially scaled Airy functions eAi and eBi, and their derivatives
+        eAip and eBip
+
+    See Also
+    --------
+    airy
+
+    Notes
+    -----
+    Wrapper for the AMOS [1]_ routines `zairy` and `zbiry`.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    We can compute exponentially scaled Airy functions and their derivatives:
+
+    >>> import numpy as np
+    >>> from scipy.special import airye
+    >>> import matplotlib.pyplot as plt
+    >>> z = np.linspace(0, 50, 500)
+    >>> eAi, eAip, eBi, eBip = airye(z)
+    >>> f, ax = plt.subplots(2, 1, sharex=True)
+    >>> for ind, data in enumerate([[eAi, eAip, ["eAi", "eAip"]],
+    ...                             [eBi, eBip, ["eBi", "eBip"]]]):
+    ...     ax[ind].plot(z, data[0], "-r", z, data[1], "-b")
+    ...     ax[ind].legend(data[2])
+    ...     ax[ind].grid(True)
+    >>> plt.show()
+
+    We can compute these using usual non-scaled Airy functions by:
+
+    >>> from scipy.special import airy
+    >>> Ai, Aip, Bi, Bip = airy(z)
+    >>> np.allclose(eAi, Ai * np.exp(2.0 / 3.0 * z * np.sqrt(z)))
+    True
+    >>> np.allclose(eAip, Aip * np.exp(2.0 / 3.0 * z * np.sqrt(z)))
+    True
+    >>> np.allclose(eBi, Bi * np.exp(-abs(np.real(2.0 / 3.0 * z * np.sqrt(z)))))
+    True
+    >>> np.allclose(eBip, Bip * np.exp(-abs(np.real(2.0 / 3.0 * z * np.sqrt(z)))))
+    True
+
+    Comparing non-scaled and exponentially scaled ones, the usual non-scaled
+    function quickly underflows for large values, whereas the exponentially
+    scaled function does not.
+
+    >>> airy(200)
+    (0.0, 0.0, nan, nan)
+    >>> airye(200)
+    (0.07501041684381093, -1.0609012305109042, 0.15003188417418148, 2.1215836725571093)
+
+    """)
+
+add_newdoc("bdtr",
+    r"""
+    bdtr(k, n, p, out=None)
+
+    Binomial distribution cumulative distribution function.
+
+    Sum of the terms 0 through `floor(k)` of the Binomial probability density.
+
+    .. math::
+        \mathrm{bdtr}(k, n, p) =
+        \sum_{j=0}^{\lfloor k \rfloor} {{n}\choose{j}} p^j (1-p)^{n-j}
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (double), rounded down to the nearest integer.
+    n : array_like
+        Number of events (int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Probability of `floor(k)` or fewer successes in `n` independent events with
+        success probabilities of `p`.
+
+    Notes
+    -----
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{bdtr}(k, n, p) =
+        I_{1 - p}(n - \lfloor k \rfloor, \lfloor k \rfloor + 1).
+
+    Wrapper for the Cephes [1]_ routine `bdtr`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    """)
+
+add_newdoc("bdtrc",
+    r"""
+    bdtrc(k, n, p, out=None)
+
+    Binomial distribution survival function.
+
+    Sum of the terms `floor(k) + 1` through `n` of the binomial probability
+    density,
+
+    .. math::
+        \mathrm{bdtrc}(k, n, p) =
+        \sum_{j=\lfloor k \rfloor +1}^n {{n}\choose{j}} p^j (1-p)^{n-j}
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (double), rounded down to nearest integer.
+    n : array_like
+        Number of events (int)
+    p : array_like
+        Probability of success in a single event.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Probability of `floor(k) + 1` or more successes in `n` independent
+        events with success probabilities of `p`.
+
+    See Also
+    --------
+    bdtr
+    betainc
+
+    Notes
+    -----
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{bdtrc}(k, n, p) = I_{p}(\lfloor k \rfloor + 1, n - \lfloor k \rfloor).
+
+    Wrapper for the Cephes [1]_ routine `bdtrc`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    """)
+
+add_newdoc("bdtri",
+    r"""
+    bdtri(k, n, y, out=None)
+
+    Inverse function to `bdtr` with respect to `p`.
+
+    Finds the event probability `p` such that the sum of the terms 0 through
+    `k` of the binomial probability density is equal to the given cumulative
+    probability `y`.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (float), rounded down to the nearest integer.
+    n : array_like
+        Number of events (float)
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    p : scalar or ndarray
+        The event probability such that `bdtr(\lfloor k \rfloor, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+    betaincinv
+
+    Notes
+    -----
+    The computation is carried out using the inverse beta integral function
+    and the relation,::
+
+        1 - p = betaincinv(n - k, k + 1, y).
+
+    Wrapper for the Cephes [1]_ routine `bdtri`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    """)
+
+add_newdoc("bdtrik",
+    """
+    bdtrik(y, n, p, out=None)
+
+    Inverse function to `bdtr` with respect to `k`.
+
+    Finds the number of successes `k` such that the sum of the terms 0 through
+    `k` of the Binomial probability density for `n` events with probability
+    `p` is equal to the given cumulative probability `y`.
+
+    Parameters
+    ----------
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    n : array_like
+        Number of events (float).
+    p : array_like
+        Success probability (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    k : scalar or ndarray
+        The number of successes `k` such that `bdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+
+    Notes
+    -----
+    Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the
+    cumulative incomplete beta distribution.
+
+    Computation of `k` involves a search for a value that produces the desired
+    value of `y`. The search relies on the monotonicity of `y` with `k`.
+
+    Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [2] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+
+    """)
+
+add_newdoc("bdtrin",
+    """
+    bdtrin(k, y, p, out=None)
+
+    Inverse function to `bdtr` with respect to `n`.
+
+    Finds the number of events `n` such that the sum of the terms 0 through
+    `k` of the Binomial probability density for events with probability `p` is
+    equal to the given cumulative probability `y`.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (float).
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    p : array_like
+        Success probability (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    n : scalar or ndarray
+        The number of events `n` such that `bdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+
+    Notes
+    -----
+    Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the
+    cumulative incomplete beta distribution.
+
+    Computation of `n` involves a search for a value that produces the desired
+    value of `y`. The search relies on the monotonicity of `y` with `n`.
+
+    Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [2] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    """)
+
+add_newdoc("btdtria",
+    r"""
+    btdtria(p, b, x, out=None)
+
+    Inverse of `betainc` with respect to `a`.
+
+    This is the inverse of the beta cumulative distribution function, `betainc`,
+    considered as a function of `a`, returning the value of `a` for which
+    `betainc(a, b, x) = p`, or
+
+    .. math::
+        p = \int_0^x \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} t^{a-1} (1-t)^{b-1}\,dt
+
+    Parameters
+    ----------
+    p : array_like
+        Cumulative probability, in [0, 1].
+    b : array_like
+        Shape parameter (`b` > 0).
+    x : array_like
+        The quantile, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    a : scalar or ndarray
+        The value of the shape parameter `a` such that `betainc(a, b, x) = p`.
+
+    See Also
+    --------
+    btdtrib : Inverse of the beta cumulative distribution function, with respect to `b`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `a` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `a`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Algorithm 708: Significant Digit Computation of the Incomplete Beta
+           Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.
+
+    """)
+
+add_newdoc("btdtrib",
+    r"""
+    btdtria(a, p, x, out=None)
+
+    Inverse of `betainc` with respect to `b`.
+
+    This is the inverse of the beta cumulative distribution function, `betainc`,
+    considered as a function of `b`, returning the value of `b` for which
+    `betainc(a, b, x) = p`, or
+
+    .. math::
+        p = \int_0^x \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} t^{a-1} (1-t)^{b-1}\,dt
+
+    Parameters
+    ----------
+    a : array_like
+        Shape parameter (`a` > 0).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    x : array_like
+        The quantile, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    b : scalar or ndarray
+        The value of the shape parameter `b` such that `betainc(a, b, x) = p`.
+
+    See Also
+    --------
+    btdtria : Inverse of the beta cumulative distribution function, with respect to `a`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `b` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `b`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Algorithm 708: Significant Digit Computation of the Incomplete Beta
+           Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.
+
+
+    """)
+
+add_newdoc(
+    "betainc",
+    r"""
+    betainc(a, b, x, out=None)
+
+    Regularized incomplete beta function.
+
+    Computes the regularized incomplete beta function, defined as [1]_:
+
+    .. math::
+
+        I_x(a, b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} \int_0^x
+        t^{a-1}(1-t)^{b-1}dt,
+
+    for :math:`0 \leq x \leq 1`.
+
+    This function is the cumulative distribution function for the beta
+    distribution; its range is [0, 1].
+
+    Parameters
+    ----------
+    a, b : array_like
+           Positive, real-valued parameters
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the regularized incomplete beta function
+
+    See Also
+    --------
+    beta : beta function
+    betaincinv : inverse of the regularized incomplete beta function
+    betaincc : complement of the regularized incomplete beta function
+    scipy.stats.beta : beta distribution
+
+    Notes
+    -----
+    The term *regularized* in the name of this function refers to the
+    scaling of the function by the gamma function terms shown in the
+    formula.  When not qualified as *regularized*, the name *incomplete
+    beta function* often refers to just the integral expression,
+    without the gamma terms.  One can use the function `beta` from
+    `scipy.special` to get this "nonregularized" incomplete beta
+    function by multiplying the result of ``betainc(a, b, x)`` by
+    ``beta(a, b)``.
+
+    This function wraps the ``ibeta`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+
+    Let :math:`B(a, b)` be the `beta` function.
+
+    >>> import scipy.special as sc
+
+    The coefficient in terms of `gamma` is equal to
+    :math:`1/B(a, b)`. Also, when :math:`x=1`
+    the integral is equal to :math:`B(a, b)`.
+    Therefore, :math:`I_{x=1}(a, b) = 1` for any :math:`a, b`.
+
+    >>> sc.betainc(0.2, 3.5, 1.0)
+    1.0
+
+    It satisfies
+    :math:`I_x(a, b) = x^a F(a, 1-b, a+1, x)/ (aB(a, b))`,
+    where :math:`F` is the hypergeometric function `hyp2f1`:
+
+    >>> a, b, x = 1.4, 3.1, 0.5
+    >>> x**a * sc.hyp2f1(a, 1 - b, a + 1, x)/(a * sc.beta(a, b))
+    0.8148904036225295
+    >>> sc.betainc(a, b, x)
+    0.8148904036225296
+
+    This functions satisfies the relationship
+    :math:`I_x(a, b) = 1 - I_{1-x}(b, a)`:
+
+    >>> sc.betainc(2.2, 3.1, 0.4)
+    0.49339638807619446
+    >>> 1 - sc.betainc(3.1, 2.2, 1 - 0.4)
+    0.49339638807619446
+
+    """)
+
+
+add_newdoc(
+    "betaincc",
+    r"""
+    betaincc(a, b, x, out=None)
+
+    Complement of the regularized incomplete beta function.
+
+    Computes the complement of the regularized incomplete beta function,
+    defined as [1]_:
+
+    .. math::
+
+        \bar{I}_x(a, b) = 1 - I_x(a, b)
+                        = 1 - \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} \int_0^x
+                                  t^{a-1}(1-t)^{b-1}dt,
+
+    for :math:`0 \leq x \leq 1`.
+
+    Parameters
+    ----------
+    a, b : array_like
+           Positive, real-valued parameters
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    betaincinv : inverse of the regularized incomplete beta function
+    betainccinv :
+        inverse of the complement of the regularized incomplete beta function
+    beta : beta function
+    scipy.stats.beta : beta distribution
+
+    Notes
+    -----
+    .. versionadded:: 1.11.0
+
+    This function wraps the ``ibetac`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import betaincc, betainc
+
+    The naive calculation ``1 - betainc(a, b, x)`` loses precision when
+    the values of ``betainc(a, b, x)`` are close to 1:
+
+    >>> 1 - betainc(0.5, 8, [0.9, 0.99, 0.999])
+    array([2.0574632e-09, 0.0000000e+00, 0.0000000e+00])
+
+    By using ``betaincc``, we get the correct values:
+
+    >>> betaincc(0.5, 8, [0.9, 0.99, 0.999])
+    array([2.05746321e-09, 1.97259354e-17, 1.96467954e-25])
+
+    """)
+
+add_newdoc(
+    "betaincinv",
+    r"""
+    betaincinv(a, b, y, out=None)
+
+    Inverse of the regularized incomplete beta function.
+
+    Computes :math:`x` such that:
+
+    .. math::
+
+        y = I_x(a, b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}
+        \int_0^x t^{a-1}(1-t)^{b-1}dt,
+
+    where :math:`I_x` is the normalized incomplete beta function `betainc`
+    and :math:`\Gamma` is the `gamma` function [1]_.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Positive, real-valued parameters
+    y : array_like
+        Real-valued input
+    out : ndarray, optional
+        Optional output array for function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the inverse of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    gamma : gamma function
+
+    Notes
+    -----
+    This function wraps the ``ibeta_inv`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    This function is the inverse of `betainc` for fixed
+    values of :math:`a` and :math:`b`.
+
+    >>> a, b = 1.2, 3.1
+    >>> y = sc.betainc(a, b, 0.2)
+    >>> sc.betaincinv(a, b, y)
+    0.2
+    >>>
+    >>> a, b = 7.5, 0.4
+    >>> x = sc.betaincinv(a, b, 0.5)
+    >>> sc.betainc(a, b, x)
+    0.5
+
+    """)
+
+
+add_newdoc(
+    "betainccinv",
+    r"""
+    betainccinv(a, b, y, out=None)
+
+    Inverse of the complemented regularized incomplete beta function.
+
+    Computes :math:`x` such that:
+
+    .. math::
+
+        y = 1 - I_x(a, b) = 1 - \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}
+        \int_0^x t^{a-1}(1-t)^{b-1}dt,
+
+    where :math:`I_x` is the normalized incomplete beta function `betainc`
+    and :math:`\Gamma` is the `gamma` function [1]_.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Positive, real-valued parameters
+    y : array_like
+        Real-valued input
+    out : ndarray, optional
+        Optional output array for function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the inverse of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    betaincc : complement of the regularized incomplete beta function
+
+    Notes
+    -----
+    .. versionadded:: 1.11.0
+
+    This function wraps the ``ibetac_inv`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import betainccinv, betaincc
+
+    This function is the inverse of `betaincc` for fixed
+    values of :math:`a` and :math:`b`.
+
+    >>> a, b = 1.2, 3.1
+    >>> y = betaincc(a, b, 0.2)
+    >>> betainccinv(a, b, y)
+    0.2
+
+    >>> a, b = 7, 2.5
+    >>> x = betainccinv(a, b, 0.875)
+    >>> betaincc(a, b, x)
+    0.875
+
+    """)
+
+add_newdoc("boxcox",
+    """
+    boxcox(x, lmbda, out=None)
+
+    Compute the Box-Cox transformation.
+
+    The Box-Cox transformation is::
+
+        y = (x**lmbda - 1) / lmbda  if lmbda != 0
+            log(x)                  if lmbda == 0
+
+    Returns `nan` if ``x < 0``.
+    Returns `-inf` if ``x == 0`` and ``lmbda < 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox
+    >>> boxcox([1, 4, 10], 2.5)
+    array([   0.        ,   12.4       ,  126.09110641])
+    >>> boxcox(2, [0, 1, 2])
+    array([ 0.69314718,  1.        ,  1.5       ])
+    """)
+
+add_newdoc("boxcox1p",
+    """
+    boxcox1p(x, lmbda, out=None)
+
+    Compute the Box-Cox transformation of 1 + `x`.
+
+    The Box-Cox transformation computed by `boxcox1p` is::
+
+        y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0
+            log(1+x)                    if lmbda == 0
+
+    Returns `nan` if ``x < -1``.
+    Returns `-inf` if ``x == -1`` and ``lmbda < 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox1p
+    >>> boxcox1p(1e-4, [0, 0.5, 1])
+    array([  9.99950003e-05,   9.99975001e-05,   1.00000000e-04])
+    >>> boxcox1p([0.01, 0.1], 0.25)
+    array([ 0.00996272,  0.09645476])
+    """)
+
+add_newdoc("inv_boxcox",
+    """
+    inv_boxcox(y, lmbda, out=None)
+
+    Compute the inverse of the Box-Cox transformation.
+
+    Find ``x`` such that::
+
+        y = (x**lmbda - 1) / lmbda  if lmbda != 0
+            log(x)                  if lmbda == 0
+
+    Parameters
+    ----------
+    y : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox, inv_boxcox
+    >>> y = boxcox([1, 4, 10], 2.5)
+    >>> inv_boxcox(y, 2.5)
+    array([1., 4., 10.])
+    """)
+
+add_newdoc("inv_boxcox1p",
+    """
+    inv_boxcox1p(y, lmbda, out=None)
+
+    Compute the inverse of the Box-Cox transformation.
+
+    Find ``x`` such that::
+
+        y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0
+            log(1+x)                    if lmbda == 0
+
+    Parameters
+    ----------
+    y : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox1p, inv_boxcox1p
+    >>> y = boxcox1p([1, 4, 10], 2.5)
+    >>> inv_boxcox1p(y, 2.5)
+    array([1., 4., 10.])
+    """)
+
+add_newdoc("chdtr",
+    r"""
+    chdtr(v, x, out=None)
+
+    Chi square cumulative distribution function.
+
+    Returns the area under the left tail (from 0 to `x`) of the Chi
+    square probability density function with `v` degrees of freedom:
+
+    .. math::
+
+        \frac{1}{2^{v/2} \Gamma(v/2)} \int_0^x t^{v/2 - 1} e^{-t/2} dt
+
+    Here :math:`\Gamma` is the Gamma function; see `gamma`. This
+    integral can be expressed in terms of the regularized lower
+    incomplete gamma function `gammainc` as
+    ``gammainc(v / 2, x / 2)``. [1]_
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    x : array_like
+        Upper bound of the integral.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the cumulative distribution function.
+
+    See Also
+    --------
+    chdtrc, chdtri, chdtriv, gammainc
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It can be expressed in terms of the regularized lower incomplete
+    gamma function.
+
+    >>> v = 1
+    >>> x = np.arange(4)
+    >>> sc.chdtr(v, x)
+    array([0.        , 0.68268949, 0.84270079, 0.91673548])
+    >>> sc.gammainc(v / 2, x / 2)
+    array([0.        , 0.68268949, 0.84270079, 0.91673548])
+
+    """)
+
+add_newdoc("chdtrc",
+    r"""
+    chdtrc(v, x, out=None)
+
+    Chi square survival function.
+
+    Returns the area under the right hand tail (from `x` to infinity)
+    of the Chi square probability density function with `v` degrees of
+    freedom:
+
+    .. math::
+
+        \frac{1}{2^{v/2} \Gamma(v/2)} \int_x^\infty t^{v/2 - 1} e^{-t/2} dt
+
+    Here :math:`\Gamma` is the Gamma function; see `gamma`. This
+    integral can be expressed in terms of the regularized upper
+    incomplete gamma function `gammaincc` as
+    ``gammaincc(v / 2, x / 2)``. [1]_
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    x : array_like
+        Lower bound of the integral.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the survival function.
+
+    See Also
+    --------
+    chdtr, chdtri, chdtriv, gammaincc
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It can be expressed in terms of the regularized upper incomplete
+    gamma function.
+
+    >>> v = 1
+    >>> x = np.arange(4)
+    >>> sc.chdtrc(v, x)
+    array([1.        , 0.31731051, 0.15729921, 0.08326452])
+    >>> sc.gammaincc(v / 2, x / 2)
+    array([1.        , 0.31731051, 0.15729921, 0.08326452])
+
+    """)
+
+add_newdoc("chdtri",
+    """
+    chdtri(v, p, out=None)
+
+    Inverse to `chdtrc` with respect to `x`.
+
+    Returns `x` such that ``chdtrc(v, x) == p``.
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    p : array_like
+        Probability.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value so that the probability a Chi square random variable
+        with `v` degrees of freedom is greater than `x` equals `p`.
+
+    See Also
+    --------
+    chdtrc, chdtr, chdtriv
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It inverts `chdtrc`.
+
+    >>> v, p = 1, 0.3
+    >>> sc.chdtrc(v, sc.chdtri(v, p))
+    0.3
+    >>> x = 1
+    >>> sc.chdtri(v, sc.chdtrc(v, x))
+    1.0
+
+    """)
+
+add_newdoc("chdtriv",
+    """
+    chdtriv(p, x, out=None)
+
+    Inverse to `chdtr` with respect to `v`.
+
+    Returns `v` such that ``chdtr(v, x) == p``.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability that the Chi square random variable is less than
+        or equal to `x`.
+    x : array_like
+        Nonnegative input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Degrees of freedom.
+
+    See Also
+    --------
+    chdtr, chdtrc, chdtri
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It inverts `chdtr`.
+
+    >>> p, x = 0.5, 1
+    >>> sc.chdtr(sc.chdtriv(p, x), x)
+    0.5000000000202172
+    >>> v = 1
+    >>> sc.chdtriv(sc.chdtr(v, x), v)
+    1.0000000000000013
+
+    """)
+
+add_newdoc("chndtr",
+    r"""
+    chndtr(x, df, nc, out=None)
+
+    Non-central chi square cumulative distribution function
+
+    The cumulative distribution function is given by:
+
+    .. math::
+
+        P(\chi^{\prime 2} \vert \nu, \lambda) =\sum_{j=0}^{\infty}
+        e^{-\lambda /2}
+        \frac{(\lambda /2)^j}{j!} P(\chi^{\prime 2} \vert \nu + 2j),
+
+    where :math:`\nu > 0` is the degrees of freedom (``df``) and
+    :math:`\lambda \geq 0` is the non-centrality parameter (``nc``).
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value of the non-central chi square cumulative distribution function.
+
+    See Also
+    --------
+    chndtrix, chndtridf, chndtrinc
+
+    """)
+
+add_newdoc("chndtrix",
+    """
+    chndtrix(p, df, nc, out=None)
+
+    Inverse to `chndtr` vs `x`
+
+    Calculated using a search to find a value for `x` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value so that the probability a non-central Chi square random variable
+        with `df` degrees of freedom and non-centrality, `nc`, is greater than
+        `x` equals `p`.
+
+    See Also
+    --------
+    chndtr, chndtridf, chndtrinc
+
+    """)
+
+add_newdoc("chndtridf",
+    """
+    chndtridf(x, p, nc, out=None)
+
+    Inverse to `chndtr` vs `df`
+
+    Calculated using a search to find a value for `df` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        Degrees of freedom
+
+    See Also
+    --------
+    chndtr, chndtrix, chndtrinc
+
+    """)
+
+add_newdoc("chndtrinc",
+    """
+    chndtrinc(x, df, p, out=None)
+
+    Inverse to `chndtr` vs `nc`
+
+    Calculated using a search to find a value for `df` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Non-centrality
+
+    See Also
+    --------
+    chndtr, chndtrix, chndtrinc
+
+    """)
+
+add_newdoc("dawsn",
+    """
+    dawsn(x, out=None)
+
+    Dawson's integral.
+
+    Computes::
+
+        exp(-x**2) * integral(exp(t**2), t=0..x).
+
+    Parameters
+    ----------
+    x : array_like
+        Function parameter.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Value of the integral.
+
+    See Also
+    --------
+    wofz, erf, erfc, erfcx, erfi
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-15, 15, num=1000)
+    >>> plt.plot(x, special.dawsn(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$dawsn(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "elliprc",
+    r"""
+    elliprc(x, y, out=None)
+
+    Degenerate symmetric elliptic integral.
+
+    The function RC is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{C}}(x, y) =
+           \frac{1}{2} \int_0^{+\infty} (t + x)^{-1/2} (t + y)^{-1} dt
+           = R_{\mathrm{F}}(x, y, y)
+
+    Parameters
+    ----------
+    x, y : array_like
+        Real or complex input parameters. `x` can be any number in the
+        complex plane cut along the negative real axis. `y` must be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If `y` is real and negative, the Cauchy
+        principal value is returned. If both of `x` and `y` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    RC is a degenerate case of the symmetric integral RF: ``elliprc(x, y) ==
+    elliprf(x, y, y)``. It is an elementary function rather than an elliptic
+    integral.
+
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E6
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprc
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprc(scale*x, scale*y)
+    (0.5484493976710874-0.4169557678995833j)
+
+    >>> elliprc(x, y)/np.sqrt(scale)
+    (0.5484493976710874-0.41695576789958333j)
+
+    When the two arguments coincide, the integral is particularly
+    simple:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprc(x, x)
+    (0.4299173120614631-0.3041729818745595j)
+
+    >>> 1/np.sqrt(x)
+    (0.4299173120614631-0.30417298187455954j)
+
+    Another simple case: the first argument vanishes:
+
+    >>> y = 1.2 + 3.4j
+    >>> elliprc(0, y)
+    (0.6753125346116815-0.47779380263880866j)
+
+    >>> np.pi/2/np.sqrt(y)
+    (0.6753125346116815-0.4777938026388088j)
+
+    When `x` and `y` are both positive, we can express
+    :math:`R_C(x,y)` in terms of more elementary functions.  For the
+    case :math:`0 \le x < y`,
+
+    >>> x = 3.2
+    >>> y = 6.
+    >>> elliprc(x, y)
+    0.44942991498453444
+
+    >>> np.arctan(np.sqrt((y-x)/x))/np.sqrt(y-x)
+    0.44942991498453433
+
+    And for the case :math:`0 \le y < x`,
+
+    >>> x = 6.
+    >>> y = 3.2
+    >>> elliprc(x,y)
+    0.4989837501576147
+
+    >>> np.log((np.sqrt(x)+np.sqrt(x-y))/np.sqrt(y))/np.sqrt(x-y)
+    0.49898375015761476
+
+    """)
+
+add_newdoc(
+    "elliprd",
+    r"""
+    elliprd(x, y, z, out=None)
+
+    Symmetric elliptic integral of the second kind.
+
+    The function RD is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{D}}(x, y, z) =
+           \frac{3}{2} \int_0^{+\infty} [(t + x) (t + y)]^{-1/2} (t + z)^{-3/2}
+           dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x` or `y` can be any number in the
+        complex plane cut along the negative real axis, but at most one of them
+        can be zero, while `z` must be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric elliptic integral.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    RD is a degenerate case of the elliptic integral RJ: ``elliprd(x, y, z) ==
+    elliprj(x, y, z, z)``.
+
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E5
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprd
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprd(scale*x, scale*y, scale*z)
+    (-0.03703043835680379-0.24500934665683802j)
+
+    >>> elliprd(x, y, z)*np.power(scale, -1.5)
+    (-0.0370304383568038-0.24500934665683805j)
+
+    All three arguments coincide:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprd(x, x, x)
+    (-0.03986825876151896-0.14051741840449586j)
+
+    >>> np.power(x, -1.5)
+    (-0.03986825876151894-0.14051741840449583j)
+
+    The so-called "second lemniscate constant":
+
+    >>> elliprd(0, 2, 1)/3
+    0.5990701173677961
+
+    >>> from scipy.special import gamma
+    >>> gamma(0.75)**2/np.sqrt(2*np.pi)
+    0.5990701173677959
+
+    """)
+
+add_newdoc(
+    "elliprf",
+    r"""
+    elliprf(x, y, z, out=None)
+
+    Completely-symmetric elliptic integral of the first kind.
+
+    The function RF is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{F}}(x, y, z) =
+           \frac{1}{2} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2} dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x`, `y`, or `z` can be any number in
+        the complex plane cut along the negative real axis, but at most one of
+        them can be zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the return
+        value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order (cf.:
+    https://dlmf.nist.gov/19.36.i) and the AGM algorithm for the complete
+    integral. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E1
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprf
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprf(scale*x, scale*y, scale*z)
+    (0.5328051227278146-0.4008623567957094j)
+
+    >>> elliprf(x, y, z)/np.sqrt(scale)
+    (0.5328051227278147-0.4008623567957095j)
+
+    All three arguments coincide:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprf(x, x, x)
+    (0.42991731206146316-0.30417298187455954j)
+
+    >>> 1/np.sqrt(x)
+    (0.4299173120614631-0.30417298187455954j)
+
+    The so-called "first lemniscate constant":
+
+    >>> elliprf(0, 1, 2)
+    1.3110287771460598
+
+    >>> from scipy.special import gamma
+    >>> gamma(0.25)**2/(4*np.sqrt(2*np.pi))
+    1.3110287771460598
+
+    """)
+
+add_newdoc(
+    "elliprg",
+    r"""
+    elliprg(x, y, z, out=None)
+
+    Completely-symmetric elliptic integral of the second kind.
+
+    The function RG is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{G}}(x, y, z) =
+           \frac{1}{4} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2}
+           \left(\frac{x}{t + x} + \frac{y}{t + y} + \frac{z}{t + z}\right) t
+           dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x`, `y`, or `z` can be any number in
+        the complex plane cut along the negative real axis.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the return
+        value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    The implementation uses the relation [1]_
+
+    .. math::
+
+        2 R_{\mathrm{G}}(x, y, z) =
+           z R_{\mathrm{F}}(x, y, z) -
+           \frac{1}{3} (x - z) (y - z) R_{\mathrm{D}}(x, y, z) +
+           \sqrt{\frac{x y}{z}}
+
+    and the symmetry of `x`, `y`, `z` when at least one non-zero parameter can
+    be chosen as the pivot. When one of the arguments is close to zero, the AGM
+    method is applied instead. Other special cases are computed following Ref.
+    [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+    .. [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E1
+           https://dlmf.nist.gov/19.20.ii
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprg
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprg(scale*x, scale*y, scale*z)
+    (1.195936862005246+0.8470988320464167j)
+
+    >>> elliprg(x, y, z)*np.sqrt(scale)
+    (1.195936862005246+0.8470988320464165j)
+
+    Simplifications:
+
+    >>> elliprg(0, y, y)
+    1.756203682760182
+
+    >>> 0.25*np.pi*np.sqrt(y)
+    1.7562036827601817
+
+    >>> elliprg(0, 0, z)
+    1.224744871391589
+
+    >>> 0.5*np.sqrt(z)
+    1.224744871391589
+
+    The surface area of a triaxial ellipsoid with semiaxes ``a``, ``b``, and
+    ``c`` is given by
+
+    .. math::
+
+        S = 4 \pi a b c R_{\mathrm{G}}(1 / a^2, 1 / b^2, 1 / c^2).
+
+    >>> def ellipsoid_area(a, b, c):
+    ...     r = 4.0 * np.pi * a * b * c
+    ...     return r * elliprg(1.0 / (a * a), 1.0 / (b * b), 1.0 / (c * c))
+    >>> print(ellipsoid_area(1, 3, 5))
+    108.62688289491807
+    """)
+
+add_newdoc(
+    "elliprj",
+    r"""
+    elliprj(x, y, z, p, out=None)
+
+    Symmetric elliptic integral of the third kind.
+
+    The function RJ is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{J}}(x, y, z, p) =
+           \frac{3}{2} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2}
+           (t + p)^{-1} dt
+
+    .. warning::
+        This function should be considered experimental when the inputs are
+        unbalanced.  Check correctness with another independent implementation.
+
+    Parameters
+    ----------
+    x, y, z, p : array_like
+        Real or complex input parameters. `x`, `y`, or `z` are numbers in
+        the complex plane cut along the negative real axis (subject to further
+        constraints, see Notes), and at most one of them can be zero. `p` must
+        be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, `z`, and `p` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+        If `p` is real and negative, while `x`, `y`, and `z` are real,
+        non-negative, and at most one of them is zero, the Cauchy principal
+        value is returned. [1]_ [2]_
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+
+    Notes
+    -----
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [3]_ The algorithm is slightly
+    different from its earlier incarnation as it appears in [1]_, in that the
+    call to `elliprc` (or ``atan``/``atanh``, see [4]_) is no longer needed in
+    the inner loop. Asymptotic approximations are used where arguments differ
+    widely in the order of magnitude. [5]_
+
+    The input values are subject to certain sufficient but not necessary
+    constraints when input arguments are complex. Notably, ``x``, ``y``, and
+    ``z`` must have non-negative real parts, unless two of them are
+    non-negative and complex-conjugates to each other while the other is a real
+    non-negative number. [1]_ If the inputs do not satisfy the sufficient
+    condition described in Ref. [1]_ they are rejected outright with the output
+    set to NaN.
+
+    In the case where one of ``x``, ``y``, and ``z`` is equal to ``p``, the
+    function ``elliprd`` should be preferred because of its less restrictive
+    domain.
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+    .. [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.20.iii
+    .. [3] B. C. Carlson, J. FitzSimmons, "Reduction Theorems for Elliptic
+           Integrands with the Square Root of Two Quadratic Factors," J.
+           Comput. Appl. Math., vol. 118, nos. 1-2, pp. 71-85, 2000.
+           https://doi.org/10.1016/S0377-0427(00)00282-X
+    .. [4] F. Johansson, "Numerical Evaluation of Elliptic Functions, Elliptic
+           Integrals and Modular Forms," in J. Blumlein, C. Schneider, P.
+           Paule, eds., "Elliptic Integrals, Elliptic Functions and Modular
+           Forms in Quantum Field Theory," pp. 269-293, 2019 (Cham,
+           Switzerland: Springer Nature Switzerland)
+           https://arxiv.org/abs/1806.06725
+           https://doi.org/10.1007/978-3-030-04480-0
+    .. [5] B. C. Carlson, J. L. Gustafson, "Asymptotic Approximations for
+           Symmetric Elliptic Integrals," SIAM J. Math. Anls., vol. 25, no. 2,
+           pp. 288-303, 1994.
+           https://arxiv.org/abs/math/9310223
+           https://doi.org/10.1137/S0036141092228477
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprj
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> p = 7.
+    >>> scale = 0.3 - 0.4j
+    >>> elliprj(scale*x, scale*y, scale*z, scale*p)
+    (0.10834905565679157+0.19694950747103812j)
+
+    >>> elliprj(x, y, z, p)*np.power(scale, -1.5)
+    (0.10834905565679556+0.19694950747103854j)
+
+    Reduction to simpler elliptic integral:
+
+    >>> elliprj(x, y, z, z)
+    (0.08288462362195129-0.028376809745123258j)
+
+    >>> from scipy.special import elliprd
+    >>> elliprd(x, y, z)
+    (0.08288462362195136-0.028376809745123296j)
+
+    All arguments coincide:
+
+    >>> elliprj(x, x, x, x)
+    (-0.03986825876151896-0.14051741840449586j)
+
+    >>> np.power(x, -1.5)
+    (-0.03986825876151894-0.14051741840449583j)
+
+    """)
+
+add_newdoc("entr",
+    r"""
+    entr(x, out=None)
+
+    Elementwise function for computing entropy.
+
+    .. math:: \text{entr}(x) = \begin{cases} - x \log(x) & x > 0  \\ 0 & x = 0
+              \\ -\infty & \text{otherwise} \end{cases}
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The value of the elementwise entropy function at the given points `x`.
+
+    See Also
+    --------
+    kl_div, rel_entr, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is concave.
+
+    The origin of this function is in convex programming; see [1]_.
+    Given a probability distribution :math:`p_1, \ldots, p_n`,
+    the definition of entropy in the context of *information theory* is
+
+    .. math::
+
+        \sum_{i = 1}^n \mathrm{entr}(p_i).
+
+    To compute the latter quantity, use `scipy.stats.entropy`.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+
+    """)
+
+add_newdoc("erf",
+    """
+    erf(z, out=None)
+
+    Returns the error function of complex argument.
+
+    It is defined as ``2/sqrt(pi)*integral(exp(-t**2), t=0..z)``.
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The values of the error function at the given points `x`.
+
+    See Also
+    --------
+    erfc, erfinv, erfcinv, wofz, erfcx, erfi
+
+    Notes
+    -----
+    The cumulative of the unit normal distribution is given by
+    ``Phi(z) = 1/2[1 + erf(z/sqrt(2))]``.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Error_function
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover,
+        1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm
+    .. [3] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erf(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erf(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfc",
+    """
+    erfc(x, out=None)
+
+    Complementary error function, ``1 - erf(x)``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the complementary error function
+
+    See Also
+    --------
+    erf, erfi, erfcx, dawsn, wofz
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfc(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfc(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfi",
+    """
+    erfi(z, out=None)
+
+    Imaginary error function, ``-i erf(i z)``.
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the imaginary error function
+
+    See Also
+    --------
+    erf, erfc, erfcx, dawsn, wofz
+
+    Notes
+    -----
+
+    .. versionadded:: 0.12.0
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfi(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfi(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfcx",
+    """
+    erfcx(x, out=None)
+
+    Scaled complementary error function, ``exp(x**2) * erfc(x)``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the scaled complementary error function
+
+
+    See Also
+    --------
+    erf, erfc, erfi, dawsn, wofz
+
+    Notes
+    -----
+
+    .. versionadded:: 0.12.0
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfcx(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfcx(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "erfinv",
+    """
+    erfinv(y, out=None)
+
+    Inverse of the error function.
+
+    Computes the inverse of the error function.
+
+    In the complex domain, there is no unique complex number w satisfying
+    erf(w)=z. This indicates a true inverse function would be multivalued.
+    When the domain restricts to the real, -1 < x < 1, there is a unique real
+    number satisfying erf(erfinv(x)) = x.
+
+    Parameters
+    ----------
+    y : ndarray
+        Argument at which to evaluate. Domain: [-1, 1]
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    erfinv : scalar or ndarray
+        The inverse of erf of y, element-wise
+
+    See Also
+    --------
+    erf : Error function of a complex argument
+    erfc : Complementary error function, ``1 - erf(x)``
+    erfcinv : Inverse of the complementary error function
+
+    Notes
+    -----
+    This function wraps the ``erf_inv`` routine from the
+    Boost Math C++ library [1]_.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import erfinv, erf
+
+    >>> erfinv(0.5)
+    0.4769362762044699
+
+    >>> y = np.linspace(-1.0, 1.0, num=9)
+    >>> x = erfinv(y)
+    >>> x
+    array([       -inf, -0.81341985, -0.47693628, -0.22531206,  0.        ,
+            0.22531206,  0.47693628,  0.81341985,         inf])
+
+    Verify that ``erf(erfinv(y))`` is ``y``.
+
+    >>> erf(x)
+    array([-1.  , -0.75, -0.5 , -0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ])
+
+    Plot the function:
+
+    >>> y = np.linspace(-1, 1, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(y, erfinv(y))
+    >>> ax.grid(True)
+    >>> ax.set_xlabel('y')
+    >>> ax.set_title('erfinv(y)')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "erfcinv",
+    """
+    erfcinv(y, out=None)
+
+    Inverse of the complementary error function.
+
+    Computes the inverse of the complementary error function.
+
+    In the complex domain, there is no unique complex number w satisfying
+    erfc(w)=z. This indicates a true inverse function would be multivalued.
+    When the domain restricts to the real, 0 < x < 2, there is a unique real
+    number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).
+
+    It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)
+
+    Parameters
+    ----------
+    y : ndarray
+        Argument at which to evaluate. Domain: [0, 2]
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    erfcinv : scalar or ndarray
+        The inverse of erfc of y, element-wise
+
+    See Also
+    --------
+    erf : Error function of a complex argument
+    erfc : Complementary error function, ``1 - erf(x)``
+    erfinv : Inverse of the error function
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import erfcinv
+
+    >>> erfcinv(0.5)
+    0.4769362762044699
+
+    >>> y = np.linspace(0.0, 2.0, num=11)
+    >>> erfcinv(y)
+    array([        inf,  0.9061938 ,  0.59511608,  0.37080716,  0.17914345,
+           -0.        , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,
+                  -inf])
+
+    Plot the function:
+
+    >>> y = np.linspace(0, 2, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(y, erfcinv(y))
+    >>> ax.grid(True)
+    >>> ax.set_xlabel('y')
+    >>> ax.set_title('erfcinv(y)')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("eval_jacobi",
+    r"""
+    eval_jacobi(n, alpha, beta, x, out=None)
+
+    Evaluate Jacobi polynomial at a point.
+
+    The Jacobi polynomials can be defined via the Gauss hypergeometric
+    function :math:`{}_2F_1` as
+
+    .. math::
+
+        P_n^{(\alpha, \beta)}(x) = \frac{(\alpha + 1)_n}{\Gamma(n + 1)}
+          {}_2F_1(-n, 1 + \alpha + \beta + n; \alpha + 1; (1 - z)/2)
+
+    where :math:`(\cdot)_n` is the Pochhammer symbol; see `poch`. When
+    :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.42 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    alpha : array_like
+        Parameter
+    beta : array_like
+        Parameter
+    x : array_like
+        Points at which to evaluate the polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the Jacobi polynomial
+
+    See Also
+    --------
+    roots_jacobi : roots and quadrature weights of Jacobi polynomials
+    jacobi : Jacobi polynomial object
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_sh_jacobi",
+    r"""
+    eval_sh_jacobi(n, p, q, x, out=None)
+
+    Evaluate shifted Jacobi polynomial at a point.
+
+    Defined by
+
+    .. math::
+
+        G_n^{(p, q)}(x)
+          = \binom{2n + p - 1}{n}^{-1} P_n^{(p - q, q - 1)}(2x - 1),
+
+    where :math:`P_n^{(\cdot, \cdot)}` is the n-th Jacobi
+    polynomial. See 22.5.2 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `binom` and `eval_jacobi`.
+    p : float
+        Parameter
+    q : float
+        Parameter
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    G : scalar or ndarray
+        Values of the shifted Jacobi polynomial.
+
+    See Also
+    --------
+    roots_sh_jacobi : roots and quadrature weights of shifted Jacobi
+                      polynomials
+    sh_jacobi : shifted Jacobi polynomial object
+    eval_jacobi : evaluate Jacobi polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_gegenbauer",
+    r"""
+    eval_gegenbauer(n, alpha, x, out=None)
+
+    Evaluate Gegenbauer polynomial at a point.
+
+    The Gegenbauer polynomials can be defined via the Gauss
+    hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        C_n^{(\alpha)} = \frac{(2\alpha)_n}{\Gamma(n + 1)}
+          {}_2F_1(-n, 2\alpha + n; \alpha + 1/2; (1 - z)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.46 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    alpha : array_like
+        Parameter
+    x : array_like
+        Points at which to evaluate the Gegenbauer polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    C : scalar or ndarray
+        Values of the Gegenbauer polynomial
+
+    See Also
+    --------
+    roots_gegenbauer : roots and quadrature weights of Gegenbauer
+                       polynomials
+    gegenbauer : Gegenbauer polynomial object
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebyt",
+    r"""
+    eval_chebyt(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the first kind at a point.
+
+    The Chebyshev polynomials of the first kind can be defined via the
+    Gauss hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        T_n(x) = {}_2F_1(n, -n; 1/2; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.47 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    T : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyt : roots and quadrature weights of Chebyshev
+                   polynomials of the first kind
+    chebyu : Chebychev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+    hyp2f1 : Gauss hypergeometric function
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+
+    Notes
+    -----
+    This routine is numerically stable for `x` in ``[-1, 1]`` at least
+    up to order ``10000``.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebyu",
+    r"""
+    eval_chebyu(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the second kind at a point.
+
+    The Chebyshev polynomials of the second kind can be defined via
+    the Gauss hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        U_n(x) = (n + 1) {}_2F_1(-n, n + 2; 3/2; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.48 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    U : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyu : roots and quadrature weights of Chebyshev
+                   polynomials of the second kind
+    chebyu : Chebyshev polynomial object
+    eval_chebyt : evaluate Chebyshev polynomials of the first kind
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebys",
+    r"""
+    eval_chebys(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        S_n(x) = U_n(x/2)
+
+    where :math:`U_n` is a Chebyshev polynomial of the second
+    kind. See 22.5.13 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyu`.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    S : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebys : roots and quadrature weights of Chebyshev
+                   polynomials of the second kind on [-2, 2]
+    chebys : Chebyshev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    They are a scaled version of the Chebyshev polynomials of the
+    second kind.
+
+    >>> x = np.linspace(-2, 2, 6)
+    >>> sc.eval_chebys(3, x)
+    array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])
+    >>> sc.eval_chebyu(3, x / 2)
+    array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])
+
+    """)
+
+add_newdoc("eval_chebyc",
+    r"""
+    eval_chebyc(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        C_n(x) = 2 T_n(x/2)
+
+    where :math:`T_n` is a Chebyshev polynomial of the first kind. See
+    22.5.11 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyt`.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    C : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyc : roots and quadrature weights of Chebyshev
+                   polynomials of the first kind on [-2, 2]
+    chebyc : Chebyshev polynomial object
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+    eval_chebyt : evaluate Chebycshev polynomials of the first kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    They are a scaled version of the Chebyshev polynomials of the
+    first kind.
+
+    >>> x = np.linspace(-2, 2, 6)
+    >>> sc.eval_chebyc(3, x)
+    array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])
+    >>> 2 * sc.eval_chebyt(3, x / 2)
+    array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])
+
+    """)
+
+add_newdoc("eval_sh_chebyt",
+    r"""
+    eval_sh_chebyt(n, x, out=None)
+
+    Evaluate shifted Chebyshev polynomial of the first kind at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        T_n^*(x) = T_n(2x - 1)
+
+    where :math:`T_n` is a Chebyshev polynomial of the first kind. See
+    22.5.14 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyt`.
+    x : array_like
+        Points at which to evaluate the shifted Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    T : scalar or ndarray
+        Values of the shifted Chebyshev polynomial
+
+    See Also
+    --------
+    roots_sh_chebyt : roots and quadrature weights of shifted
+                      Chebyshev polynomials of the first kind
+    sh_chebyt : shifted Chebyshev polynomial object
+    eval_chebyt : evaluate Chebyshev polynomials of the first kind
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_sh_chebyu",
+    r"""
+    eval_sh_chebyu(n, x, out=None)
+
+    Evaluate shifted Chebyshev polynomial of the second kind at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        U_n^*(x) = U_n(2x - 1)
+
+    where :math:`U_n` is a Chebyshev polynomial of the first kind. See
+    22.5.15 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyu`.
+    x : array_like
+        Points at which to evaluate the shifted Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    U : scalar or ndarray
+        Values of the shifted Chebyshev polynomial
+
+    See Also
+    --------
+    roots_sh_chebyu : roots and quadrature weights of shifted
+                      Chebychev polynomials of the second kind
+    sh_chebyu : shifted Chebyshev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_legendre",
+    r"""
+    eval_legendre(n, x, out=None)
+
+    Evaluate Legendre polynomial at a point.
+
+    The Legendre polynomials can be defined via the Gauss
+    hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        P_n(x) = {}_2F_1(-n, n + 1; 1; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.49 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Legendre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the Legendre polynomial
+
+    See Also
+    --------
+    roots_legendre : roots and quadrature weights of Legendre
+                     polynomials
+    legendre : Legendre polynomial object
+    hyp2f1 : Gauss hypergeometric function
+    numpy.polynomial.legendre.Legendre : Legendre series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import eval_legendre
+
+    Evaluate the zero-order Legendre polynomial at x = 0
+
+    >>> eval_legendre(0, 0)
+    1.0
+
+    Evaluate the first-order Legendre polynomial between -1 and 1
+
+    >>> X = np.linspace(-1, 1, 5)  # Domain of Legendre polynomials
+    >>> eval_legendre(1, X)
+    array([-1. , -0.5,  0. ,  0.5,  1. ])
+
+    Evaluate Legendre polynomials of order 0 through 4 at x = 0
+
+    >>> N = range(0, 5)
+    >>> eval_legendre(N, 0)
+    array([ 1.   ,  0.   , -0.5  ,  0.   ,  0.375])
+
+    Plot Legendre polynomials of order 0 through 4
+
+    >>> X = np.linspace(-1, 1)
+
+    >>> import matplotlib.pyplot as plt
+    >>> for n in range(0, 5):
+    ...     y = eval_legendre(n, X)
+    ...     plt.plot(X, y, label=r'$P_{}(x)$'.format(n))
+
+    >>> plt.title("Legendre Polynomials")
+    >>> plt.xlabel("x")
+    >>> plt.ylabel(r'$P_n(x)$')
+    >>> plt.legend(loc='lower right')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("eval_sh_legendre",
+    r"""
+    eval_sh_legendre(n, x, out=None)
+
+    Evaluate shifted Legendre polynomial at a point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        P_n^*(x) = P_n(2x - 1)
+
+    where :math:`P_n` is a Legendre polynomial. See 2.2.11 in [AS]_
+    for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the value is
+        determined via the relation to `eval_legendre`.
+    x : array_like
+        Points at which to evaluate the shifted Legendre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the shifted Legendre polynomial
+
+    See Also
+    --------
+    roots_sh_legendre : roots and quadrature weights of shifted
+                        Legendre polynomials
+    sh_legendre : shifted Legendre polynomial object
+    eval_legendre : evaluate Legendre polynomials
+    numpy.polynomial.legendre.Legendre : Legendre series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_genlaguerre",
+    r"""
+    eval_genlaguerre(n, alpha, x, out=None)
+
+    Evaluate generalized Laguerre polynomial at a point.
+
+    The generalized Laguerre polynomials can be defined via the
+    confluent hypergeometric function :math:`{}_1F_1` as
+
+    .. math::
+
+        L_n^{(\alpha)}(x) = \binom{n + \alpha}{n}
+          {}_1F_1(-n, \alpha + 1, x).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.54 in [AS]_ for details. The Laguerre
+    polynomials are the special case where :math:`\alpha = 0`.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the confluent hypergeometric
+        function.
+    alpha : array_like
+        Parameter; must have ``alpha > -1``
+    x : array_like
+        Points at which to evaluate the generalized Laguerre
+        polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    L : scalar or ndarray
+        Values of the generalized Laguerre polynomial
+
+    See Also
+    --------
+    roots_genlaguerre : roots and quadrature weights of generalized
+                        Laguerre polynomials
+    genlaguerre : generalized Laguerre polynomial object
+    hyp1f1 : confluent hypergeometric function
+    eval_laguerre : evaluate Laguerre polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_laguerre",
+    r"""
+    eval_laguerre(n, x, out=None)
+
+    Evaluate Laguerre polynomial at a point.
+
+    The Laguerre polynomials can be defined via the confluent
+    hypergeometric function :math:`{}_1F_1` as
+
+    .. math::
+
+        L_n(x) = {}_1F_1(-n, 1, x).
+
+    See 22.5.16 and 22.5.54 in [AS]_ for details. When :math:`n` is an
+    integer the result is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer the result is
+        determined via the relation to the confluent hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Laguerre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    L : scalar or ndarray
+        Values of the Laguerre polynomial
+
+    See Also
+    --------
+    roots_laguerre : roots and quadrature weights of Laguerre
+                     polynomials
+    laguerre : Laguerre polynomial object
+    numpy.polynomial.laguerre.Laguerre : Laguerre series
+    eval_genlaguerre : evaluate generalized Laguerre polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+     """)
+
+add_newdoc("eval_hermite",
+    r"""
+    eval_hermite(n, x, out=None)
+
+    Evaluate physicist's Hermite polynomial at a point.
+
+    Defined by
+
+    .. math::
+
+        H_n(x) = (-1)^n e^{x^2} \frac{d^n}{dx^n} e^{-x^2};
+
+    :math:`H_n` is a polynomial of degree :math:`n`. See 22.11.7 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial
+    x : array_like
+        Points at which to evaluate the Hermite polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    H : scalar or ndarray
+        Values of the Hermite polynomial
+
+    See Also
+    --------
+    roots_hermite : roots and quadrature weights of physicist's
+                    Hermite polynomials
+    hermite : physicist's Hermite polynomial object
+    numpy.polynomial.hermite.Hermite : Physicist's Hermite series
+    eval_hermitenorm : evaluate Probabilist's Hermite polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_hermitenorm",
+    r"""
+    eval_hermitenorm(n, x, out=None)
+
+    Evaluate probabilist's (normalized) Hermite polynomial at a
+    point.
+
+    Defined by
+
+    .. math::
+
+        He_n(x) = (-1)^n e^{x^2/2} \frac{d^n}{dx^n} e^{-x^2/2};
+
+    :math:`He_n` is a polynomial of degree :math:`n`. See 22.11.8 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial
+    x : array_like
+        Points at which to evaluate the Hermite polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    He : scalar or ndarray
+        Values of the Hermite polynomial
+
+    See Also
+    --------
+    roots_hermitenorm : roots and quadrature weights of probabilist's
+                        Hermite polynomials
+    hermitenorm : probabilist's Hermite polynomial object
+    numpy.polynomial.hermite_e.HermiteE : Probabilist's Hermite series
+    eval_hermite : evaluate physicist's Hermite polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+
+add_newdoc("exp10",
+    """
+    exp10(x, out=None)
+
+    Compute ``10**x`` element-wise.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``10**x``, computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import exp10
+
+    >>> exp10(3)
+    1000.0
+    >>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])
+    >>> exp10(x)
+    array([[  0.1       ,   0.31622777,   1.        ],
+           [  3.16227766,  10.        ,  31.6227766 ]])
+
+    """)
+
+add_newdoc("exp2",
+    """
+    exp2(x, out=None)
+
+    Compute ``2**x`` element-wise.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``2**x``, computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import exp2
+
+    >>> exp2(3)
+    8.0
+    >>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])
+    >>> exp2(x)
+    array([[ 0.5       ,  0.70710678,  1.        ],
+           [ 1.41421356,  2.        ,  2.82842712]])
+    """)
+
+add_newdoc("expm1",
+    """
+    expm1(x, out=None)
+
+    Compute ``exp(x) - 1``.
+
+    When `x` is near zero, ``exp(x)`` is near 1, so the numerical calculation
+    of ``exp(x) - 1`` can suffer from catastrophic loss of precision.
+    ``expm1(x)`` is implemented to avoid the loss of precision that occurs when
+    `x` is near zero.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``exp(x) - 1`` computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import expm1
+
+    >>> expm1(1.0)
+    1.7182818284590451
+    >>> expm1([-0.2, -0.1, 0, 0.1, 0.2])
+    array([-0.18126925, -0.09516258,  0.        ,  0.10517092,  0.22140276])
+
+    The exact value of ``exp(7.5e-13) - 1`` is::
+
+        7.5000000000028125000000007031250000001318...*10**-13.
+
+    Here is what ``expm1(7.5e-13)`` gives:
+
+    >>> expm1(7.5e-13)
+    7.5000000000028135e-13
+
+    Compare that to ``exp(7.5e-13) - 1``, where the subtraction results in
+    a "catastrophic" loss of precision:
+
+    >>> np.exp(7.5e-13) - 1
+    7.5006667543675576e-13
+
+    """)
+
+add_newdoc("expn",
+    r"""
+    expn(n, x, out=None)
+
+    Generalized exponential integral En.
+
+    For integer :math:`n \geq 0` and real :math:`x \geq 0` the
+    generalized exponential integral is defined as [dlmf]_
+
+    .. math::
+
+        E_n(x) = x^{n - 1} \int_x^\infty \frac{e^{-t}}{t^n} dt.
+
+    Parameters
+    ----------
+    n : array_like
+        Non-negative integers
+    x : array_like
+        Real argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the generalized exponential integral
+
+    See Also
+    --------
+    exp1 : special case of :math:`E_n` for :math:`n = 1`
+    expi : related to :math:`E_n` when :math:`n = 1`
+
+    References
+    ----------
+    .. [dlmf] Digital Library of Mathematical Functions, 8.19.2
+              https://dlmf.nist.gov/8.19#E2
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    Its domain is nonnegative n and x.
+
+    >>> sc.expn(-1, 1.0), sc.expn(1, -1.0)
+    (nan, nan)
+
+    It has a pole at ``x = 0`` for ``n = 1, 2``; for larger ``n`` it
+    is equal to ``1 / (n - 1)``.
+
+    >>> sc.expn([0, 1, 2, 3, 4], 0)
+    array([       inf,        inf, 1.        , 0.5       , 0.33333333])
+
+    For n equal to 0 it reduces to ``exp(-x) / x``.
+
+    >>> x = np.array([1, 2, 3, 4])
+    >>> sc.expn(0, x)
+    array([0.36787944, 0.06766764, 0.01659569, 0.00457891])
+    >>> np.exp(-x) / x
+    array([0.36787944, 0.06766764, 0.01659569, 0.00457891])
+
+    For n equal to 1 it reduces to `exp1`.
+
+    >>> sc.expn(1, x)
+    array([0.21938393, 0.04890051, 0.01304838, 0.00377935])
+    >>> sc.exp1(x)
+    array([0.21938393, 0.04890051, 0.01304838, 0.00377935])
+
+    """)
+
+add_newdoc("fdtr",
+    r"""
+    fdtr(dfn, dfd, x, out=None)
+
+    F cumulative distribution function.
+
+    Returns the value of the cumulative distribution function of the
+    F-distribution, also known as Snedecor's F-distribution or the
+    Fisher-Snedecor distribution.
+
+    The F-distribution with parameters :math:`d_n` and :math:`d_d` is the
+    distribution of the random variable,
+
+    .. math::
+        X = \frac{U_n/d_n}{U_d/d_d},
+
+    where :math:`U_n` and :math:`U_d` are random variables distributed
+    :math:`\chi^2`, with :math:`d_n` and :math:`d_d` degrees of freedom,
+    respectively.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        The CDF of the F-distribution with parameters `dfn` and `dfd` at `x`.
+
+    See Also
+    --------
+    fdtrc : F distribution survival function
+    fdtri : F distribution inverse cumulative distribution
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The regularized incomplete beta function is used, according to the
+    formula,
+
+    .. math::
+        F(d_n, d_d; x) = I_{xd_n/(d_d + xd_n)}(d_n/2, d_d/2).
+
+    Wrapper for the Cephes [1]_ routine `fdtr`. The F distribution is also
+    available as `scipy.stats.f`. Calling `fdtr` directly can improve
+    performance compared to the ``cdf`` method of `scipy.stats.f` (see last
+    example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtr
+    >>> fdtr(1, 2, 1)
+    0.5773502691896258
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.5, 2., 3.])
+    >>> fdtr(1, 2, x)
+    array([0.4472136 , 0.70710678, 0.77459667])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [1, 5, 10, 50]
+    >>> dfd_parameters = [1, 1, 2, 3]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtr_vals = fdtr(dfn, dfd, x)
+    ...     ax.plot(x, fdtr_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("F distribution cumulative distribution function")
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtr`
+    directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).cdf(x)=fdtr(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 1
+    >>> fdtr_res = fdtr(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).cdf(x)
+    >>> fdtr_res == f_dist_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtrc",
+    r"""
+    fdtrc(dfn, dfd, x, out=None)
+
+    F survival function.
+
+    Returns the complemented F-distribution function (the integral of the
+    density from `x` to infinity).
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        The complemented F-distribution function with parameters `dfn` and
+        `dfd` at `x`.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtri : F distribution inverse cumulative distribution function
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The regularized incomplete beta function is used, according to the
+    formula,
+
+    .. math::
+        F(d_n, d_d; x) = I_{d_d/(d_d + xd_n)}(d_d/2, d_n/2).
+
+    Wrapper for the Cephes [1]_ routine `fdtrc`. The F distribution is also
+    available as `scipy.stats.f`. Calling `fdtrc` directly can improve
+    performance compared to the ``sf`` method of `scipy.stats.f` (see last
+    example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtrc
+    >>> fdtrc(1, 2, 1)
+    0.42264973081037427
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.5, 2., 3.])
+    >>> fdtrc(1, 2, x)
+    array([0.5527864 , 0.29289322, 0.22540333])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [1, 5, 10, 50]
+    >>> dfd_parameters = [1, 1, 2, 3]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtrc_vals = fdtrc(dfn, dfd, x)
+    ...     ax.plot(x, fdtrc_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("F distribution survival function")
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtrc`
+    directly can be much faster than calling the ``sf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).sf(x)=fdtrc(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 1
+    >>> fdtrc_res = fdtrc(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).sf(x)
+    >>> f_dist_res == fdtrc_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtri",
+    r"""
+    fdtri(dfn, dfd, p, out=None)
+
+    The `p`-th quantile of the F-distribution.
+
+    This function is the inverse of the F-distribution CDF, `fdtr`, returning
+    the `x` such that `fdtr(dfn, dfd, x) = p`.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        The quantile corresponding to `p`.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtrc : F distribution survival function
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The computation is carried out using the relation to the inverse
+    regularized beta function, :math:`I^{-1}_x(a, b)`.  Let
+    :math:`z = I^{-1}_p(d_d/2, d_n/2).`  Then,
+
+    .. math::
+        x = \frac{d_d (1 - z)}{d_n z}.
+
+    If `p` is such that :math:`x < 0.5`, the following relation is used
+    instead for improved stability: let
+    :math:`z' = I^{-1}_{1 - p}(d_n/2, d_d/2).` Then,
+
+    .. math::
+        x = \frac{d_d z'}{d_n (1 - z')}.
+
+    Wrapper for the Cephes [1]_ routine `fdtri`.
+
+    The F distribution is also available as `scipy.stats.f`. Calling
+    `fdtri` directly can improve performance compared to the ``ppf``
+    method of `scipy.stats.f` (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    `fdtri` represents the inverse of the F distribution CDF which is
+    available as `fdtr`. Here, we calculate the CDF for ``df1=1``, ``df2=2``
+    at ``x=3``. `fdtri` then returns ``3`` given the same values for `df1`,
+    `df2` and the computed CDF value.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtri, fdtr
+    >>> df1, df2 = 1, 2
+    >>> x = 3
+    >>> cdf_value =  fdtr(df1, df2, x)
+    >>> fdtri(df1, df2, cdf_value)
+    3.000000000000006
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.1, 0.4, 0.7])
+    >>> fdtri(1, 2, x)
+    array([0.02020202, 0.38095238, 1.92156863])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [50, 10, 1, 50]
+    >>> dfd_parameters = [0.5, 1, 1, 5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtri_vals = fdtri(dfn, dfd, x)
+    ...     ax.plot(x, fdtri_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> title = "F distribution inverse cumulative distribution function"
+    >>> ax.set_title(title)
+    >>> ax.set_ylim(0, 30)
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtri`
+    directly can be much faster than calling the ``ppf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).ppf(x)=fdtri(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 0.7
+    >>> fdtri_res = fdtri(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).ppf(x)
+    >>> f_dist_res == fdtri_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtridfd",
+    """
+    fdtridfd(dfn, p, x, out=None)
+
+    Inverse to `fdtr` vs dfd
+
+    Finds the F density argument dfd such that ``fdtr(dfn, dfd, x) == p``.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    dfd : scalar or ndarray
+        `dfd` such that ``fdtr(dfn, dfd, x) == p``.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtrc : F distribution survival function
+    fdtri : F distribution quantile function
+    scipy.stats.f : F distribution
+
+    Examples
+    --------
+    Compute the F distribution cumulative distribution function for one
+    parameter set.
+
+    >>> from scipy.special import fdtridfd, fdtr
+    >>> dfn, dfd, x = 10, 5, 2
+    >>> cdf_value = fdtr(dfn, dfd, x)
+    >>> cdf_value
+    0.7700248806501017
+
+    Verify that `fdtridfd` recovers the original value for `dfd`:
+
+    >>> fdtridfd(dfn, cdf_value, x)
+    5.0
+    """)
+
+'''
+commented out as fdtridfn seems to have bugs and is not in functions.json
+see: https://github.com/scipy/scipy/pull/15622#discussion_r811440983
+
+add_newdoc(
+    "fdtridfn",
+    """
+    fdtridfn(p, dfd, x, out=None)
+
+    Inverse to `fdtr` vs dfn
+
+    finds the F density argument dfn such that ``fdtr(dfn, dfd, x) == p``.
+
+
+    Parameters
+    ----------
+    p : array_like
+        Cumulative probability, in [0, 1].
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    dfn : scalar or ndarray
+        `dfn` such that ``fdtr(dfn, dfd, x) == p``.
+
+    See Also
+    --------
+    fdtr, fdtrc, fdtri, fdtridfd
+
+
+    """)
+'''
+
+add_newdoc("gdtr",
+    r"""
+    gdtr(a, b, x, out=None)
+
+    Gamma distribution cumulative distribution function.
+
+    Returns the integral from zero to `x` of the gamma probability density
+    function,
+
+    .. math::
+
+        F = \int_0^x \frac{a^b}{\Gamma(b)} t^{b-1} e^{-at}\,dt,
+
+    where :math:`\Gamma` is the gamma function.
+
+    Parameters
+    ----------
+    a : array_like
+        The rate parameter of the gamma distribution, sometimes denoted
+        :math:`\beta` (float).  It is also the reciprocal of the scale
+        parameter :math:`\theta`.
+    b : array_like
+        The shape parameter of the gamma distribution, sometimes denoted
+        :math:`\alpha` (float).
+    x : array_like
+        The quantile (upper limit of integration; float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The CDF of the gamma distribution with parameters `a` and `b`
+        evaluated at `x`.
+
+    See Also
+    --------
+    gdtrc : 1 - CDF of the gamma distribution.
+    scipy.stats.gamma: Gamma distribution
+
+    Notes
+    -----
+    The evaluation is carried out using the relation to the incomplete gamma
+    integral (regularized gamma function).
+
+    Wrapper for the Cephes [1]_ routine `gdtr`. Calling `gdtr` directly can
+    improve performance compared to the ``cdf`` method of `scipy.stats.gamma`
+    (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``a=1``, ``b=2`` at ``x=5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import gdtr
+    >>> import matplotlib.pyplot as plt
+    >>> gdtr(1., 2., 5.)
+    0.9595723180054873
+
+    Compute the function for ``a=1`` and ``b=2`` at several points by
+    providing a NumPy array for `x`.
+
+    >>> xvalues = np.array([1., 2., 3., 4])
+    >>> gdtr(1., 1., xvalues)
+    array([0.63212056, 0.86466472, 0.95021293, 0.98168436])
+
+    `gdtr` can evaluate different parameter sets by providing arrays with
+    broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the
+    function for three different `a` at four positions `x` and ``b=3``,
+    resulting in a 3x4 array.
+
+    >>> a = np.array([[0.5], [1.5], [2.5]])
+    >>> x = np.array([1., 2., 3., 4])
+    >>> a.shape, x.shape
+    ((3, 1), (4,))
+
+    >>> gdtr(a, 3., x)
+    array([[0.01438768, 0.0803014 , 0.19115317, 0.32332358],
+           [0.19115317, 0.57680992, 0.82642193, 0.9380312 ],
+           [0.45618688, 0.87534798, 0.97974328, 0.9972306 ]])
+
+    Plot the function for four different parameter sets.
+
+    >>> a_parameters = [0.3, 1, 2, 6]
+    >>> b_parameters = [2, 10, 15, 20]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     a, b, style = parameter_set
+    ...     gdtr_vals = gdtr(a, b, x)
+    ...     ax.plot(x, gdtr_vals, label=fr"$a= {a},\, b={b}$", ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("Gamma distribution cumulative distribution function")
+    >>> plt.show()
+
+    The gamma distribution is also available as `scipy.stats.gamma`. Using
+    `gdtr` directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.gamma`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.gamma(b, scale=1/a).cdf(x)=gdtr(a, b, x)``.
+
+    >>> from scipy.stats import gamma
+    >>> a = 2.
+    >>> b = 3
+    >>> x = 1.
+    >>> gdtr_result = gdtr(a, b, x)  # this will often be faster than below
+    >>> gamma_dist_result = gamma(b, scale=1/a).cdf(x)
+    >>> gdtr_result == gamma_dist_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("gdtrc",
+    r"""
+    gdtrc(a, b, x, out=None)
+
+    Gamma distribution survival function.
+
+    Integral from `x` to infinity of the gamma probability density function,
+
+    .. math::
+
+        F = \int_x^\infty \frac{a^b}{\Gamma(b)} t^{b-1} e^{-at}\,dt,
+
+    where :math:`\Gamma` is the gamma function.
+
+    Parameters
+    ----------
+    a : array_like
+        The rate parameter of the gamma distribution, sometimes denoted
+        :math:`\beta` (float). It is also the reciprocal of the scale
+        parameter :math:`\theta`.
+    b : array_like
+        The shape parameter of the gamma distribution, sometimes denoted
+        :math:`\alpha` (float).
+    x : array_like
+        The quantile (lower limit of integration; float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The survival function of the gamma distribution with parameters `a`
+        and `b` evaluated at `x`.
+
+    See Also
+    --------
+    gdtr: Gamma distribution cumulative distribution function
+    scipy.stats.gamma: Gamma distribution
+    gdtrix
+
+    Notes
+    -----
+    The evaluation is carried out using the relation to the incomplete gamma
+    integral (regularized gamma function).
+
+    Wrapper for the Cephes [1]_ routine `gdtrc`. Calling `gdtrc` directly can
+    improve performance compared to the ``sf`` method of `scipy.stats.gamma`
+    (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``a=1`` and ``b=2`` at ``x=5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import gdtrc
+    >>> import matplotlib.pyplot as plt
+    >>> gdtrc(1., 2., 5.)
+    0.04042768199451279
+
+    Compute the function for ``a=1``, ``b=2`` at several points by providing
+    a NumPy array for `x`.
+
+    >>> xvalues = np.array([1., 2., 3., 4])
+    >>> gdtrc(1., 1., xvalues)
+    array([0.36787944, 0.13533528, 0.04978707, 0.01831564])
+
+    `gdtrc` can evaluate different parameter sets by providing arrays with
+    broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the
+    function for three different `a` at four positions `x` and ``b=3``,
+    resulting in a 3x4 array.
+
+    >>> a = np.array([[0.5], [1.5], [2.5]])
+    >>> x = np.array([1., 2., 3., 4])
+    >>> a.shape, x.shape
+    ((3, 1), (4,))
+
+    >>> gdtrc(a, 3., x)
+    array([[0.98561232, 0.9196986 , 0.80884683, 0.67667642],
+           [0.80884683, 0.42319008, 0.17357807, 0.0619688 ],
+           [0.54381312, 0.12465202, 0.02025672, 0.0027694 ]])
+
+    Plot the function for four different parameter sets.
+
+    >>> a_parameters = [0.3, 1, 2, 6]
+    >>> b_parameters = [2, 10, 15, 20]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     a, b, style = parameter_set
+    ...     gdtrc_vals = gdtrc(a, b, x)
+    ...     ax.plot(x, gdtrc_vals, label=fr"$a= {a},\, b={b}$", ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("Gamma distribution survival function")
+    >>> plt.show()
+
+    The gamma distribution is also available as `scipy.stats.gamma`.
+    Using `gdtrc` directly can be much faster than calling the ``sf`` method
+    of `scipy.stats.gamma`, especially for small arrays or individual
+    values. To get the same results one must use the following parametrization:
+    ``stats.gamma(b, scale=1/a).sf(x)=gdtrc(a, b, x)``.
+
+    >>> from scipy.stats import gamma
+    >>> a = 2
+    >>> b = 3
+    >>> x = 1.
+    >>> gdtrc_result = gdtrc(a, b, x)  # this will often be faster than below
+    >>> gamma_dist_result = gamma(b, scale=1/a).sf(x)
+    >>> gdtrc_result == gamma_dist_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("gdtria",
+    """
+    gdtria(p, b, x, out=None)
+
+    Inverse of `gdtr` vs a.
+
+    Returns the inverse with respect to the parameter `a` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability values.
+    b : array_like
+        `b` parameter values of `gdtr(a, b, x)`. `b` is the "shape" parameter
+        of the gamma distribution.
+    x : array_like
+        Nonnegative real values, from the domain of the gamma distribution.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`.  `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    a : scalar or ndarray
+        Values of the `a` parameter such that ``p = gdtr(a, b, x)`.  ``1/a``
+        is the "scale" parameter of the gamma distribution.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtrib : Inverse with respect to `b` of `gdtr(a, b, x)`.
+    gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `a` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `a`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Computation of the incomplete gamma function ratios and their
+           inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtria
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtria(p, 3.4, 5.6)
+    1.2
+    """)
+
+add_newdoc("gdtrib",
+    """
+    gdtrib(a, p, x, out=None)
+
+    Inverse of `gdtr` vs b.
+
+    Returns the inverse with respect to the parameter `b` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        `a` parameter values of ``gdtr(a, b, x)`. ``1/a`` is the "scale"
+        parameter of the gamma distribution.
+    p : array_like
+        Probability values.
+    x : array_like
+        Nonnegative real values, from the domain of the gamma distribution.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`.  `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    b : scalar or ndarray
+        Values of the `b` parameter such that `p = gdtr(a, b, x)`.  `b` is
+        the "shape" parameter of the gamma distribution.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtria : Inverse with respect to `a` of `gdtr(a, b, x)`.
+    gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.
+
+    Notes
+    -----
+
+    The cumulative distribution function `p` is computed using the Cephes [1]_
+    routines `igam` and `igamc`. Computation of `b` involves a search for a value
+    that produces the desired value of `p` using Chandrupatla's bracketing
+    root finding algorithm [2]_.
+
+    Note that there are some edge cases where `gdtrib` is extended by taking
+    limits where they are uniquely defined. In particular
+    ``x == 0`` with ``p > 0`` and ``p == 0`` with ``x > 0``.
+    For these edge cases, a numerical result will be returned for
+    ``gdtrib(a, p, x)`` even though ``gdtr(a, gdtrib(a, p, x), x)`` is
+    undefined.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [2] Chandrupatla, Tirupathi R.
+           "A new hybrid quadratic/bisection algorithm for finding the zero of a
+           nonlinear function without using derivatives".
+           Advances in Engineering Software, 28(3), 145-149.
+           https://doi.org/10.1016/s0965-9978(96)00051-8
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtrib
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtrib(1.2, p, 5.6)
+    3.3999999999999995
+    """)
+
+add_newdoc("gdtrix",
+    """
+    gdtrix(a, b, p, out=None)
+
+    Inverse of `gdtr` vs x.
+
+    Returns the inverse with respect to the parameter `x` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution. This is also known as the pth quantile of the
+    distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        `a` parameter values of ``gdtr(a, b, x)``. ``1/a`` is the "scale"
+        parameter of the gamma distribution.
+    b : array_like
+        `b` parameter values of ``gdtr(a, b, x)``. `b` is the "shape" parameter
+        of the gamma distribution.
+    p : array_like
+        Probability values.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`. `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Values of the `x` parameter such that `p = gdtr(a, b, x)`.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.
+    gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `x` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `x`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Computation of the incomplete gamma function ratios and their
+           inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtrix
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtrix(1.2, 3.4, p)
+    5.5999999999999996
+    """)
+
+add_newdoc("hankel1",
+    r"""
+    hankel1(v, z, out=None)
+
+    Hankel function of the first kind
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Hankel function of the first kind.
+
+    See Also
+    --------
+    hankel1e : ndarray
+        This function with leading exponential behavior stripped off.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(1)}_v(z) =
+              \frac{2}{\imath\pi} \exp(-\imath \pi v/2) K_v(z \exp(-\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(1)}_{-v}(z) = H^{(1)}_v(z) \exp(\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel1e",
+    r"""
+    hankel1e(v, z, out=None)
+
+    Exponentially scaled Hankel function of the first kind
+
+    Defined as::
+
+        hankel1e(v, z) = hankel1(v, z) * exp(-1j * z)
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled Hankel function.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(1)}_v(z) =
+              \frac{2}{\imath\pi} \exp(-\imath \pi v/2) K_v(z \exp(-\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(1)}_{-v}(z) = H^{(1)}_v(z) \exp(\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel2",
+    r"""
+    hankel2(v, z, out=None)
+
+    Hankel function of the second kind
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Hankel function of the second kind.
+
+    See Also
+    --------
+    hankel2e : this function with leading exponential behavior stripped off.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(2)}_v(z) =
+              -\frac{2}{\imath\pi} \exp(\imath \pi v/2) K_v(z \exp(\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(2)}_{-v}(z) = H^{(2)}_v(z) \exp(-\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel2e",
+    r"""
+    hankel2e(v, z, out=None)
+
+    Exponentially scaled Hankel function of the second kind
+
+    Defined as::
+
+        hankel2e(v, z) = hankel2(v, z) * exp(1j * z)
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled Hankel function of the second kind.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(2)}_v(z) = -\frac{2}{\imath\pi}
+              \exp(\frac{\imath \pi v}{2}) K_v(z exp(\frac{\imath\pi}{2}))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(2)}_{-v}(z) = H^{(2)}_v(z) \exp(-\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    """)
+
+add_newdoc("huber",
+    r"""
+    huber(delta, r, out=None)
+
+    Huber loss function.
+
+    .. math:: \text{huber}(\delta, r) = \begin{cases} \infty & \delta < 0  \\
+              \frac{1}{2}r^2 & 0 \le \delta, | r | \le \delta \\
+              \delta ( |r| - \frac{1}{2}\delta ) & \text{otherwise} \end{cases}
+
+    Parameters
+    ----------
+    delta : ndarray
+        Input array, indicating the quadratic vs. linear loss changepoint.
+    r : ndarray
+        Input array, possibly representing residuals.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The computed Huber loss function values.
+
+    See Also
+    --------
+    pseudo_huber : smooth approximation of this function
+
+    Notes
+    -----
+    `huber` is useful as a loss function in robust statistics or machine
+    learning to reduce the influence of outliers as compared to the common
+    squared error loss, residuals with a magnitude higher than `delta` are
+    not squared [1]_.
+
+    Typically, `r` represents residuals, the difference
+    between a model prediction and data. Then, for :math:`|r|\leq\delta`,
+    `huber` resembles the squared error and for :math:`|r|>\delta` the
+    absolute error. This way, the Huber loss often achieves
+    a fast convergence in model fitting for small residuals like the squared
+    error loss function and still reduces the influence of outliers
+    (:math:`|r|>\delta`) like the absolute error loss. As :math:`\delta` is
+    the cutoff between squared and absolute error regimes, it has
+    to be tuned carefully for each problem. `huber` is also
+    convex, making it suitable for gradient based optimization.
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Peter Huber. "Robust Estimation of a Location Parameter",
+           1964. Annals of Statistics. 53 (1): 73 - 101.
+
+    Examples
+    --------
+    Import all necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.special import huber
+    >>> import matplotlib.pyplot as plt
+
+    Compute the function for ``delta=1`` at ``r=2``
+
+    >>> huber(1., 2.)
+    1.5
+
+    Compute the function for different `delta` by providing a NumPy array or
+    list for `delta`.
+
+    >>> huber([1., 3., 5.], 4.)
+    array([3.5, 7.5, 8. ])
+
+    Compute the function at different points by providing a NumPy array or
+    list for `r`.
+
+    >>> huber(2., np.array([1., 1.5, 3.]))
+    array([0.5  , 1.125, 4.   ])
+
+    The function can be calculated for different `delta` and `r` by
+    providing arrays for both with compatible shapes for broadcasting.
+
+    >>> r = np.array([1., 2.5, 8., 10.])
+    >>> deltas = np.array([[1.], [5.], [9.]])
+    >>> print(r.shape, deltas.shape)
+    (4,) (3, 1)
+
+    >>> huber(deltas, r)
+    array([[ 0.5  ,  2.   ,  7.5  ,  9.5  ],
+           [ 0.5  ,  3.125, 27.5  , 37.5  ],
+           [ 0.5  ,  3.125, 32.   , 49.5  ]])
+
+    Plot the function for different `delta`.
+
+    >>> x = np.linspace(-4, 4, 500)
+    >>> deltas = [1, 2, 3]
+    >>> linestyles = ["dashed", "dotted", "dashdot"]
+    >>> fig, ax = plt.subplots()
+    >>> combined_plot_parameters = list(zip(deltas, linestyles))
+    >>> for delta, style in combined_plot_parameters:
+    ...     ax.plot(x, huber(delta, x), label=fr"$\delta={delta}$", ls=style)
+    >>> ax.legend(loc="upper center")
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title(r"Huber loss function $h_{\delta}(x)$")
+    >>> ax.set_xlim(-4, 4)
+    >>> ax.set_ylim(0, 8)
+    >>> plt.show()
+    """)
+
+add_newdoc("hyp0f1",
+    r"""
+    hyp0f1(v, z, out=None)
+
+    Confluent hypergeometric limit function 0F1.
+
+    Parameters
+    ----------
+    v : array_like
+        Real-valued parameter
+    z : array_like
+        Real- or complex-valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The confluent hypergeometric limit function
+
+    Notes
+    -----
+    This function is defined as:
+
+    .. math:: _0F_1(v, z) = \sum_{k=0}^{\infty}\frac{z^k}{(v)_k k!}.
+
+    It's also the limit as :math:`q \to \infty` of :math:`_1F_1(q; v; z/q)`,
+    and satisfies the differential equation :math:`f''(z) + vf'(z) =
+    f(z)`. See [1]_ for more information.
+
+    References
+    ----------
+    .. [1] Wolfram MathWorld, "Confluent Hypergeometric Limit Function",
+           http://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is one when `z` is zero.
+
+    >>> sc.hyp0f1(1, 0)
+    1.0
+
+    It is the limit of the confluent hypergeometric function as `q`
+    goes to infinity.
+
+    >>> q = np.array([1, 10, 100, 1000])
+    >>> v = 1
+    >>> z = 1
+    >>> sc.hyp1f1(q, v, z / q)
+    array([2.71828183, 2.31481985, 2.28303778, 2.27992985])
+    >>> sc.hyp0f1(v, z)
+    2.2795853023360673
+
+    It is related to Bessel functions.
+
+    >>> n = 1
+    >>> x = np.linspace(0, 1, 5)
+    >>> sc.jv(n, x)
+    array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])
+    >>> (0.5 * x)**n / sc.factorial(n) * sc.hyp0f1(n + 1, -0.25 * x**2)
+    array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])
+
+    """)
+
+add_newdoc("hyp1f1",
+    r"""
+    hyp1f1(a, b, x, out=None)
+
+    Confluent hypergeometric function 1F1.
+
+    The confluent hypergeometric function is defined by the series
+
+    .. math::
+
+       {}_1F_1(a; b; x) = \sum_{k = 0}^\infty \frac{(a)_k}{(b)_k k!} x^k.
+
+    See [dlmf]_ for more details. Here :math:`(\cdot)_k` is the
+    Pochhammer symbol; see `poch`.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real parameters
+    x : array_like
+        Real or complex argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the confluent hypergeometric function
+
+    See Also
+    --------
+    hyperu : another confluent hypergeometric function
+    hyp0f1 : confluent hypergeometric limit function
+    hyp2f1 : Gaussian hypergeometric function
+
+    Notes
+    -----
+    For real values, this function uses the ``hyp1f1`` routine from the C++ Boost
+    library [2]_, for complex values a C translation of the specfun
+    Fortran library [3]_.
+
+    References
+    ----------
+    .. [dlmf] NIST Digital Library of Mathematical Functions
+              https://dlmf.nist.gov/13.2#E2
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+    .. [3] Zhang, Jin, "Computation of Special Functions", John Wiley
+           and Sons, Inc, 1996.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is one when `x` is zero:
+
+    >>> sc.hyp1f1(0.5, 0.5, 0)
+    1.0
+
+    It is singular when `b` is a nonpositive integer.
+
+    >>> sc.hyp1f1(0.5, -1, 0)
+    inf
+
+    It is a polynomial when `a` is a nonpositive integer.
+
+    >>> a, b, x = -1, 0.5, np.array([1.0, 2.0, 3.0, 4.0])
+    >>> sc.hyp1f1(a, b, x)
+    array([-1., -3., -5., -7.])
+    >>> 1 + (a / b) * x
+    array([-1., -3., -5., -7.])
+
+    It reduces to the exponential function when ``a = b``.
+
+    >>> sc.hyp1f1(2, 2, [1, 2, 3, 4])
+    array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])
+    >>> np.exp([1, 2, 3, 4])
+    array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])
+
+    """)
+
+add_newdoc("hyperu",
+    r"""
+    hyperu(a, b, x, out=None)
+
+    Confluent hypergeometric function U
+
+    It is defined as the solution to the equation
+
+    .. math::
+
+       x \frac{d^2w}{dx^2} + (b - x) \frac{dw}{dx} - aw = 0
+
+    which satisfies the property
+
+    .. math::
+
+       U(a, b, x) \sim x^{-a}
+
+    as :math:`x \to \infty`. See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real-valued parameters
+    x : array_like
+        Real-valued argument
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of `U`
+
+    References
+    ----------
+    .. [dlmf] NIST Digital Library of Mathematics Functions
+              https://dlmf.nist.gov/13.2#E6
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It has a branch cut along the negative `x` axis.
+
+    >>> x = np.linspace(-0.1, -10, 5)
+    >>> sc.hyperu(1, 1, x)
+    array([nan, nan, nan, nan, nan])
+
+    It approaches zero as `x` goes to infinity.
+
+    >>> x = np.array([1, 10, 100])
+    >>> sc.hyperu(1, 1, x)
+    array([0.59634736, 0.09156333, 0.00990194])
+
+    It satisfies Kummer's transformation.
+
+    >>> a, b, x = 2, 1, 1
+    >>> sc.hyperu(a, b, x)
+    0.1926947246463881
+    >>> x**(1 - b) * sc.hyperu(a - b + 1, 2 - b, x)
+    0.1926947246463881
+
+    """)
+
+add_newdoc("_igam_fac",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("iv",
+    r"""
+    iv(v, z, out=None)
+
+    Modified Bessel function of the first kind of real order.
+
+    Parameters
+    ----------
+    v : array_like
+        Order. If `z` is of real type and negative, `v` must be integer
+        valued.
+    z : array_like of float or complex
+        Argument.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the modified Bessel function.
+
+    See Also
+    --------
+    ive : This function with leading exponential behavior stripped off.
+    i0 : Faster version of this function for order 0.
+    i1 : Faster version of this function for order 1.
+
+    Notes
+    -----
+    For real `z` and :math:`v \in [-50, 50]`, the evaluation is carried out
+    using Temme's method [1]_.  For larger orders, uniform asymptotic
+    expansions are applied.
+
+    For complex `z` and positive `v`, the AMOS [2]_ `zbesi` routine is
+    called. It uses a power series for small `z`, the asymptotic expansion
+    for large `abs(z)`, the Miller algorithm normalized by the Wronskian
+    and a Neumann series for intermediate magnitudes, and the uniform
+    asymptotic expansions for :math:`I_v(z)` and :math:`J_v(z)` for large
+    orders. Backward recurrence is used to generate sequences or reduce
+    orders when necessary.
+
+    The calculations above are done in the right half plane and continued
+    into the left half plane by the formula,
+
+    .. math:: I_v(z \exp(\pm\imath\pi)) = \exp(\pm\pi v) I_v(z)
+
+    (valid when the real part of `z` is positive).  For negative `v`, the
+    formula
+
+    .. math:: I_{-v}(z) = I_v(z) + \frac{2}{\pi} \sin(\pi v) K_v(z)
+
+    is used, where :math:`K_v(z)` is the modified Bessel function of the
+    second kind, evaluated using the AMOS routine `zbesk`.
+
+    References
+    ----------
+    .. [1] Temme, Journal of Computational Physics, vol 21, 343 (1976)
+    .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import iv
+    >>> iv(0, 1.)
+    1.2660658777520084
+
+    Evaluate the function at one point for different orders.
+
+    >>> iv(0, 1.), iv(1, 1.), iv(1.5, 1.)
+    (1.2660658777520084, 0.565159103992485, 0.2935253263474798)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> iv([0, 1, 1.5], 1.)
+    array([1.26606588, 0.5651591 , 0.29352533])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([-2., 0., 3.])
+    >>> iv(0, points)
+    array([2.2795853 , 1.        , 4.88079259])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> iv(orders, points)
+    array([[ 2.2795853 ,  1.        ,  4.88079259],
+           [-1.59063685,  0.        ,  3.95337022]])
+
+    Plot the functions of order 0 to 3 from -5 to 5.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-5., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, iv(i, x), label=f'$I_{i!r}$')
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("ive",
+    r"""
+    ive(v, z, out=None)
+
+    Exponentially scaled modified Bessel function of the first kind.
+
+    Defined as::
+
+        ive(v, z) = iv(v, z) * exp(-abs(z.real))
+
+    For imaginary numbers without a real part, returns the unscaled
+    Bessel function of the first kind `iv`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order.
+    z : array_like of float or complex
+        Argument.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled modified Bessel function.
+
+    See Also
+    --------
+    iv: Modified Bessel function of the first kind
+    i0e: Faster implementation of this function for order 0
+    i1e: Faster implementation of this function for order 1
+
+    Notes
+    -----
+    For positive `v`, the AMOS [1]_ `zbesi` routine is called. It uses a
+    power series for small `z`, the asymptotic expansion for large
+    `abs(z)`, the Miller algorithm normalized by the Wronskian and a
+    Neumann series for intermediate magnitudes, and the uniform asymptotic
+    expansions for :math:`I_v(z)` and :math:`J_v(z)` for large orders.
+    Backward recurrence is used to generate sequences or reduce orders when
+    necessary.
+
+    The calculations above are done in the right half plane and continued
+    into the left half plane by the formula,
+
+    .. math:: I_v(z \exp(\pm\imath\pi)) = \exp(\pm\pi v) I_v(z)
+
+    (valid when the real part of `z` is positive).  For negative `v`, the
+    formula
+
+    .. math:: I_{-v}(z) = I_v(z) + \frac{2}{\pi} \sin(\pi v) K_v(z)
+
+    is used, where :math:`K_v(z)` is the modified Bessel function of the
+    second kind, evaluated using the AMOS routine `zbesk`.
+
+    `ive` is useful for large arguments `z`: for these, `iv` easily overflows,
+    while `ive` does not due to the exponential scaling.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    In the following example `iv` returns infinity whereas `ive` still returns
+    a finite number.
+
+    >>> from scipy.special import iv, ive
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> iv(3, 1000.), ive(3, 1000.)
+    (inf, 0.01256056218254712)
+
+    Evaluate the function at one point for different orders by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> ive([0, 1, 1.5], 1.)
+    array([0.46575961, 0.20791042, 0.10798193])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> points = np.array([-2., 0., 3.])
+    >>> ive(0, points)
+    array([0.30850832, 1.        , 0.24300035])
+
+    Evaluate the function at several points for different orders by
+    providing arrays for both `v` for `z`. Both arrays have to be
+    broadcastable to the correct shape. To calculate the orders 0, 1
+    and 2 for a 1D array of points:
+
+    >>> ive([[0], [1], [2]], points)
+    array([[ 0.30850832,  1.        ,  0.24300035],
+           [-0.21526929,  0.        ,  0.19682671],
+           [ 0.09323903,  0.        ,  0.11178255]])
+
+    Plot the functions of order 0 to 3 from -5 to 5.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-5., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, ive(i, x), label=fr'$I_{i!r}(z)\cdot e^{{-|z|}}$')
+    >>> ax.legend()
+    >>> ax.set_xlabel(r"$z$")
+    >>> plt.show()
+    """)
+
+add_newdoc("jn",
+    """
+    jn(n, x, out=None)
+
+    Bessel function of the first kind of integer order and real argument.
+
+    Parameters
+    ----------
+    n : array_like
+        order of the Bessel function
+    x : array_like
+        argument of the Bessel function
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the bessel function
+
+    See Also
+    --------
+    jv
+    spherical_jn : spherical Bessel functions.
+
+    Notes
+    -----
+    `jn` is an alias of `jv`.
+    Not to be confused with the spherical Bessel functions (see
+    `spherical_jn`).
+
+    """)
+
+add_newdoc("jv",
+    r"""
+    jv(v, z, out=None)
+
+    Bessel function of the first kind of real order and complex argument.
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    J : scalar or ndarray
+        Value of the Bessel function, :math:`J_v(z)`.
+
+    See Also
+    --------
+    jve : :math:`J_v` with leading exponential behavior stripped off.
+    spherical_jn : spherical Bessel functions.
+    j0 : faster version of this function for order 0.
+    j1 : faster version of this function for order 1.
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the AMOS
+    [1]_ `zbesj` routine, which exploits the connection to the modified
+    Bessel function :math:`I_v`,
+
+    .. math::
+        J_v(z) = \exp(v\pi\imath/2) I_v(-\imath z)\qquad (\Im z > 0)
+
+        J_v(z) = \exp(-v\pi\imath/2) I_v(\imath z)\qquad (\Im z < 0)
+
+    For negative `v` values the formula,
+
+    .. math:: J_{-v}(z) = J_v(z) \cos(\pi v) - Y_v(z) \sin(\pi v)
+
+    is used, where :math:`Y_v(z)` is the Bessel function of the second
+    kind, computed using the AMOS routine `zbesy`.  Note that the second
+    term is exactly zero for integer `v`; to improve accuracy the second
+    term is explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Not to be confused with the spherical Bessel functions (see `spherical_jn`).
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import jv
+    >>> jv(0, 1.)
+    0.7651976865579666
+
+    Evaluate the function at one point for different orders.
+
+    >>> jv(0, 1.), jv(1, 1.), jv(1.5, 1.)
+    (0.7651976865579666, 0.44005058574493355, 0.24029783912342725)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> jv([0, 1, 1.5], 1.)
+    array([0.76519769, 0.44005059, 0.24029784])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([-2., 0., 3.])
+    >>> jv(0, points)
+    array([ 0.22389078,  1.        , -0.26005195])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> jv(orders, points)
+    array([[ 0.22389078,  1.        , -0.26005195],
+           [-0.57672481,  0.        ,  0.33905896]])
+
+    Plot the functions of order 0 to 3 from -10 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-10., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, jv(i, x), label=f'$J_{i!r}$')
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("jve",
+    r"""
+    jve(v, z, out=None)
+
+    Exponentially scaled Bessel function of the first kind of order `v`.
+
+    Defined as::
+
+        jve(v, z) = jv(v, z) * exp(-abs(z.imag))
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    J : scalar or ndarray
+        Value of the exponentially scaled Bessel function.
+
+    See Also
+    --------
+    jv: Unscaled Bessel function of the first kind
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the AMOS
+    [1]_ `zbesj` routine, which exploits the connection to the modified
+    Bessel function :math:`I_v`,
+
+    .. math::
+        J_v(z) = \exp(v\pi\imath/2) I_v(-\imath z)\qquad (\Im z > 0)
+
+        J_v(z) = \exp(-v\pi\imath/2) I_v(\imath z)\qquad (\Im z < 0)
+
+    For negative `v` values the formula,
+
+    .. math:: J_{-v}(z) = J_v(z) \cos(\pi v) - Y_v(z) \sin(\pi v)
+
+    is used, where :math:`Y_v(z)` is the Bessel function of the second
+    kind, computed using the AMOS routine `zbesy`.  Note that the second
+    term is exactly zero for integer `v`; to improve accuracy the second
+    term is explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Exponentially scaled Bessel functions are useful for large arguments `z`:
+    for these, the unscaled Bessel functions can easily under-or overflow.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compare the output of `jv` and `jve` for large complex arguments for `z`
+    by computing their values for order ``v=1`` at ``z=1000j``. We see that
+    `jv` overflows but `jve` returns a finite number:
+
+    >>> import numpy as np
+    >>> from scipy.special import jv, jve
+    >>> v = 1
+    >>> z = 1000j
+    >>> jv(v, z), jve(v, z)
+    ((inf+infj), (7.721967686709077e-19+0.012610930256928629j))
+
+    For real arguments for `z`, `jve` returns the same as `jv`.
+
+    >>> v, z = 1, 1000
+    >>> jv(v, z), jve(v, z)
+    (0.004728311907089523, 0.004728311907089523)
+
+    The function can be evaluated for several orders at the same time by
+    providing a list or NumPy array for `v`:
+
+    >>> jve([1, 3, 5], 1j)
+    array([1.27304208e-17+2.07910415e-01j, -4.99352086e-19-8.15530777e-03j,
+           6.11480940e-21+9.98657141e-05j])
+
+    In the same way, the function can be evaluated at several points in one
+    call by providing a list or NumPy array for `z`:
+
+    >>> jve(1, np.array([1j, 2j, 3j]))
+    array([1.27308412e-17+0.20791042j, 1.31814423e-17+0.21526929j,
+           1.20521602e-17+0.19682671j])
+
+    It is also possible to evaluate several orders at several points
+    at the same time by providing arrays for `v` and `z` with
+    compatible shapes for broadcasting. Compute `jve` for two different orders
+    `v` and three points `z` resulting in a 2x3 array.
+
+    >>> v = np.array([[1], [3]])
+    >>> z = np.array([1j, 2j, 3j])
+    >>> v.shape, z.shape
+    ((2, 1), (3,))
+
+    >>> jve(v, z)
+    array([[1.27304208e-17+0.20791042j,  1.31810070e-17+0.21526929j,
+            1.20517622e-17+0.19682671j],
+           [-4.99352086e-19-0.00815531j, -1.76289571e-18-0.02879122j,
+            -2.92578784e-18-0.04778332j]])
+    """)
+
+add_newdoc("kelvin",
+    """
+    kelvin(x, out=None)
+
+    Kelvin functions as complex numbers
+
+    Parameters
+    ----------
+    x : array_like
+        Argument
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    Be, Ke, Bep, Kep : 4-tuple of scalar or ndarray
+        The tuple (Be, Ke, Bep, Kep) contains complex numbers
+        representing the real and imaginary Kelvin functions and their
+        derivatives evaluated at `x`.  For example, kelvin(x)[0].real =
+        ber x and kelvin(x)[0].imag = bei x with similar relationships
+        for ker and kei.
+    """)
+
+add_newdoc("ker",
+    r"""
+    ker(x, out=None)
+
+    Kelvin function ker.
+
+    Defined as
+
+    .. math::
+
+        \mathrm{ker}(x) = \Re[K_0(x e^{\pi i / 4})]
+
+    Where :math:`K_0` is the modified Bessel function of the second
+    kind (see `kv`). See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Kelvin function.
+
+    See Also
+    --------
+    kei : the corresponding imaginary part
+    kerp : the derivative of ker
+    kv : modified Bessel function of the second kind
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/10.61
+
+    Examples
+    --------
+    It can be expressed using the modified Bessel function of the
+    second kind.
+
+    >>> import numpy as np
+    >>> import scipy.special as sc
+    >>> x = np.array([1.0, 2.0, 3.0, 4.0])
+    >>> sc.kv(0, x * np.exp(np.pi * 1j / 4)).real
+    array([ 0.28670621, -0.04166451, -0.06702923, -0.03617885])
+    >>> sc.ker(x)
+    array([ 0.28670621, -0.04166451, -0.06702923, -0.03617885])
+
+    """)
+
+add_newdoc("kerp",
+    r"""
+    kerp(x, out=None)
+
+    Derivative of the Kelvin function ker.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of ker.
+
+    See Also
+    --------
+    ker
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/10#PT5
+
+    """)
+
+add_newdoc("kl_div",
+    r"""
+    kl_div(x, y, out=None)
+
+    Elementwise function for computing Kullback-Leibler divergence.
+
+    .. math::
+
+        \mathrm{kl\_div}(x, y) =
+          \begin{cases}
+            x \log(x / y) - x + y & x > 0, y > 0 \\
+            y & x = 0, y \ge 0 \\
+            \infty & \text{otherwise}
+          \end{cases}
+
+    Parameters
+    ----------
+    x, y : array_like
+        Real arguments
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Kullback-Liebler divergence.
+
+    See Also
+    --------
+    entr, rel_entr, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is non-negative and is jointly convex in `x` and `y`.
+
+    The origin of this function is in convex programming; see [1]_ for
+    details. This is why the function contains the extra :math:`-x
+    + y` terms over what might be expected from the Kullback-Leibler
+    divergence. For a version of the function without the extra terms,
+    see `rel_entr`.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+
+    """)
+
+add_newdoc("kn",
+    r"""
+    kn(n, x, out=None)
+
+    Modified Bessel function of the second kind of integer order `n`
+
+    Returns the modified Bessel function of the second kind for integer order
+    `n` at real `z`.
+
+    These are also sometimes called functions of the third kind, Basset
+    functions, or Macdonald functions.
+
+    Parameters
+    ----------
+    n : array_like of int
+        Order of Bessel functions (floats will truncate with a warning)
+    x : array_like of float
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Modified Bessel function of the second kind,
+        :math:`K_n(x)`.
+
+    See Also
+    --------
+    kv : Same function, but accepts real order and complex argument
+    kvp : Derivative of this function
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+
+    Examples
+    --------
+    Plot the function of several orders for real input:
+
+    >>> import numpy as np
+    >>> from scipy.special import kn
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> for N in range(6):
+    ...     plt.plot(x, kn(N, x), label='$K_{}(x)$'.format(N))
+    >>> plt.ylim(0, 10)
+    >>> plt.legend()
+    >>> plt.title(r'Modified Bessel function of the second kind $K_n(x)$')
+    >>> plt.show()
+
+    Calculate for a single value at multiple orders:
+
+    >>> kn([4, 5, 6], 1)
+    array([   44.23241585,   360.9605896 ,  3653.83831186])
+    """)
+
+add_newdoc("kolmogi",
+    """
+    kolmogi(p, out=None)
+
+    Inverse Survival Function of Kolmogorov distribution
+
+    It is the inverse function to `kolmogorov`.
+    Returns y such that ``kolmogorov(y) == p``.
+
+    Parameters
+    ----------
+    p : float array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of kolmogi(p)
+
+    See Also
+    --------
+    kolmogorov : The Survival Function for the distribution
+    scipy.stats.kstwobign : Provides the functionality as a continuous distribution
+    smirnov, smirnovi : Functions for the one-sided distribution
+
+    Notes
+    -----
+    `kolmogorov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.kstwobign` distribution.
+
+    Examples
+    --------
+    >>> from scipy.special import kolmogi
+    >>> kolmogi([0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0])
+    array([        inf,  1.22384787,  1.01918472,  0.82757356,  0.67644769,
+            0.57117327,  0.        ])
+
+    """)
+
+add_newdoc("kolmogorov",
+    r"""
+    kolmogorov(y, out=None)
+
+    Complementary cumulative distribution (Survival Function) function of
+    Kolmogorov distribution.
+
+    Returns the complementary cumulative distribution function of
+    Kolmogorov's limiting distribution (``D_n*\sqrt(n)`` as n goes to infinity)
+    of a two-sided test for equality between an empirical and a theoretical
+    distribution. It is equal to the (limit as n->infinity of the)
+    probability that ``sqrt(n) * max absolute deviation > y``.
+
+    Parameters
+    ----------
+    y : float array_like
+      Absolute deviation between the Empirical CDF (ECDF) and the target CDF,
+      multiplied by sqrt(n).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of kolmogorov(y)
+
+    See Also
+    --------
+    kolmogi : The Inverse Survival Function for the distribution
+    scipy.stats.kstwobign : Provides the functionality as a continuous distribution
+    smirnov, smirnovi : Functions for the one-sided distribution
+
+    Notes
+    -----
+    `kolmogorov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.kstwobign` distribution.
+
+    Examples
+    --------
+    Show the probability of a gap at least as big as 0, 0.5 and 1.0.
+
+    >>> import numpy as np
+    >>> from scipy.special import kolmogorov
+    >>> from scipy.stats import kstwobign
+    >>> kolmogorov([0, 0.5, 1.0])
+    array([ 1.        ,  0.96394524,  0.26999967])
+
+    Compare a sample of size 1000 drawn from a Laplace(0, 1) distribution against
+    the target distribution, a Normal(0, 1) distribution.
+
+    >>> from scipy.stats import norm, laplace
+    >>> rng = np.random.default_rng()
+    >>> n = 1000
+    >>> lap01 = laplace(0, 1)
+    >>> x = np.sort(lap01.rvs(n, random_state=rng))
+    >>> np.mean(x), np.std(x)
+    (-0.05841730131499543, 1.3968109101997568)
+
+    Construct the Empirical CDF and the K-S statistic Dn.
+
+    >>> target = norm(0,1)  # Normal mean 0, stddev 1
+    >>> cdfs = target.cdf(x)
+    >>> ecdfs = np.arange(n+1, dtype=float)/n
+    >>> gaps = np.column_stack([cdfs - ecdfs[:n], ecdfs[1:] - cdfs])
+    >>> Dn = np.max(gaps)
+    >>> Kn = np.sqrt(n) * Dn
+    >>> print('Dn=%f, sqrt(n)*Dn=%f' % (Dn, Kn))
+    Dn=0.043363, sqrt(n)*Dn=1.371265
+    >>> print(chr(10).join(['For a sample of size n drawn from a N(0, 1) distribution:',
+    ...   ' the approximate Kolmogorov probability that sqrt(n)*Dn>=%f is %f' %
+    ...    (Kn, kolmogorov(Kn)),
+    ...   ' the approximate Kolmogorov probability that sqrt(n)*Dn<=%f is %f' %
+    ...    (Kn, kstwobign.cdf(Kn))]))
+    For a sample of size n drawn from a N(0, 1) distribution:
+     the approximate Kolmogorov probability that sqrt(n)*Dn>=1.371265 is 0.046533
+     the approximate Kolmogorov probability that sqrt(n)*Dn<=1.371265 is 0.953467
+
+    Plot the Empirical CDF against the target N(0, 1) CDF.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.step(np.concatenate([[-3], x]), ecdfs, where='post', label='Empirical CDF')
+    >>> x3 = np.linspace(-3, 3, 100)
+    >>> plt.plot(x3, target.cdf(x3), label='CDF for N(0, 1)')
+    >>> plt.ylim([0, 1]); plt.grid(True); plt.legend();
+    >>> # Add vertical lines marking Dn+ and Dn-
+    >>> iminus, iplus = np.argmax(gaps, axis=0)
+    >>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus],
+    ...            color='r', linestyle='dashed', lw=4)
+    >>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1],
+    ...            color='r', linestyle='dashed', lw=4)
+    >>> plt.show()
+    """)
+
+add_newdoc("_kolmogc",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("_kolmogci",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("_kolmogp",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("kv",
+    r"""
+    kv(v, z, out=None)
+
+    Modified Bessel function of the second kind of real order `v`
+
+    Returns the modified Bessel function of the second kind for real order
+    `v` at complex `z`.
+
+    These are also sometimes called functions of the third kind, Basset
+    functions, or Macdonald functions.  They are defined as those solutions
+    of the modified Bessel equation for which,
+
+    .. math::
+        K_v(x) \sim \sqrt{\pi/(2x)} \exp(-x)
+
+    as :math:`x \to \infty` [3]_.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel functions
+    z : array_like of complex
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The results. Note that input must be of complex type to get complex
+        output, e.g. ``kv(3, -2+0j)`` instead of ``kv(3, -2)``.
+
+    See Also
+    --------
+    kve : This function with leading exponential behavior stripped off.
+    kvp : Derivative of this function
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+    .. [3] NIST Digital Library of Mathematical Functions,
+           Eq. 10.25.E3. https://dlmf.nist.gov/10.25.E3
+
+    Examples
+    --------
+    Plot the function of several orders for real input:
+
+    >>> import numpy as np
+    >>> from scipy.special import kv
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> for N in np.linspace(0, 6, 5):
+    ...     plt.plot(x, kv(N, x), label='$K_{{{}}}(x)$'.format(N))
+    >>> plt.ylim(0, 10)
+    >>> plt.legend()
+    >>> plt.title(r'Modified Bessel function of the second kind $K_\nu(x)$')
+    >>> plt.show()
+
+    Calculate for a single value at multiple orders:
+
+    >>> kv([4, 4.5, 5], 1+2j)
+    array([ 0.1992+2.3892j,  2.3493+3.6j   ,  7.2827+3.8104j])
+
+    """)
+
+add_newdoc("kve",
+    r"""
+    kve(v, z, out=None)
+
+    Exponentially scaled modified Bessel function of the second kind.
+
+    Returns the exponentially scaled, modified Bessel function of the
+    second kind (sometimes called the third kind) for real order `v` at
+    complex `z`::
+
+        kve(v, z) = kv(v, z) * exp(z)
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel functions
+    z : array_like of complex
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The exponentially scaled modified Bessel function of the second kind.
+
+    See Also
+    --------
+    kv : This function without exponential scaling.
+    k0e : Faster version of this function for order 0.
+    k1e : Faster version of this function for order 1.
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+
+    Examples
+    --------
+    In the following example `kv` returns 0 whereas `kve` still returns
+    a useful finite number.
+
+    >>> import numpy as np
+    >>> from scipy.special import kv, kve
+    >>> import matplotlib.pyplot as plt
+    >>> kv(3, 1000.), kve(3, 1000.)
+    (0.0, 0.03980696128440973)
+
+    Evaluate the function at one point for different orders by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> kve([0, 1, 1.5], 1.)
+    array([1.14446308, 1.63615349, 2.50662827])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> points = np.array([1., 3., 10.])
+    >>> kve(0, points)
+    array([1.14446308, 0.6977616 , 0.39163193])
+
+    Evaluate the function at several points for different orders by
+    providing arrays for both `v` for `z`. Both arrays have to be
+    broadcastable to the correct shape. To calculate the orders 0, 1
+    and 2 for a 1D array of points:
+
+    >>> kve([[0], [1], [2]], points)
+    array([[1.14446308, 0.6977616 , 0.39163193],
+           [1.63615349, 0.80656348, 0.41076657],
+           [4.41677005, 1.23547058, 0.47378525]])
+
+    Plot the functions of order 0 to 3 from 0 to 5.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, kve(i, x), label=fr'$K_{i!r}(z)\cdot e^z$')
+    >>> ax.legend()
+    >>> ax.set_xlabel(r"$z$")
+    >>> ax.set_ylim(0, 4)
+    >>> ax.set_xlim(0, 5)
+    >>> plt.show()
+    """)
+
+add_newdoc("_lanczos_sum_expg_scaled",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc(
+    "_landau_pdf",
+    """
+    _landau_pdf(x, loc, scale)
+
+    Probability density function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_cdf",
+    """
+    _landau_cdf(x, loc, scale)
+
+    Cumulative distribution function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_sf",
+    """
+    _landau_sf(x, loc, scale)
+
+    Survival function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_ppf",
+    """
+    _landau_ppf(p, loc, scale)
+
+    Percent point function of the Landau distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Real-valued argument between 0 and 1
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_isf",
+    """
+    _landau_isf(p, loc, scale)
+
+    Inverse survival function of the Landau distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Real-valued argument between 0 and 1
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc("_lgam1p",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("log1p",
+    """
+    log1p(x, out=None)
+
+    Calculates log(1 + x) for use when `x` is near zero.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of ``log(1 + x)``.
+
+    See Also
+    --------
+    expm1, cosm1
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is more accurate than using ``log(1 + x)`` directly for ``x``
+    near 0. Note that in the below example ``1 + 1e-17 == 1`` to
+    double precision.
+
+    >>> sc.log1p(1e-17)
+    1e-17
+    >>> np.log(1 + 1e-17)
+    0.0
+
+    """)
+
+add_newdoc("_log1pmx",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("lpmv",
+    r"""
+    lpmv(m, v, x, out=None)
+
+    Associated Legendre function of integer order and real degree.
+
+    Defined as
+
+    .. math::
+
+        P_v^m = (-1)^m (1 - x^2)^{m/2} \frac{d^m}{dx^m} P_v(x)
+
+    where
+
+    .. math::
+
+        P_v = \sum_{k = 0}^\infty \frac{(-v)_k (v + 1)_k}{(k!)^2}
+                \left(\frac{1 - x}{2}\right)^k
+
+    is the Legendre function of the first kind. Here :math:`(\cdot)_k`
+    is the Pochhammer symbol; see `poch`.
+
+    Parameters
+    ----------
+    m : array_like
+        Order (int or float). If passed a float not equal to an
+        integer the function returns NaN.
+    v : array_like
+        Degree (float).
+    x : array_like
+        Argument (float). Must have ``|x| <= 1``.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    pmv : scalar or ndarray
+        Value of the associated Legendre function.
+
+    See Also
+    --------
+    lpmn : Compute the associated Legendre function for all orders
+           ``0, ..., m`` and degrees ``0, ..., n``.
+    clpmn : Compute the associated Legendre function at complex
+            arguments.
+
+    Notes
+    -----
+    Note that this implementation includes the Condon-Shortley phase.
+
+    References
+    ----------
+    .. [1] Zhang, Jin, "Computation of Special Functions", John Wiley
+           and Sons, Inc, 1996.
+
+    """)
+
+add_newdoc("nbdtr",
+    r"""
+    nbdtr(k, n, p, out=None)
+
+    Negative binomial cumulative distribution function.
+
+    Returns the sum of the terms 0 through `k` of the negative binomial
+    distribution probability mass function,
+
+    .. math::
+
+        F = \sum_{j=0}^k {{n + j - 1}\choose{j}} p^n (1 - p)^j.
+
+    In a sequence of Bernoulli trials with individual success probabilities
+    `p`, this is the probability that `k` or fewer failures precede the nth
+    success.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The probability of `k` or fewer failures before `n` successes in a
+        sequence of events with individual success probability `p`.
+
+    See Also
+    --------
+    nbdtrc : Negative binomial survival function
+    nbdtrik : Negative binomial quantile function
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    If floating point values are passed for `k` or `n`, they will be truncated
+    to integers.
+
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{nbdtr}(k, n, p) = I_{p}(n, k + 1).
+
+    Wrapper for the Cephes [1]_ routine `nbdtr`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtr` directly can improve performance
+    compared to the ``cdf`` method of `scipy.stats.nbinom` (see last example).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtr
+    >>> nbdtr(10, 5, 0.5)
+    0.940765380859375
+
+    Compute the function for ``n=10`` and ``p=0.5`` at several points by
+    providing a NumPy array or list for `k`.
+
+    >>> nbdtr([5, 10, 15], 10, 0.5)
+    array([0.15087891, 0.58809853, 0.88523853])
+
+    Plot the function for four different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> k = np.arange(130)
+    >>> n_parameters = [20, 20, 20, 80]
+    >>> p_parameters = [0.2, 0.5, 0.8, 0.5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters,
+    ...                            linestyles))
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtr_vals = nbdtr(k, n, p)
+    ...     ax.plot(k, nbdtr_vals, label=rf"$n={n},\, p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$k$")
+    >>> ax.set_title("Negative binomial cumulative distribution function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtr` directly can be much faster than
+    calling the ``cdf`` method of `scipy.stats.nbinom`, especially for small
+    arrays or individual values. To get the same results one must use the
+    following parametrization: ``nbinom(n, p).cdf(k)=nbdtr(k, n, p)``.
+
+    >>> from scipy.stats import nbinom
+    >>> k, n, p = 5, 3, 0.5
+    >>> nbdtr_res = nbdtr(k, n, p)  # this will often be faster than below
+    >>> stats_res = nbinom(n, p).cdf(k)
+    >>> stats_res, nbdtr_res  # test that results are equal
+    (0.85546875, 0.85546875)
+
+    `nbdtr` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> p = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> nbdtr(k, 5, p)
+    array([[0.15026833, 0.62304687, 0.95265101, 0.9998531 ],
+           [0.48450894, 0.94076538, 0.99932777, 0.99999999],
+           [0.76249222, 0.99409103, 0.99999445, 1.        ]])
+    """)
+
+add_newdoc("nbdtrc",
+    r"""
+    nbdtrc(k, n, p, out=None)
+
+    Negative binomial survival function.
+
+    Returns the sum of the terms `k + 1` to infinity of the negative binomial
+    distribution probability mass function,
+
+    .. math::
+
+        F = \sum_{j=k + 1}^\infty {{n + j - 1}\choose{j}} p^n (1 - p)^j.
+
+    In a sequence of Bernoulli trials with individual success probabilities
+    `p`, this is the probability that more than `k` failures precede the nth
+    success.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The probability of `k + 1` or more failures before `n` successes in a
+        sequence of events with individual success probability `p`.
+
+    See Also
+    --------
+    nbdtr : Negative binomial cumulative distribution function
+    nbdtrik : Negative binomial percentile function
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    If floating point values are passed for `k` or `n`, they will be truncated
+    to integers.
+
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{nbdtrc}(k, n, p) = I_{1 - p}(k + 1, n).
+
+    Wrapper for the Cephes [1]_ routine `nbdtrc`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtrc` directly can improve performance
+    compared to the ``sf`` method of `scipy.stats.nbinom` (see last example).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtrc
+    >>> nbdtrc(10, 5, 0.5)
+    0.059234619140624986
+
+    Compute the function for ``n=10`` and ``p=0.5`` at several points by
+    providing a NumPy array or list for `k`.
+
+    >>> nbdtrc([5, 10, 15], 10, 0.5)
+    array([0.84912109, 0.41190147, 0.11476147])
+
+    Plot the function for four different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> k = np.arange(130)
+    >>> n_parameters = [20, 20, 20, 80]
+    >>> p_parameters = [0.2, 0.5, 0.8, 0.5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters,
+    ...                            linestyles))
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtrc_vals = nbdtrc(k, n, p)
+    ...     ax.plot(k, nbdtrc_vals, label=rf"$n={n},\, p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$k$")
+    >>> ax.set_title("Negative binomial distribution survival function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtrc` directly can be much faster than
+    calling the ``sf`` method of `scipy.stats.nbinom`, especially for small
+    arrays or individual values. To get the same results one must use the
+    following parametrization: ``nbinom(n, p).sf(k)=nbdtrc(k, n, p)``.
+
+    >>> from scipy.stats import nbinom
+    >>> k, n, p = 3, 5, 0.5
+    >>> nbdtr_res = nbdtrc(k, n, p)  # this will often be faster than below
+    >>> stats_res = nbinom(n, p).sf(k)
+    >>> stats_res, nbdtr_res  # test that results are equal
+    (0.6367187499999999, 0.6367187499999999)
+
+    `nbdtrc` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> p = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> nbdtrc(k, 5, p)
+    array([[8.49731667e-01, 3.76953125e-01, 4.73489874e-02, 1.46902600e-04],
+           [5.15491059e-01, 5.92346191e-02, 6.72234070e-04, 9.29610100e-09],
+           [2.37507779e-01, 5.90896606e-03, 5.55025308e-06, 3.26346760e-13]])
+    """)
+
+add_newdoc(
+    "nbdtri",
+    r"""
+    nbdtri(k, n, y, out=None)
+
+    Returns the inverse with respect to the parameter `p` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    p : scalar or ndarray
+        Probability of success in a single event (float) such that
+        `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtrc : Negative binomial survival function.
+    scipy.stats.nbinom : negative binomial distribution.
+    nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.
+    nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    Wrapper for the Cephes [1]_ routine `nbdtri`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtri` directly can improve performance
+    compared to the ``ppf`` method of `scipy.stats.nbinom`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    `nbdtri` is the inverse of `nbdtr` with respect to `p`.
+    Up to floating point errors the following holds:
+    ``nbdtri(k, n, nbdtr(k, n, p))=p``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtri, nbdtr
+    >>> k, n, y = 5, 10, 0.2
+    >>> cdf_val = nbdtr(k, n, y)
+    >>> nbdtri(k, n, cdf_val)
+    0.20000000000000004
+
+    Compute the function for ``k=10`` and ``n=5`` at several points by
+    providing a NumPy array or list for `y`.
+
+    >>> y = np.array([0.1, 0.4, 0.8])
+    >>> nbdtri(3, 5, y)
+    array([0.34462319, 0.51653095, 0.69677416])
+
+    Plot the function for three different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> n_parameters = [5, 20, 30, 30]
+    >>> k_parameters = [20, 20, 60, 80]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(n_parameters, k_parameters, linestyles))
+    >>> cdf_vals = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     n, k, style = parameter_set
+    ...     nbdtri_vals = nbdtri(k, n, cdf_vals)
+    ...     ax.plot(cdf_vals, nbdtri_vals, label=rf"$k={k},\ n={n}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_ylabel("$p$")
+    >>> ax.set_xlabel("$CDF$")
+    >>> title = "nbdtri: inverse of negative binomial CDF with respect to $p$"
+    >>> ax.set_title(title)
+    >>> plt.show()
+
+    `nbdtri` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> y = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, y.shape
+    ((3, 1), (4,))
+
+    >>> nbdtri(k, 5, y)
+    array([[0.37258157, 0.45169416, 0.53249956, 0.64578407],
+           [0.24588501, 0.30451981, 0.36778453, 0.46397088],
+           [0.18362101, 0.22966758, 0.28054743, 0.36066188]])
+    """)
+
+add_newdoc("nbdtrik",
+    r"""
+    nbdtrik(y, n, p, out=None)
+
+    Negative binomial percentile function.
+
+    Returns the inverse with respect to the parameter `k` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    k : scalar or ndarray
+        The maximum number of allowed failures such that `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtrc : Survival function of the negative binomial.
+    nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.
+    nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.
+
+    Formula 26.5.26 of [2]_,
+
+    .. math::
+        \sum_{j=k + 1}^\infty {{n + j - 1}
+        \choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),
+
+    is used to reduce calculation of the cumulative distribution function to
+    that of a regularized incomplete beta :math:`I`.
+
+    Computation of `k` involves a search for a value that produces the desired
+    value of `y`.  The search relies on the monotonicity of `y` with `k`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Compute the negative binomial cumulative distribution function for an
+    exemplary parameter set.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtr, nbdtrik
+    >>> k, n, p = 5, 2, 0.5
+    >>> cdf_value = nbdtr(k, n, p)
+    >>> cdf_value
+    0.9375
+
+    Verify that `nbdtrik` recovers the original value for `k`.
+
+    >>> nbdtrik(cdf_value, n, p)
+    5.0
+
+    Plot the function for different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> p_parameters = [0.2, 0.5, 0.7, 0.5]
+    >>> n_parameters = [30, 30, 30, 80]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters, linestyles))
+    >>> cdf_vals = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtrik_vals = nbdtrik(cdf_vals, n, p)
+    ...     ax.plot(cdf_vals, nbdtrik_vals, label=rf"$n={n},\ p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_ylabel("$k$")
+    >>> ax.set_xlabel("$CDF$")
+    >>> ax.set_title("Negative binomial percentile function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. The percentile function  method ``ppf``
+    returns the result of `nbdtrik` rounded up to integers:
+
+    >>> from scipy.stats import nbinom
+    >>> q, n, p = 0.6, 5, 0.5
+    >>> nbinom.ppf(q, n, p), nbdtrik(q, n, p)
+    (5.0, 4.800428460273882)
+
+    """)
+
+add_newdoc("nbdtrin",
+    r"""
+    nbdtrin(k, y, p, out=None)
+
+    Inverse of `nbdtr` vs `n`.
+
+    Returns the inverse with respect to the parameter `n` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    n : scalar or ndarray
+        The number of successes `n` such that `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.
+    nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.
+
+    Formula 26.5.26 of [2]_,
+
+    .. math::
+        \sum_{j=k + 1}^\infty {{n + j - 1}
+        \choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),
+
+    is used to reduce calculation of the cumulative distribution function to
+    that of a regularized incomplete beta :math:`I`.
+
+    Computation of `n` involves a search for a value that produces the desired
+    value of `y`.  The search relies on the monotonicity of `y` with `n`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Compute the negative binomial cumulative distribution function for an
+    exemplary parameter set.
+
+    >>> from scipy.special import nbdtr, nbdtrin
+    >>> k, n, p = 5, 2, 0.5
+    >>> cdf_value = nbdtr(k, n, p)
+    >>> cdf_value
+    0.9375
+
+    Verify that `nbdtrin` recovers the original value for `n` up to floating
+    point accuracy.
+
+    >>> nbdtrin(k, cdf_value, p)
+    1.999999999998137
+    """)
+
+add_newdoc("ncfdtr",
+    r"""
+    ncfdtr(dfn, dfd, nc, f, out=None)
+
+    Cumulative distribution function of the non-central F distribution.
+
+    The non-central F describes the distribution of,
+
+    .. math::
+        Z = \frac{X/d_n}{Y/d_d}
+
+    where :math:`X` and :math:`Y` are independently distributed, with
+    :math:`X` distributed non-central :math:`\chi^2` with noncentrality
+    parameter `nc` and :math:`d_n` degrees of freedom, and :math:`Y`
+    distributed :math:`\chi^2` with :math:`d_d` degrees of freedom.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares.  Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Range [0, inf).
+    f : array_like
+        Quantiles, i.e. the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        The calculated CDF.  If all inputs are scalar, the return will be a
+        float.  Otherwise it will be an array.
+
+    See Also
+    --------
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+    scipy.stats.ncf : Non-central F distribution.
+
+    Notes
+    -----
+    This function calculates the CDF of the non-central f distribution using
+    the Boost Math C++ library [1]_.
+
+    The cumulative distribution function is computed using Formula 26.6.20 of
+    [2]_:
+
+    .. math::
+        F(d_n, d_d, n_c, f) = \sum_{j=0}^\infty e^{-n_c/2}
+        \frac{(n_c/2)^j}{j!} I_{x}(\frac{d_n}{2} + j, \frac{d_d}{2}),
+
+    where :math:`I` is the regularized incomplete beta function, and
+    :math:`x = f d_n/(f d_n + d_d)`.
+
+    Note that argument order of `ncfdtr` is different from that of the
+    similar ``cdf`` method of `scipy.stats.ncf`: `f` is the last
+    parameter of `ncfdtr` but the first parameter of ``scipy.stats.ncf.cdf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Plot the CDF of the non-central F distribution, for nc=0.  Compare with the
+    F-distribution from scipy.stats:
+
+    >>> x = np.linspace(-1, 8, num=500)
+    >>> dfn = 3
+    >>> dfd = 2
+    >>> ncf_stats = stats.f.cdf(x, dfn, dfd)
+    >>> ncf_special = special.ncfdtr(dfn, dfd, 0, x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, ncf_stats, 'b-', lw=3)
+    >>> ax.plot(x, ncf_special, 'r-')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("ncfdtri",
+    """
+    ncfdtri(dfn, dfd, nc, p, out=None)
+
+    Inverse with respect to `f` of the CDF of the non-central F distribution.
+
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares.  Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Range [0, inf).
+    p : array_like
+        Value of the cumulative distribution function.  Must be in the
+        range [0, 1].
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    f : scalar or ndarray
+        Quantiles, i.e., the upper limit of integration.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+    scipy.stats.ncf : Non-central F distribution.
+
+    Notes
+    -----
+    This function calculates the Quantile of the non-central f distribution
+    using the Boost Math C++ library [1]_.
+
+    Note that argument order of `ncfdtri` is different from that of the
+    similar ``ppf`` method of `scipy.stats.ncf`. `p` is the last parameter
+    of `ncfdtri` but the first parameter of ``scipy.stats.ncf.ppf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtri
+
+    Compute the CDF for several values of `f`:
+
+    >>> f = [0.5, 1, 1.5]
+    >>> p = ncfdtr(2, 3, 1.5, f)
+    >>> p
+    array([ 0.20782291,  0.36107392,  0.47345752])
+
+    Compute the inverse.  We recover the values of `f`, as expected:
+
+    >>> ncfdtri(2, 3, 1.5, p)
+    array([ 0.5,  1. ,  1.5])
+
+    """)
+
+add_newdoc("ncfdtridfd",
+    """
+    ncfdtridfd(dfn, p, nc, f, out=None)
+
+    Calculate degrees of freedom (denominator) for the noncentral F-distribution.
+
+    This is the inverse with respect to `dfd` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    p : array_like
+        Value of the cumulative distribution function.  Must be in the
+        range [0, 1].
+    nc : array_like
+        Noncentrality parameter.  Should be in range (0, 1e4).
+    f : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    dfd : scalar or ndarray
+        Degrees of freedom of the denominator sum of squares.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+
+    Notes
+    -----
+    The value of the cumulative noncentral F distribution is not necessarily
+    monotone in either degrees of freedom. There thus may be two values that
+    provide a given CDF value. This routine assumes monotonicity and will
+    find an arbitrary one of the two values.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtridfd
+
+    Compute the CDF for several values of `dfd`:
+
+    >>> dfd = [1, 2, 3]
+    >>> p = ncfdtr(2, dfd, 0.25, 15)
+    >>> p
+    array([ 0.8097138 ,  0.93020416,  0.96787852])
+
+    Compute the inverse.  We recover the values of `dfd`, as expected:
+
+    >>> ncfdtridfd(2, p, 0.25, 15)
+    array([ 1.,  2.,  3.])
+
+    """)
+
+add_newdoc("ncfdtridfn",
+    """
+    ncfdtridfn(p, dfd, nc, f, out=None)
+
+    Calculate degrees of freedom (numerator) for the noncentral F-distribution.
+
+    This is the inverse with respect to `dfn` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    p : array_like
+        Value of the cumulative distribution function. Must be in the
+        range [0, 1].
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares. Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Should be in range (0, 1e4).
+    f : float
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    dfn : scalar or ndarray
+        Degrees of freedom of the numerator sum of squares.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+
+    Notes
+    -----
+    The value of the cumulative noncentral F distribution is not necessarily
+    monotone in either degrees of freedom. There thus may be two values that
+    provide a given CDF value. This routine assumes monotonicity and will
+    find an arbitrary one of the two values.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtridfn
+
+    Compute the CDF for several values of `dfn`:
+
+    >>> dfn = [1, 2, 3]
+    >>> p = ncfdtr(dfn, 2, 0.25, 15)
+    >>> p
+    array([ 0.92562363,  0.93020416,  0.93188394])
+
+    Compute the inverse. We recover the values of `dfn`, as expected:
+
+    >>> ncfdtridfn(p, 2, 0.25, 15)
+    array([ 1.,  2.,  3.])
+
+    """)
+
+add_newdoc("ncfdtrinc",
+    """
+    ncfdtrinc(dfn, dfd, p, f, out=None)
+
+    Calculate non-centrality parameter for non-central F distribution.
+
+    This is the inverse with respect to `nc` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares. Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares. Range (0, inf).
+    p : array_like
+        Value of the cumulative distribution function. Must be in the
+        range [0, 1].
+    f : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Noncentrality parameter.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtrinc
+
+    Compute the CDF for several values of `nc`:
+
+    >>> nc = [0.5, 1.5, 2.0]
+    >>> p = ncfdtr(2, 3, nc, 15)
+    >>> p
+    array([ 0.96309246,  0.94327955,  0.93304098])
+
+    Compute the inverse. We recover the values of `nc`, as expected:
+
+    >>> ncfdtrinc(2, 3, p, 15)
+    array([ 0.5,  1.5,  2. ])
+
+    """)
+
+add_newdoc("nctdtr",
+    """
+    nctdtr(df, nc, t, out=None)
+
+    Cumulative distribution function of the non-central `t` distribution.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    nc : array_like
+        Noncentrality parameter.
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        The calculated CDF. If all inputs are scalar, the return will be a
+        float. Otherwise, it will be an array.
+
+    See Also
+    --------
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Notes
+    -----
+    This function calculates the CDF of the non-central t distribution using
+    the Boost Math C++ library [1]_.
+
+    Note that the argument order of `nctdtr` is different from that of the
+    similar ``cdf`` method of `scipy.stats.nct`: `t` is the last
+    parameter of `nctdtr` but the first parameter of ``scipy.stats.nct.cdf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Plot the CDF of the non-central t distribution, for nc=0. Compare with the
+    t-distribution from scipy.stats:
+
+    >>> x = np.linspace(-5, 5, num=500)
+    >>> df = 3
+    >>> nct_stats = stats.t.cdf(x, df)
+    >>> nct_special = special.nctdtr(df, 0, x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, nct_stats, 'b-', lw=3)
+    >>> ax.plot(x, nct_special, 'r-')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("nctdtridf",
+    """
+    nctdtridf(p, nc, t, out=None)
+
+    Calculate degrees of freedom for non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    p : array_like
+        CDF values, in range (0, 1].
+    nc : array_like
+        Noncentrality parameter. Should be in range (-1e6, 1e6).
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        The degrees of freedom. If all inputs are scalar, the return will be a
+        float. Otherwise, it will be an array.
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtridf
+
+    Compute the CDF for several values of `df`:
+
+    >>> df = [1, 2, 3]
+    >>> p = nctdtr(df, 0.25, 1)
+    >>> p
+    array([0.67491974, 0.716464  , 0.73349456])
+
+    Compute the inverse. We recover the values of `df`, as expected:
+
+    >>> nctdtridf(p, 0.25, 1)
+    array([1., 2., 3.])
+
+    """)
+
+add_newdoc("nctdtrinc",
+    """
+    nctdtrinc(df, p, t, out=None)
+
+    Calculate non-centrality parameter for non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    p : array_like
+        CDF values, in range (0, 1].
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Noncentrality parameter
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtrinc
+
+    Compute the CDF for several values of `nc`:
+
+    >>> nc = [0.5, 1.5, 2.5]
+    >>> p = nctdtr(3, nc, 1.5)
+    >>> p
+    array([0.77569497, 0.45524533, 0.1668691 ])
+
+    Compute the inverse. We recover the values of `nc`, as expected:
+
+    >>> nctdtrinc(3, p, 1.5)
+    array([0.5, 1.5, 2.5])
+
+    """)
+
+add_newdoc("nctdtrit",
+    """
+    nctdtrit(df, nc, p, out=None)
+
+    Inverse cumulative distribution function of the non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    nc : array_like
+        Noncentrality parameter. Should be in range (-1e6, 1e6).
+    p : array_like
+        CDF values, in range (0, 1].
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t : scalar or ndarray
+        Quantiles
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtrit
+
+    Compute the CDF for several values of `t`:
+
+    >>> t = [0.5, 1, 1.5]
+    >>> p = nctdtr(3, 1, t)
+    >>> p
+    array([0.29811049, 0.46922687, 0.6257559 ])
+
+    Compute the inverse. We recover the values of `t`, as expected:
+
+    >>> nctdtrit(3, 1, p)
+    array([0.5, 1. , 1.5])
+
+    """)
+
+add_newdoc("ndtr",
+    r"""
+    ndtr(x, out=None)
+
+    Cumulative distribution of the standard normal distribution.
+
+    Returns the area under the standard Gaussian probability
+    density function, integrated from minus infinity to `x`
+
+    .. math::
+
+       \frac{1}{\sqrt{2\pi}} \int_{-\infty}^x \exp(-t^2/2) dt
+
+    Parameters
+    ----------
+    x : array_like, real or complex
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the normal CDF evaluated at `x`
+
+    See Also
+    --------
+    log_ndtr : Logarithm of ndtr
+    ndtri : Inverse of ndtr, standard normal percentile function
+    erf : Error function
+    erfc : 1 - erf
+    scipy.stats.norm : Normal distribution
+
+    Examples
+    --------
+    Evaluate `ndtr` at one point.
+
+    >>> import numpy as np
+    >>> from scipy.special import ndtr
+    >>> ndtr(0.5)
+    0.6914624612740131
+
+    Evaluate the function at several points by providing a NumPy array
+    or list for `x`.
+
+    >>> ndtr([0, 0.5, 2])
+    array([0.5       , 0.69146246, 0.97724987])
+
+    Plot the function.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-5, 5, 100)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ndtr(x))
+    >>> ax.set_title(r"Standard normal cumulative distribution function $\Phi$")
+    >>> plt.show()
+    """)
+
+
+add_newdoc("nrdtrimn",
+    """
+    nrdtrimn(p, std, x, out=None)
+
+    Calculate mean of normal distribution given other params.
+
+    Parameters
+    ----------
+    p : array_like
+        CDF values, in range (0, 1].
+    std : array_like
+        Standard deviation.
+    x : array_like
+        Quantiles, i.e. the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    mn : scalar or ndarray
+        The mean of the normal distribution.
+
+    See Also
+    --------
+    scipy.stats.norm : Normal distribution
+    ndtr : Standard normal cumulative probability distribution
+    ndtri : Inverse of standard normal CDF with respect to quantile
+    nrdtrisd : Inverse of normal distribution CDF with respect to
+               standard deviation
+
+    Examples
+    --------
+    `nrdtrimn` can be used to recover the mean of a normal distribution
+    if we know the CDF value `p` for a given quantile `x` and the
+    standard deviation `std`. First, we calculate
+    the normal distribution CDF for an exemplary parameter set.
+
+    >>> from scipy.stats import norm
+    >>> mean = 3.
+    >>> std = 2.
+    >>> x = 6.
+    >>> p = norm.cdf(x, loc=mean, scale=std)
+    >>> p
+    0.9331927987311419
+
+    Verify that `nrdtrimn` returns the original value for `mean`.
+
+    >>> from scipy.special import nrdtrimn
+    >>> nrdtrimn(p, std, x)
+    3.0000000000000004
+
+    """)
+
+add_newdoc("nrdtrisd",
+    """
+    nrdtrisd(mn, p, x, out=None)
+
+    Calculate standard deviation of normal distribution given other params.
+
+    Parameters
+    ----------
+    mn : scalar or ndarray
+        The mean of the normal distribution.
+    p : array_like
+        CDF values, in range (0, 1].
+    x : array_like
+        Quantiles, i.e. the upper limit of integration.
+
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    std : scalar or ndarray
+        Standard deviation.
+
+    See Also
+    --------
+    scipy.stats.norm : Normal distribution
+    ndtr : Standard normal cumulative probability distribution
+    ndtri : Inverse of standard normal CDF with respect to quantile
+    nrdtrimn : Inverse of normal distribution CDF with respect to
+               mean
+
+    Examples
+    --------
+    `nrdtrisd` can be used to recover the standard deviation of a normal
+    distribution if we know the CDF value `p` for a given quantile `x` and
+    the mean `mn`. First, we calculate the normal distribution CDF for an
+    exemplary parameter set.
+
+    >>> from scipy.stats import norm
+    >>> mean = 3.
+    >>> std = 2.
+    >>> x = 6.
+    >>> p = norm.cdf(x, loc=mean, scale=std)
+    >>> p
+    0.9331927987311419
+
+    Verify that `nrdtrisd` returns the original value for `std`.
+
+    >>> from scipy.special import nrdtrisd
+    >>> nrdtrisd(mean, p, x)
+    2.0000000000000004
+
+    """)
+
+add_newdoc("log_ndtr",
+    """
+    log_ndtr(x, out=None)
+
+    Logarithm of Gaussian cumulative distribution function.
+
+    Returns the log of the area under the standard Gaussian probability
+    density function, integrated from minus infinity to `x`::
+
+        log(1/sqrt(2*pi) * integral(exp(-t**2 / 2), t=-inf..x))
+
+    Parameters
+    ----------
+    x : array_like, real or complex
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the log of the normal CDF evaluated at `x`
+
+    See Also
+    --------
+    erf
+    erfc
+    scipy.stats.norm
+    ndtr
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import log_ndtr, ndtr
+
+    The benefit of ``log_ndtr(x)`` over the naive implementation
+    ``np.log(ndtr(x))`` is most evident with moderate to large positive
+    values of ``x``:
+
+    >>> x = np.array([6, 7, 9, 12, 15, 25])
+    >>> log_ndtr(x)
+    array([-9.86587646e-010, -1.27981254e-012, -1.12858841e-019,
+           -1.77648211e-033, -3.67096620e-051, -3.05669671e-138])
+
+    The results of the naive calculation for the moderate ``x`` values
+    have only 5 or 6 correct significant digits. For values of ``x``
+    greater than approximately 8.3, the naive expression returns 0:
+
+    >>> np.log(ndtr(x))
+    array([-9.86587701e-10, -1.27986510e-12,  0.00000000e+00,
+            0.00000000e+00,  0.00000000e+00,  0.00000000e+00])
+    """)
+
+add_newdoc("ndtri",
+    """
+    ndtri(y, out=None)
+
+    Inverse of `ndtr` vs x
+
+    Returns the argument x for which the area under the standard normal
+    probability density function (integrated from minus infinity to `x`)
+    is equal to y.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value of x such that ``ndtr(x) == p``.
+
+    See Also
+    --------
+    ndtr : Standard normal cumulative probability distribution
+    ndtri_exp : Inverse of log_ndtr
+
+    Examples
+    --------
+    `ndtri` is the percentile function of the standard normal distribution.
+    This means it returns the inverse of the cumulative density `ndtr`. First,
+    let us compute a cumulative density value.
+
+    >>> import numpy as np
+    >>> from scipy.special import ndtri, ndtr
+    >>> cdf_val = ndtr(2)
+    >>> cdf_val
+    0.9772498680518208
+
+    Verify that `ndtri` yields the original value for `x` up to floating point
+    errors.
+
+    >>> ndtri(cdf_val)
+    2.0000000000000004
+
+    Plot the function. For that purpose, we provide a NumPy array as argument.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0.01, 1, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ndtri(x))
+    >>> ax.set_title("Standard normal percentile function")
+    >>> plt.show()
+    """)
+
+add_newdoc("pdtr",
+    r"""
+    pdtr(k, m, out=None)
+
+    Poisson cumulative distribution function.
+
+    Defined as the probability that a Poisson-distributed random
+    variable with event rate :math:`m` is less than or equal to
+    :math:`k`. More concretely, this works out to be [1]_
+
+    .. math::
+
+       \exp(-m) \sum_{j = 0}^{\lfloor{k}\rfloor} \frac{m^j}{j!}.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Poisson cumulative distribution function
+
+    See Also
+    --------
+    pdtrc : Poisson survival function
+    pdtrik : inverse of `pdtr` with respect to `k`
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Poisson_distribution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is a cumulative distribution function, so it converges to 1
+    monotonically as `k` goes to infinity.
+
+    >>> sc.pdtr([1, 10, 100, np.inf], 1)
+    array([0.73575888, 0.99999999, 1.        , 1.        ])
+
+    It is discontinuous at integers and constant between integers.
+
+    >>> sc.pdtr([1, 1.5, 1.9, 2], 1)
+    array([0.73575888, 0.73575888, 0.73575888, 0.9196986 ])
+
+    """)
+
+add_newdoc("pdtrc",
+    """
+    pdtrc(k, m, out=None)
+
+    Poisson survival function
+
+    Returns the sum of the terms from k+1 to infinity of the Poisson
+    distribution: sum(exp(-m) * m**j / j!, j=k+1..inf) = gammainc(
+    k+1, m). Arguments must both be non-negative doubles.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Poisson survival function
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrik : inverse of `pdtr` with respect to `k`
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is a survival function, so it decreases to 0
+    monotonically as `k` goes to infinity.
+
+    >>> k = np.array([1, 10, 100, np.inf])
+    >>> sc.pdtrc(k, 1)
+    array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])
+
+    It can be expressed in terms of the lower incomplete gamma
+    function `gammainc`.
+
+    >>> sc.gammainc(k + 1, 1)
+    array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])
+
+    """)
+
+add_newdoc("pdtri",
+    """
+    pdtri(k, y, out=None)
+
+    Inverse to `pdtr` vs m
+
+    Returns the Poisson variable `m` such that the sum from 0 to `k` of
+    the Poisson density is equal to the given probability `y`:
+    calculated by ``gammaincinv(k + 1, y)``. `k` must be a nonnegative
+    integer and `y` between 0 and 1.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    y : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the shape parameter `m` such that ``pdtr(k, m) = p``
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrc : Poisson survival function
+    pdtrik : inverse of `pdtr` with respect to `k`
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    Compute the CDF for several values of `m`:
+
+    >>> m = [0.5, 1, 1.5]
+    >>> p = sc.pdtr(1, m)
+    >>> p
+    array([0.90979599, 0.73575888, 0.5578254 ])
+
+    Compute the inverse. We recover the values of `m`, as expected:
+
+    >>> sc.pdtri(1, p)
+    array([0.5, 1. , 1.5])
+
+    """)
+
+add_newdoc("pdtrik",
+    """
+    pdtrik(p, m, out=None)
+
+    Inverse to `pdtr` vs `k`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The number of occurrences `k` such that ``pdtr(k, m) = p``
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrc : Poisson survival function
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    Compute the CDF for several values of `k`:
+
+    >>> k = [1, 2, 3]
+    >>> p = sc.pdtr(k, 2)
+    >>> p
+    array([0.40600585, 0.67667642, 0.85712346])
+
+    Compute the inverse. We recover the values of `k`, as expected:
+
+    >>> sc.pdtrik(p, 2)
+    array([1., 2., 3.])
+
+    """)
+
+add_newdoc("poch",
+    r"""
+    poch(z, m, out=None)
+
+    Pochhammer symbol.
+
+    The Pochhammer symbol (rising factorial) is defined as
+
+    .. math::
+
+        (z)_m = \frac{\Gamma(z + m)}{\Gamma(z)}
+
+    For positive integer `m` it reads
+
+    .. math::
+
+        (z)_m = z (z + 1) ... (z + m - 1)
+
+    See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    z, m : array_like
+        Real-valued arguments.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the function.
+
+    References
+    ----------
+    .. [dlmf] Nist, Digital Library of Mathematical Functions
+        https://dlmf.nist.gov/5.2#iii
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It is 1 when m is 0.
+
+    >>> sc.poch([1, 2, 3, 4], 0)
+    array([1., 1., 1., 1.])
+
+    For z equal to 1 it reduces to the factorial function.
+
+    >>> sc.poch(1, 5)
+    120.0
+    >>> 1 * 2 * 3 * 4 * 5
+    120
+
+    It can be expressed in terms of the gamma function.
+
+    >>> z, m = 3.7, 2.1
+    >>> sc.poch(z, m)
+    20.529581933776953
+    >>> sc.gamma(z + m) / sc.gamma(z)
+    20.52958193377696
+
+    """)
+
+add_newdoc("powm1", """
+    powm1(x, y, out=None)
+
+    Computes ``x**y - 1``.
+
+    This function is useful when `y` is near 0, or when `x` is near 1.
+
+    The function is implemented for real types only (unlike ``numpy.power``,
+    which accepts complex inputs).
+
+    Parameters
+    ----------
+    x : array_like
+        The base. Must be a real type (i.e. integer or float, not complex).
+    y : array_like
+        The exponent. Must be a real type (i.e. integer or float, not complex).
+
+    Returns
+    -------
+    array_like
+        Result of the calculation
+
+    Notes
+    -----
+    .. versionadded:: 1.10.0
+
+    The underlying code is implemented for single precision and double
+    precision floats only.  Unlike `numpy.power`, integer inputs to
+    `powm1` are converted to floating point, and complex inputs are
+    not accepted.
+
+    Note the following edge cases:
+
+    * ``powm1(x, 0)`` returns 0 for any ``x``, including 0, ``inf``
+      and ``nan``.
+    * ``powm1(1, y)`` returns 0 for any ``y``, including ``nan``
+      and ``inf``.
+
+    This function wraps the ``powm1`` routine from the
+    Boost Math C++ library [1]_.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import powm1
+
+    >>> x = np.array([1.2, 10.0, 0.9999999975])
+    >>> y = np.array([1e-9, 1e-11, 0.1875])
+    >>> powm1(x, y)
+    array([ 1.82321557e-10,  2.30258509e-11, -4.68749998e-10])
+
+    It can be verified that the relative errors in those results
+    are less than 2.5e-16.
+
+    Compare that to the result of ``x**y - 1``, where the
+    relative errors are all larger than 8e-8:
+
+    >>> x**y - 1
+    array([ 1.82321491e-10,  2.30258035e-11, -4.68750039e-10])
+
+    """)
+
+
+add_newdoc("pseudo_huber",
+    r"""
+    pseudo_huber(delta, r, out=None)
+
+    Pseudo-Huber loss function.
+
+    .. math:: \mathrm{pseudo\_huber}(\delta, r) =
+              \delta^2 \left( \sqrt{ 1 + \left( \frac{r}{\delta} \right)^2 } - 1 \right)
+
+    Parameters
+    ----------
+    delta : array_like
+        Input array, indicating the soft quadratic vs. linear loss changepoint.
+    r : array_like
+        Input array, possibly representing residuals.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The computed Pseudo-Huber loss function values.
+
+    See Also
+    --------
+    huber: Similar function which this function approximates
+
+    Notes
+    -----
+    Like `huber`, `pseudo_huber` often serves as a robust loss function
+    in statistics or machine learning to reduce the influence of outliers.
+    Unlike `huber`, `pseudo_huber` is smooth.
+
+    Typically, `r` represents residuals, the difference
+    between a model prediction and data. Then, for :math:`|r|\leq\delta`,
+    `pseudo_huber` resembles the squared error and for :math:`|r|>\delta` the
+    absolute error. This way, the Pseudo-Huber loss often achieves
+    a fast convergence in model fitting for small residuals like the squared
+    error loss function and still reduces the influence of outliers
+    (:math:`|r|>\delta`) like the absolute error loss. As :math:`\delta` is
+    the cutoff between squared and absolute error regimes, it has
+    to be tuned carefully for each problem. `pseudo_huber` is also
+    convex, making it suitable for gradient based optimization. [1]_ [2]_
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Hartley, Zisserman, "Multiple View Geometry in Computer Vision".
+           2003. Cambridge University Press. p. 619
+    .. [2] Charbonnier et al. "Deterministic edge-preserving regularization
+           in computed imaging". 1997. IEEE Trans. Image Processing.
+           6 (2): 298 - 311.
+
+    Examples
+    --------
+    Import all necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.special import pseudo_huber, huber
+    >>> import matplotlib.pyplot as plt
+
+    Calculate the function for ``delta=1`` at ``r=2``.
+
+    >>> pseudo_huber(1., 2.)
+    1.2360679774997898
+
+    Calculate the function at ``r=2`` for different `delta` by providing
+    a list or NumPy array for `delta`.
+
+    >>> pseudo_huber([1., 2., 4.], 3.)
+    array([2.16227766, 3.21110255, 4.        ])
+
+    Calculate the function for ``delta=1`` at several points by providing
+    a list or NumPy array for `r`.
+
+    >>> pseudo_huber(2., np.array([1., 1.5, 3., 4.]))
+    array([0.47213595, 1.        , 3.21110255, 4.94427191])
+
+    The function can be calculated for different `delta` and `r` by
+    providing arrays for both with compatible shapes for broadcasting.
+
+    >>> r = np.array([1., 2.5, 8., 10.])
+    >>> deltas = np.array([[1.], [5.], [9.]])
+    >>> print(r.shape, deltas.shape)
+    (4,) (3, 1)
+
+    >>> pseudo_huber(deltas, r)
+    array([[ 0.41421356,  1.6925824 ,  7.06225775,  9.04987562],
+           [ 0.49509757,  2.95084972, 22.16990566, 30.90169944],
+           [ 0.49846624,  3.06693762, 27.37435121, 40.08261642]])
+
+    Plot the function for different `delta`.
+
+    >>> x = np.linspace(-4, 4, 500)
+    >>> deltas = [1, 2, 3]
+    >>> linestyles = ["dashed", "dotted", "dashdot"]
+    >>> fig, ax = plt.subplots()
+    >>> combined_plot_parameters = list(zip(deltas, linestyles))
+    >>> for delta, style in combined_plot_parameters:
+    ...     ax.plot(x, pseudo_huber(delta, x), label=rf"$\delta={delta}$",
+    ...             ls=style)
+    >>> ax.legend(loc="upper center")
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title(r"Pseudo-Huber loss function $h_{\delta}(x)$")
+    >>> ax.set_xlim(-4, 4)
+    >>> ax.set_ylim(0, 8)
+    >>> plt.show()
+
+    Finally, illustrate the difference between `huber` and `pseudo_huber` by
+    plotting them and their gradients with respect to `r`. The plot shows
+    that `pseudo_huber` is continuously differentiable while `huber` is not
+    at the points :math:`\pm\delta`.
+
+    >>> def huber_grad(delta, x):
+    ...     grad = np.copy(x)
+    ...     linear_area = np.argwhere(np.abs(x) > delta)
+    ...     grad[linear_area]=delta*np.sign(x[linear_area])
+    ...     return grad
+    >>> def pseudo_huber_grad(delta, x):
+    ...     return x* (1+(x/delta)**2)**(-0.5)
+    >>> x=np.linspace(-3, 3, 500)
+    >>> delta = 1.
+    >>> fig, ax = plt.subplots(figsize=(7, 7))
+    >>> ax.plot(x, huber(delta, x), label="Huber", ls="dashed")
+    >>> ax.plot(x, huber_grad(delta, x), label="Huber Gradient", ls="dashdot")
+    >>> ax.plot(x, pseudo_huber(delta, x), label="Pseudo-Huber", ls="dotted")
+    >>> ax.plot(x, pseudo_huber_grad(delta, x), label="Pseudo-Huber Gradient",
+    ...         ls="solid")
+    >>> ax.legend(loc="upper center")
+    >>> plt.show()
+    """)
+
+add_newdoc("rel_entr",
+    r"""
+    rel_entr(x, y, out=None)
+
+    Elementwise function for computing relative entropy.
+
+    .. math::
+
+        \mathrm{rel\_entr}(x, y) =
+            \begin{cases}
+                x \log(x / y) & x > 0, y > 0 \\
+                0 & x = 0, y \ge 0 \\
+                \infty & \text{otherwise}
+            \end{cases}
+
+    Parameters
+    ----------
+    x, y : array_like
+        Input arrays
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Relative entropy of the inputs
+
+    See Also
+    --------
+    entr, kl_div, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is jointly convex in x and y.
+
+    The origin of this function is in convex programming; see
+    [1]_. Given two discrete probability distributions :math:`p_1,
+    \ldots, p_n` and :math:`q_1, \ldots, q_n`, the definition of relative
+    entropy in the context of *information theory* is
+
+    .. math::
+
+        \sum_{i = 1}^n \mathrm{rel\_entr}(p_i, q_i).
+
+    To compute the latter quantity, use `scipy.stats.entropy`.
+
+    See [2]_ for details.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+    .. [2] Kullback-Leibler divergence,
+           https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence
+
+    """)
+
+add_newdoc("round",
+    """
+    round(x, out=None)
+
+    Round to the nearest integer.
+
+    Returns the nearest integer to `x`.  If `x` ends in 0.5 exactly,
+    the nearest even integer is chosen.
+
+    Parameters
+    ----------
+    x : array_like
+        Real valued input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        The nearest integers to the elements of `x`. The result is of
+        floating type, not integer type.
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It rounds to even.
+
+    >>> sc.round([0.5, 1.5])
+    array([0., 2.])
+
+    """)
+
+add_newdoc("shichi",
+    r"""
+    shichi(x, out=None)
+
+    Hyperbolic sine and cosine integrals.
+
+    The hyperbolic sine integral is
+
+    .. math::
+
+      \int_0^x \frac{\sinh{t}}{t}dt
+
+    and the hyperbolic cosine integral is
+
+    .. math::
+
+      \gamma + \log(x) + \int_0^x \frac{\cosh{t} - 1}{t} dt
+
+    where :math:`\gamma` is Euler's constant and :math:`\log` is the
+    principal branch of the logarithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex points at which to compute the hyperbolic sine
+        and cosine integrals.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function results
+
+    Returns
+    -------
+    si : scalar or ndarray
+        Hyperbolic sine integral at ``x``
+    ci : scalar or ndarray
+        Hyperbolic cosine integral at ``x``
+
+    See Also
+    --------
+    sici : Sine and cosine integrals.
+    exp1 : Exponential integral E1.
+    expi : Exponential integral Ei.
+
+    Notes
+    -----
+    For real arguments with ``x < 0``, ``chi`` is the real part of the
+    hyperbolic cosine integral. For such points ``chi(x)`` and ``chi(x
+    + 0j)`` differ by a factor of ``1j*pi``.
+
+    For real arguments the function is computed by calling Cephes'
+    [2]_ *shichi* routine. For complex arguments the algorithm is based
+    on Mpmath's [3]_ *shi* and *chi* routines.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+           (See Section 5.2.)
+    .. [2] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [3] Fredrik Johansson and others.
+           "mpmath: a Python library for arbitrary-precision floating-point
+           arithmetic" (Version 0.19) http://mpmath.org/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import shichi, sici
+
+    `shichi` accepts real or complex input:
+
+    >>> shichi(0.5)
+    (0.5069967498196671, -0.05277684495649357)
+    >>> shichi(0.5 + 2.5j)
+    ((0.11772029666668238+1.831091777729851j),
+     (0.29912435887648825+1.7395351121166562j))
+
+    The hyperbolic sine and cosine integrals Shi(z) and Chi(z) are
+    related to the sine and cosine integrals Si(z) and Ci(z) by
+
+    * Shi(z) = -i*Si(i*z)
+    * Chi(z) = Ci(-i*z) + i*pi/2
+
+    >>> z = 0.25 + 5j
+    >>> shi, chi = shichi(z)
+    >>> shi, -1j*sici(1j*z)[0]            # Should be the same.
+    ((-0.04834719325101729+1.5469354086921228j),
+     (-0.04834719325101729+1.5469354086921228j))
+    >>> chi, sici(-1j*z)[1] + 1j*np.pi/2  # Should be the same.
+    ((-0.19568708973868087+1.556276312103824j),
+     (-0.19568708973868087+1.556276312103824j))
+
+    Plot the functions evaluated on the real axis:
+
+    >>> xp = np.geomspace(1e-8, 4.0, 250)
+    >>> x = np.concatenate((-xp[::-1], xp))
+    >>> shi, chi = shichi(x)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, shi, label='Shi(x)')
+    >>> ax.plot(x, chi, '--', label='Chi(x)')
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('Hyperbolic Sine and Cosine Integrals')
+    >>> ax.legend(shadow=True, framealpha=1, loc='lower right')
+    >>> ax.grid(True)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("sici",
+    r"""
+    sici(x, out=None)
+
+    Sine and cosine integrals.
+
+    The sine integral is
+
+    .. math::
+
+      \int_0^x \frac{\sin{t}}{t}dt
+
+    and the cosine integral is
+
+    .. math::
+
+      \gamma + \log(x) + \int_0^x \frac{\cos{t} - 1}{t}dt
+
+    where :math:`\gamma` is Euler's constant and :math:`\log` is the
+    principal branch of the logarithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex points at which to compute the sine and cosine
+        integrals.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function results
+
+    Returns
+    -------
+    si : scalar or ndarray
+        Sine integral at ``x``
+    ci : scalar or ndarray
+        Cosine integral at ``x``
+
+    See Also
+    --------
+    shichi : Hyperbolic sine and cosine integrals.
+    exp1 : Exponential integral E1.
+    expi : Exponential integral Ei.
+
+    Notes
+    -----
+    For real arguments with ``x < 0``, ``ci`` is the real part of the
+    cosine integral. For such points ``ci(x)`` and ``ci(x + 0j)``
+    differ by a factor of ``1j*pi``.
+
+    For real arguments the function is computed by calling Cephes'
+    [2]_ *sici* routine. For complex arguments the algorithm is based
+    on Mpmath's [3]_ *si* and *ci* routines.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+           (See Section 5.2.)
+    .. [2] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [3] Fredrik Johansson and others.
+           "mpmath: a Python library for arbitrary-precision floating-point
+           arithmetic" (Version 0.19) http://mpmath.org/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import sici, exp1
+
+    `sici` accepts real or complex input:
+
+    >>> sici(2.5)
+    (1.7785201734438267, 0.2858711963653835)
+    >>> sici(2.5 + 3j)
+    ((4.505735874563953+0.06863305018999577j),
+    (0.0793644206906966-2.935510262937543j))
+
+    For z in the right half plane, the sine and cosine integrals are
+    related to the exponential integral E1 (implemented in SciPy as
+    `scipy.special.exp1`) by
+
+    * Si(z) = (E1(i*z) - E1(-i*z))/2i + pi/2
+    * Ci(z) = -(E1(i*z) + E1(-i*z))/2
+
+    See [1]_ (equations 5.2.21 and 5.2.23).
+
+    We can verify these relations:
+
+    >>> z = 2 - 3j
+    >>> sici(z)
+    ((4.54751388956229-1.3991965806460565j),
+    (1.408292501520851+2.9836177420296055j))
+
+    >>> (exp1(1j*z) - exp1(-1j*z))/2j + np.pi/2  # Same as sine integral
+    (4.54751388956229-1.3991965806460565j)
+
+    >>> -(exp1(1j*z) + exp1(-1j*z))/2            # Same as cosine integral
+    (1.408292501520851+2.9836177420296055j)
+
+    Plot the functions evaluated on the real axis; the dotted horizontal
+    lines are at pi/2 and -pi/2:
+
+    >>> x = np.linspace(-16, 16, 150)
+    >>> si, ci = sici(x)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, si, label='Si(x)')
+    >>> ax.plot(x, ci, '--', label='Ci(x)')
+    >>> ax.legend(shadow=True, framealpha=1, loc='upper left')
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('Sine and Cosine Integrals')
+    >>> ax.axhline(np.pi/2, linestyle=':', alpha=0.5, color='k')
+    >>> ax.axhline(-np.pi/2, linestyle=':', alpha=0.5, color='k')
+    >>> ax.grid(True)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("smirnov",
+    r"""
+    smirnov(n, d, out=None)
+
+    Kolmogorov-Smirnov complementary cumulative distribution function
+
+    Returns the exact Kolmogorov-Smirnov complementary cumulative
+    distribution function,(aka the Survival Function) of Dn+ (or Dn-)
+    for a one-sided test of equality between an empirical and a
+    theoretical distribution. It is equal to the probability that the
+    maximum difference between a theoretical distribution and an empirical
+    one based on `n` samples is greater than d.
+
+    Parameters
+    ----------
+    n : int
+      Number of samples
+    d : float array_like
+      Deviation between the Empirical CDF (ECDF) and the target CDF.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of smirnov(n, d), Prob(Dn+ >= d) (Also Prob(Dn- >= d))
+
+    See Also
+    --------
+    smirnovi : The Inverse Survival Function for the distribution
+    scipy.stats.ksone : Provides the functionality as a continuous distribution
+    kolmogorov, kolmogi : Functions for the two-sided distribution
+
+    Notes
+    -----
+    `smirnov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.ksone` distribution.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import smirnov
+    >>> from scipy.stats import norm
+
+    Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a
+    sample of size 5.
+
+    >>> smirnov(5, [0, 0.5, 1.0])
+    array([ 1.   ,  0.056,  0.   ])
+
+    Compare a sample of size 5 against N(0, 1), the standard normal
+    distribution with mean 0 and standard deviation 1.
+
+    `x` is the sample.
+
+    >>> x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82])
+
+    >>> target = norm(0, 1)
+    >>> cdfs = target.cdf(x)
+    >>> cdfs
+    array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ])
+
+    Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn).
+
+    >>> n = len(x)
+    >>> ecdfs = np.arange(n+1, dtype=float)/n
+    >>> cols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n],
+    ...                        ecdfs[1:] - cdfs])
+    >>> with np.printoptions(precision=3):
+    ...    print(cols)
+    [[-1.392  0.2    0.082  0.082  0.118]
+     [-0.135  0.4    0.446  0.246 -0.046]
+     [ 0.114  0.6    0.545  0.145  0.055]
+     [ 0.19   0.8    0.575 -0.025  0.225]
+     [ 1.82   1.     0.966  0.166  0.034]]
+    >>> gaps = cols[:, -2:]
+    >>> Dnpm = np.max(gaps, axis=0)
+    >>> print(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}')
+    Dn-=0.246306, Dn+=0.224655
+    >>> probs = smirnov(n, Dnpm)
+    >>> print(f'For a sample of size {n} drawn from N(0, 1):',
+    ...       f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}',
+    ...       f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}',
+    ...       sep='\n')
+    For a sample of size 5 drawn from N(0, 1):
+     Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711
+     Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245
+
+    Plot the empirical CDF and the standard normal CDF.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.step(np.concatenate(([-2.5], x, [2.5])),
+    ...          np.concatenate((ecdfs, [1])),
+    ...          where='post', label='Empirical CDF')
+    >>> xx = np.linspace(-2.5, 2.5, 100)
+    >>> plt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)')
+
+    Add vertical lines marking Dn+ and Dn-.
+
+    >>> iminus, iplus = np.argmax(gaps, axis=0)
+    >>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r',
+    ...            alpha=0.5, lw=4)
+    >>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m',
+    ...            alpha=0.5, lw=4)
+
+    >>> plt.grid(True)
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.show()
+    """)
+
+add_newdoc("smirnovi",
+    """
+    smirnovi(n, p, out=None)
+
+    Inverse to `smirnov`
+
+    Returns `d` such that ``smirnov(n, d) == p``, the critical value
+    corresponding to `p`.
+
+    Parameters
+    ----------
+    n : int
+      Number of samples
+    p : float array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of smirnovi(n, p), the critical values.
+
+    See Also
+    --------
+    smirnov : The Survival Function (SF) for the distribution
+    scipy.stats.ksone : Provides the functionality as a continuous distribution
+    kolmogorov, kolmogi : Functions for the two-sided distribution
+    scipy.stats.kstwobign : Two-sided Kolmogorov-Smirnov distribution, large n
+
+    Notes
+    -----
+    `smirnov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.ksone` distribution.
+
+    Examples
+    --------
+    >>> from scipy.special import smirnovi, smirnov
+
+    >>> n = 24
+    >>> deviations = [0.1, 0.2, 0.3]
+
+    Use `smirnov` to compute the complementary CDF of the Smirnov
+    distribution for the given number of samples and deviations.
+
+    >>> p = smirnov(n, deviations)
+    >>> p
+    array([0.58105083, 0.12826832, 0.01032231])
+
+    The inverse function ``smirnovi(n, p)`` returns ``deviations``.
+
+    >>> smirnovi(n, p)
+    array([0.1, 0.2, 0.3])
+
+    """)
+
+add_newdoc("_smirnovc",
+    """
+    _smirnovc(n, d)
+     Internal function, do not use.
+    """)
+
+add_newdoc("_smirnovci",
+    """
+     Internal function, do not use.
+    """)
+
+add_newdoc("_smirnovp",
+    """
+    _smirnovp(n, p)
+     Internal function, do not use.
+    """)
+
+add_newdoc("spence",
+    r"""
+    spence(z, out=None)
+
+    Spence's function, also known as the dilogarithm.
+
+    It is defined to be
+
+    .. math::
+      \int_1^z \frac{\log(t)}{1 - t}dt
+
+    for complex :math:`z`, where the contour of integration is taken
+    to avoid the branch cut of the logarithm. Spence's function is
+    analytic everywhere except the negative real axis where it has a
+    branch cut.
+
+    Parameters
+    ----------
+    z : array_like
+        Points at which to evaluate Spence's function
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    s : scalar or ndarray
+        Computed values of Spence's function
+
+    Notes
+    -----
+    There is a different convention which defines Spence's function by
+    the integral
+
+    .. math::
+      -\int_0^z \frac{\log(1 - t)}{t}dt;
+
+    this is our ``spence(1 - z)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import spence
+    >>> import matplotlib.pyplot as plt
+
+    The function is defined for complex inputs:
+
+    >>> spence([1-1j, 1.5+2j, 3j, -10-5j])
+    array([-0.20561676+0.91596559j, -0.86766909-1.39560134j,
+           -0.59422064-2.49129918j, -1.14044398+6.80075924j])
+
+    For complex inputs on the branch cut, which is the negative real axis,
+    the function returns the limit for ``z`` with positive imaginary part.
+    For example, in the following, note the sign change of the imaginary
+    part of the output for ``z = -2`` and ``z = -2 - 1e-8j``:
+
+    >>> spence([-2 + 1e-8j, -2, -2 - 1e-8j])
+    array([2.32018041-3.45139229j, 2.32018042-3.4513923j ,
+           2.32018041+3.45139229j])
+
+    The function returns ``nan`` for real inputs on the branch cut:
+
+    >>> spence(-1.5)
+    nan
+
+    Verify some particular values: ``spence(0) = pi**2/6``,
+    ``spence(1) = 0`` and ``spence(2) = -pi**2/12``.
+
+    >>> spence([0, 1, 2])
+    array([ 1.64493407,  0.        , -0.82246703])
+    >>> np.pi**2/6, -np.pi**2/12
+    (1.6449340668482264, -0.8224670334241132)
+
+    Verify the identity::
+
+        spence(z) + spence(1 - z) = pi**2/6 - log(z)*log(1 - z)
+
+    >>> z = 3 + 4j
+    >>> spence(z) + spence(1 - z)
+    (-2.6523186143876067+1.8853470951513935j)
+    >>> np.pi**2/6 - np.log(z)*np.log(1 - z)
+    (-2.652318614387606+1.885347095151394j)
+
+    Plot the function for positive real input.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0, 6, 400)
+    >>> ax.plot(x, spence(x))
+    >>> ax.grid()
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('spence(x)')
+    >>> plt.show()
+    """)
+
+add_newdoc(
+    "stdtr",
+    r"""
+    stdtr(df, t, out=None)
+
+    Student t distribution cumulative distribution function
+
+    Returns the integral:
+
+    .. math::
+        \frac{\Gamma((df+1)/2)}{\sqrt{\pi df} \Gamma(df/2)}
+        \int_{-\infty}^t (1+x^2/df)^{-(df+1)/2}\, dx
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom
+    t : array_like
+        Upper bound of the integral
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Student t CDF at t
+
+    See Also
+    --------
+    stdtridf : inverse of stdtr with respect to `df`
+    stdtrit : inverse of stdtr with respect to `t`
+    scipy.stats.t : student t distribution
+
+    Notes
+    -----
+    The student t distribution is also available as `scipy.stats.t`.
+    Calling `stdtr` directly can improve performance compared to the
+    ``cdf`` method of `scipy.stats.t` (see last example below).
+
+    Examples
+    --------
+    Calculate the function for ``df=3`` at ``t=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import stdtr
+    >>> import matplotlib.pyplot as plt
+    >>> stdtr(3, 1)
+    0.8044988905221148
+
+    Plot the function for three different degrees of freedom.
+
+    >>> x = np.linspace(-10, 10, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> parameters = [(1, "solid"), (3, "dashed"), (10, "dotted")]
+    >>> for (df, linestyle) in parameters:
+    ...     ax.plot(x, stdtr(df, x), ls=linestyle, label=f"$df={df}$")
+    >>> ax.legend()
+    >>> ax.set_title("Student t distribution cumulative distribution function")
+    >>> plt.show()
+
+    The function can be computed for several degrees of freedom at the same
+    time by providing a NumPy array or list for `df`:
+
+    >>> stdtr([1, 2, 3], 1)
+    array([0.75      , 0.78867513, 0.80449889])
+
+    It is possible to calculate the function at several points for several
+    different degrees of freedom simultaneously by providing arrays for `df`
+    and `t` with shapes compatible for broadcasting. Compute `stdtr` at
+    4 points for 3 degrees of freedom resulting in an array of shape 3x4.
+
+    >>> dfs = np.array([[1], [2], [3]])
+    >>> t = np.array([2, 4, 6, 8])
+    >>> dfs.shape, t.shape
+    ((3, 1), (4,))
+
+    >>> stdtr(dfs, t)
+    array([[0.85241638, 0.92202087, 0.94743154, 0.96041658],
+           [0.90824829, 0.97140452, 0.98666426, 0.99236596],
+           [0.93033702, 0.98599577, 0.99536364, 0.99796171]])
+
+    The t distribution is also available as `scipy.stats.t`. Calling `stdtr`
+    directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.t`. To get the same results, one must use the following
+    parametrization: ``scipy.stats.t(df).cdf(x) = stdtr(df, x)``.
+
+    >>> from scipy.stats import t
+    >>> df, x = 3, 1
+    >>> stdtr_result = stdtr(df, x)  # this can be faster than below
+    >>> stats_result = t(df).cdf(x)
+    >>> stats_result == stdtr_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("stdtridf",
+    """
+    stdtridf(p, t, out=None)
+
+    Inverse of `stdtr` vs df
+
+    Returns the argument df such that stdtr(df, t) is equal to `p`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    t : array_like
+        Upper bound of the integral
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        Value of `df` such that ``stdtr(df, t) == p``
+
+    See Also
+    --------
+    stdtr : Student t CDF
+    stdtrit : inverse of stdtr with respect to `t`
+    scipy.stats.t : Student t distribution
+
+    Examples
+    --------
+    Compute the student t cumulative distribution function for one
+    parameter set.
+
+    >>> from scipy.special import stdtr, stdtridf
+    >>> df, x = 5, 2
+    >>> cdf_value = stdtr(df, x)
+    >>> cdf_value
+    0.9490302605850709
+
+    Verify that `stdtridf` recovers the original value for `df` given
+    the CDF value and `x`.
+
+    >>> stdtridf(cdf_value, x)
+    5.0
+    """)
+
+add_newdoc("stdtrit",
+    """
+    stdtrit(df, p, out=None)
+
+    The `p`-th quantile of the student t distribution.
+
+    This function is the inverse of the student t distribution cumulative
+    distribution function (CDF), returning `t` such that `stdtr(df, t) = p`.
+
+    Returns the argument `t` such that stdtr(df, t) is equal to `p`.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom
+    p : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t : scalar or ndarray
+        Value of `t` such that ``stdtr(df, t) == p``
+
+    See Also
+    --------
+    stdtr : Student t CDF
+    stdtridf : inverse of stdtr with respect to `df`
+    scipy.stats.t : Student t distribution
+
+    Notes
+    -----
+    The student t distribution is also available as `scipy.stats.t`. Calling
+    `stdtrit` directly can improve performance compared to the ``ppf``
+    method of `scipy.stats.t` (see last example below).
+
+    Examples
+    --------
+    `stdtrit` represents the inverse of the student t distribution CDF which
+    is available as `stdtr`. Here, we calculate the CDF for ``df`` at
+    ``x=1``. `stdtrit` then returns ``1`` up to floating point errors
+    given the same value for `df` and the computed CDF value.
+
+    >>> import numpy as np
+    >>> from scipy.special import stdtr, stdtrit
+    >>> import matplotlib.pyplot as plt
+    >>> df = 3
+    >>> x = 1
+    >>> cdf_value = stdtr(df, x)
+    >>> stdtrit(df, cdf_value)
+    0.9999999994418539
+
+    Plot the function for three different degrees of freedom.
+
+    >>> x = np.linspace(0, 1, 1000)
+    >>> parameters = [(1, "solid"), (2, "dashed"), (5, "dotted")]
+    >>> fig, ax = plt.subplots()
+    >>> for (df, linestyle) in parameters:
+    ...     ax.plot(x, stdtrit(df, x), ls=linestyle, label=f"$df={df}$")
+    >>> ax.legend()
+    >>> ax.set_ylim(-10, 10)
+    >>> ax.set_title("Student t distribution quantile function")
+    >>> plt.show()
+
+    The function can be computed for several degrees of freedom at the same
+    time by providing a NumPy array or list for `df`:
+
+    >>> stdtrit([1, 2, 3], 0.7)
+    array([0.72654253, 0.6172134 , 0.58438973])
+
+    It is possible to calculate the function at several points for several
+    different degrees of freedom simultaneously by providing arrays for `df`
+    and `p` with shapes compatible for broadcasting. Compute `stdtrit` at
+    4 points for 3 degrees of freedom resulting in an array of shape 3x4.
+
+    >>> dfs = np.array([[1], [2], [3]])
+    >>> p = np.array([0.2, 0.4, 0.7, 0.8])
+    >>> dfs.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> stdtrit(dfs, p)
+    array([[-1.37638192, -0.3249197 ,  0.72654253,  1.37638192],
+           [-1.06066017, -0.28867513,  0.6172134 ,  1.06066017],
+           [-0.97847231, -0.27667066,  0.58438973,  0.97847231]])
+
+    The t distribution is also available as `scipy.stats.t`. Calling `stdtrit`
+    directly can be much faster than calling the ``ppf`` method of
+    `scipy.stats.t`. To get the same results, one must use the following
+    parametrization: ``scipy.stats.t(df).ppf(x) = stdtrit(df, x)``.
+
+    >>> from scipy.stats import t
+    >>> df, x = 3, 0.5
+    >>> stdtrit_result = stdtrit(df, x)  # this can be faster than below
+    >>> stats_result = t(df).ppf(x)
+    >>> stats_result == stdtrit_result  # test that results are equal
+    True
+    """)
+
+add_newdoc(
+    "tklmbda",
+    r"""
+    tklmbda(x, lmbda, out=None)
+
+    Cumulative distribution function of the Tukey lambda distribution.
+
+    Parameters
+    ----------
+    x, lmbda : array_like
+        Parameters
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        Value of the Tukey lambda CDF
+
+    See Also
+    --------
+    scipy.stats.tukeylambda : Tukey lambda distribution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import tklmbda, expit
+
+    Compute the cumulative distribution function (CDF) of the Tukey lambda
+    distribution at several ``x`` values for `lmbda` = -1.5.
+
+    >>> x = np.linspace(-2, 2, 9)
+    >>> x
+    array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])
+    >>> tklmbda(x, -1.5)
+    array([0.34688734, 0.3786554 , 0.41528805, 0.45629737, 0.5       ,
+           0.54370263, 0.58471195, 0.6213446 , 0.65311266])
+
+    When `lmbda` is 0, the function is the logistic sigmoid function,
+    which is implemented in `scipy.special` as `expit`.
+
+    >>> tklmbda(x, 0)
+    array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,
+           0.62245933, 0.73105858, 0.81757448, 0.88079708])
+    >>> expit(x)
+    array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,
+           0.62245933, 0.73105858, 0.81757448, 0.88079708])
+
+    When `lmbda` is 1, the Tukey lambda distribution is uniform on the
+    interval [-1, 1], so the CDF increases linearly.
+
+    >>> t = np.linspace(-1, 1, 9)
+    >>> tklmbda(t, 1)
+    array([0.   , 0.125, 0.25 , 0.375, 0.5  , 0.625, 0.75 , 0.875, 1.   ])
+
+    In the following, we generate plots for several values of `lmbda`.
+
+    The first figure shows graphs for `lmbda` <= 0.
+
+    >>> styles = ['-', '-.', '--', ':']
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-12, 12, 500)
+    >>> for k, lmbda in enumerate([-1.0, -0.5, 0.0]):
+    ...     y = tklmbda(x, lmbda)
+    ...     ax.plot(x, y, styles[k], label=rf'$\lambda$ = {lmbda:-4.1f}')
+
+    >>> ax.set_title(r'tklmbda(x, $\lambda$)')
+    >>> ax.set_label('x')
+    >>> ax.legend(framealpha=1, shadow=True)
+    >>> ax.grid(True)
+
+    The second figure shows graphs for `lmbda` > 0.  The dots in the
+    graphs show the bounds of the support of the distribution.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-4.2, 4.2, 500)
+    >>> lmbdas = [0.25, 0.5, 1.0, 1.5]
+    >>> for k, lmbda in enumerate(lmbdas):
+    ...     y = tklmbda(x, lmbda)
+    ...     ax.plot(x, y, styles[k], label=fr'$\lambda$ = {lmbda}')
+
+    >>> ax.set_prop_cycle(None)
+    >>> for lmbda in lmbdas:
+    ...     ax.plot([-1/lmbda, 1/lmbda], [0, 1], '.', ms=8)
+
+    >>> ax.set_title(r'tklmbda(x, $\lambda$)')
+    >>> ax.set_xlabel('x')
+    >>> ax.legend(framealpha=1, shadow=True)
+    >>> ax.grid(True)
+
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    The CDF of the Tukey lambda distribution is also implemented as the
+    ``cdf`` method of `scipy.stats.tukeylambda`.  In the following,
+    ``tukeylambda.cdf(x, -0.5)`` and ``tklmbda(x, -0.5)`` compute the
+    same values:
+
+    >>> from scipy.stats import tukeylambda
+    >>> x = np.linspace(-2, 2, 9)
+
+    >>> tukeylambda.cdf(x, -0.5)
+    array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,
+           0.58671839, 0.66458323, 0.72906142, 0.78004843])
+
+    >>> tklmbda(x, -0.5)
+    array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,
+           0.58671839, 0.66458323, 0.72906142, 0.78004843])
+
+    The implementation in ``tukeylambda`` also provides location and scale
+    parameters, and other methods such as ``pdf()`` (the probability
+    density function) and ``ppf()`` (the inverse of the CDF), so for
+    working with the Tukey lambda distribution, ``tukeylambda`` is more
+    generally useful.  The primary advantage of ``tklmbda`` is that it is
+    significantly faster than ``tukeylambda.cdf``.
+    """)
+
+add_newdoc("wofz",
+    """
+    wofz(z, out=None)
+
+    Faddeeva function
+
+    Returns the value of the Faddeeva function for complex argument::
+
+        exp(-z**2) * erfc(-i*z)
+
+    Parameters
+    ----------
+    z : array_like
+        complex argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Faddeeva function
+
+    See Also
+    --------
+    dawsn, erf, erfc, erfcx, erfi
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-3, 3)
+    >>> z = special.wofz(x)
+
+    >>> plt.plot(x, z.real, label='wofz(x).real')
+    >>> plt.plot(x, z.imag, label='wofz(x).imag')
+    >>> plt.xlabel('$x$')
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.grid(alpha=0.25)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("xlogy",
+    """
+    xlogy(x, y, out=None)
+
+    Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Multiplier
+    y : array_like
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    z : scalar or ndarray
+        Computed x*log(y)
+
+    Notes
+    -----
+    The log function used in the computation is the natural log.
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    We can use this function to calculate the binary logistic loss also
+    known as the binary cross entropy. This loss function is used for
+    binary classification problems and is defined as:
+
+    .. math::
+        L = 1/n * \\sum_{i=0}^n -(y_i*log(y\\_pred_i) + (1-y_i)*log(1-y\\_pred_i))
+
+    We can define the parameters `x` and `y` as y and y_pred respectively.
+    y is the array of the actual labels which over here can be either 0 or 1.
+    y_pred is the array of the predicted probabilities with respect to
+    the positive class (1).
+
+    >>> import numpy as np
+    >>> from scipy.special import xlogy
+    >>> y = np.array([0, 1, 0, 1, 1, 0])
+    >>> y_pred = np.array([0.3, 0.8, 0.4, 0.7, 0.9, 0.2])
+    >>> n = len(y)
+    >>> loss = -(xlogy(y, y_pred) + xlogy(1 - y, 1 - y_pred)).sum()
+    >>> loss /= n
+    >>> loss
+    0.29597052165495025
+
+    A lower loss is usually better as it indicates that the predictions are
+    similar to the actual labels. In this example since our predicted
+    probabilities are close to the actual labels, we get an overall loss
+    that is reasonably low and appropriate.
+
+    """)
+
+add_newdoc("xlog1py",
+    """
+    xlog1py(x, y, out=None)
+
+    Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Multiplier
+    y : array_like
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    z : scalar or ndarray
+        Computed x*log1p(y)
+
+    Notes
+    -----
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    This example shows how the function can be used to calculate the log of
+    the probability mass function for a geometric discrete random variable.
+    The probability mass function of the geometric distribution is defined
+    as follows:
+
+    .. math:: f(k) = (1-p)^{k-1} p
+
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure
+    and :math:`k` is the number of trials to get the first success.
+
+    >>> import numpy as np
+    >>> from scipy.special import xlog1py
+    >>> p = 0.5
+    >>> k = 100
+    >>> _pmf = np.power(1 - p, k - 1) * p
+    >>> _pmf
+    7.888609052210118e-31
+
+    If we take k as a relatively large number the value of the probability
+    mass function can become very low. In such cases taking the log of the
+    pmf would be more suitable as the log function can change the values
+    to a scale that is more appropriate to work with.
+
+    >>> _log_pmf = xlog1py(k - 1, -p) + np.log(p)
+    >>> _log_pmf
+    -69.31471805599453
+
+    We can confirm that we get a value close to the original pmf value by
+    taking the exponential of the log pmf.
+
+    >>> _orig_pmf = np.exp(_log_pmf)
+    >>> np.isclose(_pmf, _orig_pmf)
+    True
+
+    """)
+
+add_newdoc("yn",
+    r"""
+    yn(n, x, out=None)
+
+    Bessel function of the second kind of integer order and real argument.
+
+    Parameters
+    ----------
+    n : array_like
+        Order (integer).
+    x : array_like
+        Argument (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the Bessel function, :math:`Y_n(x)`.
+
+    See Also
+    --------
+    yv : For real order and real or complex argument.
+    y0: faster implementation of this function for order 0
+    y1: faster implementation of this function for order 1
+
+    Notes
+    -----
+    Wrapper for the Cephes [1]_ routine `yn`.
+
+    The function is evaluated by forward recurrence on `n`, starting with
+    values computed by the Cephes routines `y0` and `y1`. If ``n = 0`` or 1,
+    the routine for `y0` or `y1` is called directly.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import yn
+    >>> yn(0, 1.)
+    0.08825696421567697
+
+    Evaluate the function at one point for different orders.
+
+    >>> yn(0, 1.), yn(1, 1.), yn(2, 1.)
+    (0.08825696421567697, -0.7812128213002888, -1.6506826068162546)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> yn([0, 1, 2], 1.)
+    array([ 0.08825696, -0.78121282, -1.65068261])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 3., 8.])
+    >>> yn(0, points)
+    array([-0.44451873,  0.37685001,  0.22352149])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> yn(orders, points)
+    array([[-0.44451873,  0.37685001,  0.22352149],
+           [-1.47147239,  0.32467442, -0.15806046]])
+
+    Plot the functions of order 0 to 3 from 0 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, yn(i, x), label=f'$Y_{i!r}$')
+    >>> ax.set_ylim(-3, 1)
+    >>> ax.legend()
+    >>> plt.show()
+    """)
+
+add_newdoc("yv",
+    r"""
+    yv(v, z, out=None)
+
+    Bessel function of the second kind of real order and complex argument.
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the Bessel function of the second kind, :math:`Y_v(x)`.
+
+    See Also
+    --------
+    yve : :math:`Y_v` with leading exponential behavior stripped off.
+    y0: faster implementation of this function for order 0
+    y1: faster implementation of this function for order 1
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the
+    AMOS [1]_ `zbesy` routine, which exploits the connection to the Hankel
+    Bessel functions :math:`H_v^{(1)}` and :math:`H_v^{(2)}`,
+
+    .. math:: Y_v(z) = \frac{1}{2\imath} (H_v^{(1)} - H_v^{(2)}).
+
+    For negative `v` values the formula,
+
+    .. math:: Y_{-v}(z) = Y_v(z) \cos(\pi v) + J_v(z) \sin(\pi v)
+
+    is used, where :math:`J_v(z)` is the Bessel function of the first kind,
+    computed using the AMOS routine `zbesj`.  Note that the second term is
+    exactly zero for integer `v`; to improve accuracy the second term is
+    explicitly omitted for `v` values such that `v = floor(v)`.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import yv
+    >>> yv(0, 1.)
+    0.088256964215677
+
+    Evaluate the function at one point for different orders.
+
+    >>> yv(0, 1.), yv(1, 1.), yv(1.5, 1.)
+    (0.088256964215677, -0.7812128213002889, -1.102495575160179)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> yv([0, 1, 1.5], 1.)
+    array([ 0.08825696, -0.78121282, -1.10249558])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 3., 8.])
+    >>> yv(0, points)
+    array([-0.44451873,  0.37685001,  0.22352149])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> yv(orders, points)
+    array([[-0.44451873,  0.37685001,  0.22352149],
+           [-1.47147239,  0.32467442, -0.15806046]])
+
+    Plot the functions of order 0 to 3 from 0 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, yv(i, x), label=f'$Y_{i!r}$')
+    >>> ax.set_ylim(-3, 1)
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("yve",
+    r"""
+    yve(v, z, out=None)
+
+    Exponentially scaled Bessel function of the second kind of real order.
+
+    Returns the exponentially scaled Bessel function of the second
+    kind of real order `v` at complex `z`::
+
+        yve(v, z) = yv(v, z) * exp(-abs(z.imag))
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the exponentially scaled Bessel function.
+
+    See Also
+    --------
+    yv: Unscaled Bessel function of the second kind of real order.
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the
+    AMOS [1]_ `zbesy` routine, which exploits the connection to the Hankel
+    Bessel functions :math:`H_v^{(1)}` and :math:`H_v^{(2)}`,
+
+    .. math:: Y_v(z) = \frac{1}{2\imath} (H_v^{(1)} - H_v^{(2)}).
+
+    For negative `v` values the formula,
+
+    .. math:: Y_{-v}(z) = Y_v(z) \cos(\pi v) + J_v(z) \sin(\pi v)
+
+    is used, where :math:`J_v(z)` is the Bessel function of the first kind,
+    computed using the AMOS routine `zbesj`.  Note that the second term is
+    exactly zero for integer `v`; to improve accuracy the second term is
+    explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Exponentially scaled Bessel functions are useful for large `z`:
+    for these, the unscaled Bessel functions can easily under-or overflow.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compare the output of `yv` and `yve` for large complex arguments for `z`
+    by computing their values for order ``v=1`` at ``z=1000j``. We see that
+    `yv` returns nan but `yve` returns a finite number:
+
+    >>> import numpy as np
+    >>> from scipy.special import yv, yve
+    >>> v = 1
+    >>> z = 1000j
+    >>> yv(v, z), yve(v, z)
+    ((nan+nanj), (-0.012610930256928629+7.721967686709076e-19j))
+
+    For real arguments for `z`, `yve` returns the same as `yv` up to
+    floating point errors.
+
+    >>> v, z = 1, 1000
+    >>> yv(v, z), yve(v, z)
+    (-0.02478433129235178, -0.02478433129235179)
+
+    The function can be evaluated for several orders at the same time by
+    providing a list or NumPy array for `v`:
+
+    >>> yve([1, 2, 3], 1j)
+    array([-0.20791042+0.14096627j,  0.38053618-0.04993878j,
+           0.00815531-1.66311097j])
+
+    In the same way, the function can be evaluated at several points in one
+    call by providing a list or NumPy array for `z`:
+
+    >>> yve(1, np.array([1j, 2j, 3j]))
+    array([-0.20791042+0.14096627j, -0.21526929+0.01205044j,
+           -0.19682671+0.00127278j])
+
+    It is also possible to evaluate several orders at several points
+    at the same time by providing arrays for `v` and `z` with
+    broadcasting compatible shapes. Compute `yve` for two different orders
+    `v` and three points `z` resulting in a 2x3 array.
+
+    >>> v = np.array([[1], [2]])
+    >>> z = np.array([3j, 4j, 5j])
+    >>> v.shape, z.shape
+    ((2, 1), (3,))
+
+    >>> yve(v, z)
+    array([[-1.96826713e-01+1.27277544e-03j, -1.78750840e-01+1.45558819e-04j,
+            -1.63972267e-01+1.73494110e-05j],
+           [1.94960056e-03-1.11782545e-01j,  2.02902325e-04-1.17626501e-01j,
+            2.27727687e-05-1.17951906e-01j]])
+    """)
+
+add_newdoc("_struve_asymp_large_z",
+    """
+    _struve_asymp_large_z(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using asymptotic expansion
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_struve_power_series",
+    """
+    _struve_power_series(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using power series
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_struve_bessel_series",
+    """
+    _struve_bessel_series(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using Bessel function series
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_spherical_jn",
+    """
+    Internal function, use `spherical_jn` instead.
+    """)
+
+add_newdoc("_spherical_jn_d",
+    """
+    Internal function, use `spherical_jn` instead.
+    """)
+
+add_newdoc("_spherical_yn",
+    """
+    Internal function, use `spherical_yn` instead.
+    """)
+
+add_newdoc("_spherical_yn_d",
+    """
+    Internal function, use `spherical_yn` instead.
+    """)
+
+add_newdoc("_spherical_in",
+    """
+    Internal function, use `spherical_in` instead.
+    """)
+
+add_newdoc("_spherical_in_d",
+    """
+    Internal function, use `spherical_in` instead.
+    """)
+
+add_newdoc("_spherical_kn",
+    """
+    Internal function, use `spherical_kn` instead.
+    """)
+
+add_newdoc("_spherical_kn_d",
+    """
+    Internal function, use `spherical_kn` instead.
+    """)
+
+add_newdoc("owens_t",
+    """
+    owens_t(h, a, out=None)
+
+    Owen's T Function.
+
+    The function T(h, a) gives the probability of the event
+    (X > h and 0 < Y < a * X) where X and Y are independent
+    standard normal random variables.
+
+    Parameters
+    ----------
+    h: array_like
+        Input value.
+    a: array_like
+        Input value.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t: scalar or ndarray
+        Probability of the event (X > h and 0 < Y < a * X),
+        where X and Y are independent standard normal random variables.
+
+    References
+    ----------
+    .. [1] M. Patefield and D. Tandy, "Fast and accurate calculation of
+           Owen's T Function", Statistical Software vol. 5, pp. 1-25, 2000.
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> a = 3.5
+    >>> h = 0.78
+    >>> special.owens_t(h, a)
+    0.10877216734852274
+    """)
+
+add_newdoc("_factorial",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("ndtri_exp",
+    r"""
+    ndtri_exp(y, out=None)
+
+    Inverse of `log_ndtr` vs x. Allows for greater precision than
+    `ndtri` composed with `numpy.exp` for very small values of y and for
+    y close to 0.
+
+    Parameters
+    ----------
+    y : array_like of float
+        Function argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Inverse of the log CDF of the standard normal distribution, evaluated
+        at y.
+
+    See Also
+    --------
+    log_ndtr : log of the standard normal cumulative distribution function
+    ndtr : standard normal cumulative distribution function
+    ndtri : standard normal percentile function
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    `ndtri_exp` agrees with the naive implementation when the latter does
+    not suffer from underflow.
+
+    >>> sc.ndtri_exp(-1)
+    -0.33747496376420244
+    >>> sc.ndtri(np.exp(-1))
+    -0.33747496376420244
+
+    For extreme values of y, the naive approach fails
+
+    >>> sc.ndtri(np.exp(-800))
+    -inf
+    >>> sc.ndtri(np.exp(-1e-20))
+    inf
+
+    whereas `ndtri_exp` is still able to compute the result to high precision.
+
+    >>> sc.ndtri_exp(-800)
+    -39.88469483825668
+    >>> sc.ndtri_exp(-1e-20)
+    9.262340089798409
+    """)
+
+
+add_newdoc("_stirling2_inexact",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc(
+    "_beta_pdf",
+    r"""
+    _beta_pdf(x, a, b)
+
+    Probability density function of beta distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    a, b : array_like
+           Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_beta_ppf",
+    r"""
+    _beta_ppf(x, a, b)
+
+    Percent point function of beta distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    a, b : array_like
+           Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_invgauss_ppf",
+    """
+    _invgauss_ppf(x, mu)
+
+    Percent point function of inverse gaussian distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    mu : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_invgauss_isf",
+    """
+    _invgauss_isf(x, mu, s)
+
+    Inverse survival function of inverse gaussian distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    mu : array_like
+        Positive, real-valued parameters
+    s : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_cauchy_ppf",
+    """
+    _cauchy_ppf(p, loc, scale)
+
+    Percent point function (i.e. quantile) of the Cauchy distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probabilities
+    loc : array_like
+        Location parameter of the distribution.
+    scale : array_like
+        Scale parameter of the distribution.
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_cauchy_isf",
+    """
+    _cauchy_isf(p, loc, scale)
+
+    Inverse survival function of the Cauchy distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probabilities
+    loc : array_like
+        Location parameter of the distribution.
+    scale : array_like
+        Scale parameter of the distribution.
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_pdf",
+    """
+    _ncx2_pdf(x, k, l)
+
+    Probability density function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_cdf",
+    """
+    _ncx2_cdf(x, k, l)
+
+    Cumulative density function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_ppf",
+    """
+    _ncx2_ppf(x, k, l)
+
+    Percent point function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_sf",
+    """
+    _ncx2_sf(x, k, l)
+
+    Survival function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_isf",
+    """
+    _ncx2_isf(x, k, l)
+
+    Inverse survival function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_pdf",
+    """
+    _ncf_pdf(x, v1, v2, l)
+
+    Probability density function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_cdf",
+    """
+    _ncf_cdf(x, v1, v2, l)
+
+    Cumulative density function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_ppf",
+    """
+    _ncf_ppf(x, v1, v2, l)
+
+    Percent point function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_sf",
+    """
+    _ncf_sf(x, v1, v2, l)
+
+    Survival function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_isf",
+    """
+    _ncf_isf(x, v1, v2, l)
+
+    Inverse survival function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_mean",
+    """
+    _ncf_mean(v1, v2, l)
+
+    Mean of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_variance",
+    """
+    _ncf_variance(v1, v2, l)
+
+    Variance of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_skewness",
+    """
+    _ncf_skewness(v1, v2, l)
+
+    Skewness of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_kurtosis_excess",
+    """
+    _ncf_kurtosis_excess(v1, v2, l)
+
+    Kurtosis excess of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_cdf",
+    """
+    _nct_cdf(x, v, l)
+
+    Cumulative density function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_pdf",
+    """
+    _nct_pdf(x, v, l)
+
+    Probability density function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+
+add_newdoc(
+    "_nct_ppf",
+    """
+    _nct_ppf(x, v, l)
+
+    Percent point function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_sf",
+    """
+    _nct_sf(x, v, l)
+
+    Survival function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_isf",
+    """
+    _nct_isf(x, v, l)
+
+    Inverse survival function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_mean",
+    """
+    _nct_mean(v, l)
+
+    Mean of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_variance",
+    """
+    _nct_variance(v, l)
+
+    Variance of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_skewness",
+    """
+    _nct_skewness(v, l)
+
+    Skewness of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_kurtosis_excess",
+    """
+    _nct_kurtosis_excess(v, l)
+
+    Kurtosis excess of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_cdf",
+    """
+    _skewnorm_cdf(x, l, sc, sh)
+
+    Cumulative density function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_ppf",
+    """
+    _skewnorm_ppf(x, l, sc, sh)
+
+    Percent point function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_isf",
+    """
+    _skewnorm_isf(x, l, sc, sh)
+
+    Inverse survival function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_pmf",
+    """
+    _binom_pmf(x, n, p)
+
+    Probability mass function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_cdf",
+    """
+    _binom_cdf(x, n, p)
+
+    Cumulative density function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_ppf",
+    """
+    _binom_ppf(x, n, p)
+
+    Percent point function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_sf",
+    """
+    _binom_sf(x, n, p)
+
+    Survival function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_isf",
+    """
+    _binom_isf(x, n, p)
+
+    Inverse survival function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_pmf",
+    """
+    _nbinom_pmf(x, r, p)
+
+    Probability mass function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_cdf",
+    """
+    _nbinom_cdf(x, r, p)
+
+    Cumulative density function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_ppf",
+    """
+    _nbinom_ppf(x, r, p)
+
+    Percent point function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_sf",
+    """
+    _nbinom_sf(x, r, p)
+
+    Survival function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_isf",
+    """
+    _nbinom_isf(x, r, p)
+
+    Inverse survival function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_mean",
+    """
+    _nbinom_mean(r, p)
+
+    Mean of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_variance",
+    """
+    _nbinom_variance(r, p)
+
+    Variance of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_skewness",
+    """
+    _nbinom_skewness(r, p)
+
+    Skewness of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_kurtosis_excess",
+    """
+    _nbinom_kurtosis_excess(r, p)
+
+    Kurtosis excess of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_pmf",
+    """
+    _hypergeom_pmf(x, r, N, M)
+
+    Probability mass function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_cdf",
+    """
+    _hypergeom_cdf(x, r, N, M)
+
+    Cumulative density function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_hypergeom_sf",
+    """
+    _hypergeom_sf(x, r, N, M)
+
+    Survival function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_hypergeom_mean",
+    """
+    _hypergeom_mean(r, N, M)
+
+    Mean of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_variance",
+    """
+    _hypergeom_variance(r, N, M)
+
+    Mean of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_skewness",
+    """
+    _hypergeom_skewness(r, N, M)
+
+    Skewness of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..76b13b309eed0c036dd226ff96f0e020f296e032
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_basic.py
@@ -0,0 +1,3579 @@
+#
+# Author:  Travis Oliphant, 2002
+#
+
+import numpy as np
+import math
+import warnings
+from collections import defaultdict
+from heapq import heapify, heappop
+from numpy import (pi, asarray, floor, isscalar, sqrt, where,
+                   sin, place, issubdtype, extract, inexact, nan, zeros, sinc)
+
+from . import _ufuncs
+from ._ufuncs import (mathieu_a, mathieu_b, iv, jv, gamma, rgamma,
+                      psi, hankel1, hankel2, yv, kv, poch, binom,
+                      _stirling2_inexact)
+
+from ._gufuncs import _lqn, _lqmn, _rctj, _rcty
+from ._input_validation import _nonneg_int_or_fail
+from . import _specfun
+from ._comb import _comb_int
+from ._multiufuncs import (assoc_legendre_p_all,
+                           legendre_p_all)
+from scipy._lib.deprecation import _deprecated
+
+
+__all__ = [
+    'ai_zeros',
+    'assoc_laguerre',
+    'bei_zeros',
+    'beip_zeros',
+    'ber_zeros',
+    'bernoulli',
+    'berp_zeros',
+    'bi_zeros',
+    'clpmn',
+    'comb',
+    'digamma',
+    'diric',
+    'erf_zeros',
+    'euler',
+    'factorial',
+    'factorial2',
+    'factorialk',
+    'fresnel_zeros',
+    'fresnelc_zeros',
+    'fresnels_zeros',
+    'h1vp',
+    'h2vp',
+    'ivp',
+    'jn_zeros',
+    'jnjnp_zeros',
+    'jnp_zeros',
+    'jnyn_zeros',
+    'jvp',
+    'kei_zeros',
+    'keip_zeros',
+    'kelvin_zeros',
+    'ker_zeros',
+    'kerp_zeros',
+    'kvp',
+    'lmbda',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'lqn',
+    'mathieu_even_coef',
+    'mathieu_odd_coef',
+    'obl_cv_seq',
+    'pbdn_seq',
+    'pbdv_seq',
+    'pbvv_seq',
+    'perm',
+    'polygamma',
+    'pro_cv_seq',
+    'riccati_jn',
+    'riccati_yn',
+    'sinc',
+    'softplus',
+    'stirling2',
+    'y0_zeros',
+    'y1_zeros',
+    'y1p_zeros',
+    'yn_zeros',
+    'ynp_zeros',
+    'yvp',
+    'zeta'
+]
+
+
+__DEPRECATION_MSG_1_15 = (
+    "`scipy.special.{}` is deprecated as of SciPy 1.15.0 and will be "
+    "removed in SciPy 1.17.0. Please use `scipy.special.{}` instead."
+)
+
+# mapping k to last n such that factorialk(n, k) < np.iinfo(np.int64).max
+_FACTORIALK_LIMITS_64BITS = {1: 20, 2: 33, 3: 44, 4: 54, 5: 65,
+                             6: 74, 7: 84, 8: 93, 9: 101}
+# mapping k to last n such that factorialk(n, k) < np.iinfo(np.int32).max
+_FACTORIALK_LIMITS_32BITS = {1: 12, 2: 19, 3: 25, 4: 31, 5: 37,
+                             6: 43, 7: 47, 8: 51, 9: 56}
+
+
+def diric(x, n):
+    """Periodic sinc function, also called the Dirichlet function.
+
+    The Dirichlet function is defined as::
+
+        diric(x, n) = sin(x * n/2) / (n * sin(x / 2)),
+
+    where `n` is a positive integer.
+
+    Parameters
+    ----------
+    x : array_like
+        Input data
+    n : int
+        Integer defining the periodicity.
+
+    Returns
+    -------
+    diric : ndarray
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-8*np.pi, 8*np.pi, num=201)
+    >>> plt.figure(figsize=(8, 8));
+    >>> for idx, n in enumerate([2, 3, 4, 9]):
+    ...     plt.subplot(2, 2, idx+1)
+    ...     plt.plot(x, special.diric(x, n))
+    ...     plt.title('diric, n={}'.format(n))
+    >>> plt.show()
+
+    The following example demonstrates that `diric` gives the magnitudes
+    (modulo the sign and scaling) of the Fourier coefficients of a
+    rectangular pulse.
+
+    Suppress output of values that are effectively 0:
+
+    >>> np.set_printoptions(suppress=True)
+
+    Create a signal `x` of length `m` with `k` ones:
+
+    >>> m = 8
+    >>> k = 3
+    >>> x = np.zeros(m)
+    >>> x[:k] = 1
+
+    Use the FFT to compute the Fourier transform of `x`, and
+    inspect the magnitudes of the coefficients:
+
+    >>> np.abs(np.fft.fft(x))
+    array([ 3.        ,  2.41421356,  1.        ,  0.41421356,  1.        ,
+            0.41421356,  1.        ,  2.41421356])
+
+    Now find the same values (up to sign) using `diric`. We multiply
+    by `k` to account for the different scaling conventions of
+    `numpy.fft.fft` and `diric`:
+
+    >>> theta = np.linspace(0, 2*np.pi, m, endpoint=False)
+    >>> k * special.diric(theta, k)
+    array([ 3.        ,  2.41421356,  1.        , -0.41421356, -1.        ,
+           -0.41421356,  1.        ,  2.41421356])
+    """
+    x, n = asarray(x), asarray(n)
+    n = asarray(n + (x-x))
+    x = asarray(x + (n-n))
+    if issubdtype(x.dtype, inexact):
+        ytype = x.dtype
+    else:
+        ytype = float
+    y = zeros(x.shape, ytype)
+
+    # empirical minval for 32, 64 or 128 bit float computations
+    # where sin(x/2) < minval, result is fixed at +1 or -1
+    if np.finfo(ytype).eps < 1e-18:
+        minval = 1e-11
+    elif np.finfo(ytype).eps < 1e-15:
+        minval = 1e-7
+    else:
+        minval = 1e-3
+
+    mask1 = (n <= 0) | (n != floor(n))
+    place(y, mask1, nan)
+
+    x = x / 2
+    denom = sin(x)
+    mask2 = (1-mask1) & (abs(denom) < minval)
+    xsub = extract(mask2, x)
+    nsub = extract(mask2, n)
+    zsub = xsub / pi
+    place(y, mask2, pow(-1, np.round(zsub)*(nsub-1)))
+
+    mask = (1-mask1) & (1-mask2)
+    xsub = extract(mask, x)
+    nsub = extract(mask, n)
+    dsub = extract(mask, denom)
+    place(y, mask, sin(nsub*xsub)/(nsub*dsub))
+    return y
+
+
+def jnjnp_zeros(nt):
+    """Compute zeros of integer-order Bessel functions Jn and Jn'.
+
+    Results are arranged in order of the magnitudes of the zeros.
+
+    Parameters
+    ----------
+    nt : int
+        Number (<=1200) of zeros to compute
+
+    Returns
+    -------
+    zo[l-1] : ndarray
+        Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
+    n[l-1] : ndarray
+        Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`.
+    m[l-1] : ndarray
+        Serial number of the zeros of Jn(x) or Jn'(x) associated
+        with lth zero. Of length `nt`.
+    t[l-1] : ndarray
+        0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of
+        length `nt`.
+
+    See Also
+    --------
+    jn_zeros, jnp_zeros : to get separated arrays of zeros.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200):
+        raise ValueError("Number must be integer <= 1200.")
+    nt = int(nt)
+    n, m, t, zo = _specfun.jdzo(nt)
+    return zo[1:nt+1], n[:nt], m[:nt], t[:nt]
+
+
+def jnyn_zeros(n, nt):
+    """Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
+
+    Returns 4 arrays of length `nt`, corresponding to the first `nt`
+    zeros of Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively. The zeros
+    are returned in ascending order.
+
+    Parameters
+    ----------
+    n : int
+        Order of the Bessel functions
+    nt : int
+        Number (<=1200) of zeros to compute
+
+    Returns
+    -------
+    Jn : ndarray
+        First `nt` zeros of Jn
+    Jnp : ndarray
+        First `nt` zeros of Jn'
+    Yn : ndarray
+        First `nt` zeros of Yn
+    Ynp : ndarray
+        First `nt` zeros of Yn'
+
+    See Also
+    --------
+    jn_zeros, jnp_zeros, yn_zeros, ynp_zeros
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first three roots of :math:`J_1`, :math:`J_1'`,
+    :math:`Y_1` and :math:`Y_1'`.
+
+    >>> from scipy.special import jnyn_zeros
+    >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3)
+    >>> jn_roots, yn_roots
+    (array([ 3.83170597,  7.01558667, 10.17346814]),
+     array([2.19714133, 5.42968104, 8.59600587]))
+
+    Plot :math:`J_1`, :math:`J_1'`, :math:`Y_1`, :math:`Y_1'` and their roots.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jnyn_zeros, jvp, jn, yvp, yn
+    >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3)
+    >>> fig, ax = plt.subplots()
+    >>> xmax= 11
+    >>> x = np.linspace(0, xmax)
+    >>> x[0] += 1e-15
+    >>> ax.plot(x, jn(1, x), label=r"$J_1$", c='r')
+    >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$", c='b')
+    >>> ax.plot(x, yn(1, x), label=r"$Y_1$", c='y')
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$", c='c')
+    >>> zeros = np.zeros((3, ))
+    >>> ax.scatter(jn_roots, zeros, s=30, c='r', zorder=5,
+    ...            label=r"$J_1$ roots")
+    >>> ax.scatter(jnp_roots, zeros, s=30, c='b', zorder=5,
+    ...            label=r"$J_1'$ roots")
+    >>> ax.scatter(yn_roots, zeros, s=30, c='y', zorder=5,
+    ...            label=r"$Y_1$ roots")
+    >>> ax.scatter(ynp_roots, zeros, s=30, c='c', zorder=5,
+    ...            label=r"$Y_1'$ roots")
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.6, 0.6)
+    >>> ax.set_xlim(0, xmax)
+    >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75))
+    >>> plt.tight_layout()
+    >>> plt.show()
+    """
+    if not (isscalar(nt) and isscalar(n)):
+        raise ValueError("Arguments must be scalars.")
+    if (floor(n) != n) or (floor(nt) != nt):
+        raise ValueError("Arguments must be integers.")
+    if (nt <= 0):
+        raise ValueError("nt > 0")
+    return _specfun.jyzo(abs(n), nt)
+
+
+def jn_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel functions Jn.
+
+    Compute `nt` zeros of the Bessel functions :math:`J_n(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order. Note that this interval excludes the zero at :math:`x = 0`
+    that exists for :math:`n > 0`.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    jv: Real-order Bessel functions of the first kind
+    jnp_zeros: Zeros of :math:`Jn'`
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four positive roots of :math:`J_3`.
+
+    >>> from scipy.special import jn_zeros
+    >>> jn_zeros(3, 4)
+    array([ 6.3801619 ,  9.76102313, 13.01520072, 16.22346616])
+
+    Plot :math:`J_3` and its first four positive roots. Note
+    that the root located at 0 is not returned by `jn_zeros`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jn, jn_zeros
+    >>> j3_roots = jn_zeros(3, 4)
+    >>> xmax = 18
+    >>> xmin = -1
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jn(3, x), label=r'$J_3$')
+    >>> ax.scatter(j3_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"$J_3$_Zeros", zorder=5)
+    >>> ax.scatter(0, 0, s=30, c='k',
+    ...            label=r"Root at 0", zorder=5)
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[0]
+
+
+def jnp_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function derivatives Jn'.
+
+    Compute `nt` zeros of the functions :math:`J_n'(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order. Note that this interval excludes the zero at :math:`x = 0`
+    that exists for :math:`n > 1`.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    jvp: Derivatives of integer-order Bessel functions of the first kind
+    jv: Float-order Bessel functions of the first kind
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`J_2'`.
+
+    >>> from scipy.special import jnp_zeros
+    >>> jnp_zeros(2, 4)
+    array([ 3.05423693,  6.70613319,  9.96946782, 13.17037086])
+
+    As `jnp_zeros` yields the roots of :math:`J_n'`, it can be used to
+    compute the locations of the peaks of :math:`J_n`. Plot
+    :math:`J_2`, :math:`J_2'` and the locations of the roots of :math:`J_2'`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jn, jnp_zeros, jvp
+    >>> j2_roots = jnp_zeros(2, 4)
+    >>> xmax = 15
+    >>> x = np.linspace(0, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jn(2, x), label=r'$J_2$')
+    >>> ax.plot(x, jvp(2, x, 1), label=r"$J_2'$")
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.scatter(j2_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $J_2'$", zorder=5)
+    >>> ax.set_ylim(-0.4, 0.8)
+    >>> ax.set_xlim(0, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[1]
+
+
+def yn_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function Yn(x).
+
+    Compute `nt` zeros of the functions :math:`Y_n(x)` on the interval
+    :math:`(0, \infty)`. The zeros are returned in ascending order.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    yn: Bessel function of the second kind for integer order
+    yv: Bessel function of the second kind for real order
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`Y_2`.
+
+    >>> from scipy.special import yn_zeros
+    >>> yn_zeros(2, 4)
+    array([ 3.38424177,  6.79380751, 10.02347798, 13.20998671])
+
+    Plot :math:`Y_2` and its first four roots.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import yn, yn_zeros
+    >>> xmin = 2
+    >>> xmax = 15
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, yn(2, x), label=r'$Y_2$')
+    >>> ax.scatter(yn_zeros(2, 4), np.zeros((4, )), s=30, c='r',
+    ...            label='Roots', zorder=5)
+    >>> ax.set_ylim(-0.4, 0.4)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[2]
+
+
+def ynp_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function derivatives Yn'(x).
+
+    Compute `nt` zeros of the functions :math:`Y_n'(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel derivative function.
+
+
+    See Also
+    --------
+    yvp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of the first derivative of the
+    Bessel function of second kind for order 0 :math:`Y_0'`.
+
+    >>> from scipy.special import ynp_zeros
+    >>> ynp_zeros(0, 4)
+    array([ 2.19714133,  5.42968104,  8.59600587, 11.74915483])
+
+    Plot :math:`Y_0`, :math:`Y_0'` and confirm visually that the roots of
+    :math:`Y_0'` are located at local extrema of :math:`Y_0`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import yn, ynp_zeros, yvp
+    >>> zeros = ynp_zeros(0, 4)
+    >>> xmax = 13
+    >>> x = np.linspace(0, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, yn(0, x), label=r'$Y_0$')
+    >>> ax.plot(x, yvp(0, x, 1), label=r"$Y_0'$")
+    >>> ax.scatter(zeros, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $Y_0'$", zorder=5)
+    >>> for root in zeros:
+    ...     y0_extremum =  yn(0, root)
+    ...     lower = min(0, y0_extremum)
+    ...     upper = max(0, y0_extremum)
+    ...     ax.vlines(root, lower, upper, color='r')
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.6, 0.6)
+    >>> ax.set_xlim(0, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[3]
+
+
+def y0_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
+
+    The derivatives are given by Y0'(z0) = -Y1(z0) at each zero z0.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z0n : ndarray
+        Location of nth zero of Y0(z)
+    y0pz0n : ndarray
+        Value of derivative Y0'(z0) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first 4 real roots and the derivatives at the roots of
+    :math:`Y_0`:
+
+    >>> import numpy as np
+    >>> from scipy.special import y0_zeros
+    >>> zeros, grads = y0_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Roots: {zeros}")
+    ...     print(f"Gradients: {grads}")
+    Roots: [ 0.89358+0.j  3.95768+0.j  7.08605+0.j 10.22235+0.j]
+    Gradients: [-0.87942+0.j  0.40254+0.j -0.3001 +0.j  0.2497 +0.j]
+
+    Plot the real part of :math:`Y_0` and the first four computed roots.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y0
+    >>> xmin = 0
+    >>> xmax = 11
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, y0(x), label=r'$Y_0$')
+    >>> zeros, grads = y0_zeros(4)
+    >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r',
+    ...            label=r'$Y_0$_zeros', zorder=5)
+    >>> ax.set_ylim(-0.5, 0.6)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend(ncol=2)
+    >>> plt.show()
+
+    Compute the first 4 complex roots and the derivatives at the roots of
+    :math:`Y_0` by setting ``complex=True``:
+
+    >>> y0_zeros(4, True)
+    (array([ -2.40301663+0.53988231j,  -5.5198767 +0.54718001j,
+             -8.6536724 +0.54841207j, -11.79151203+0.54881912j]),
+     array([ 0.10074769-0.88196771j, -0.02924642+0.5871695j ,
+             0.01490806-0.46945875j, -0.00937368+0.40230454j]))
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 0
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def y1_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
+
+    The derivatives are given by Y1'(z1) = Y0(z1) at each zero z1.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z1n : ndarray
+        Location of nth zero of Y1(z)
+    y1pz1n : ndarray
+        Value of derivative Y1'(z1) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first 4 real roots and the derivatives at the roots of
+    :math:`Y_1`:
+
+    >>> import numpy as np
+    >>> from scipy.special import y1_zeros
+    >>> zeros, grads = y1_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Roots: {zeros}")
+    ...     print(f"Gradients: {grads}")
+    Roots: [ 2.19714+0.j  5.42968+0.j  8.59601+0.j 11.74915+0.j]
+    Gradients: [ 0.52079+0.j -0.34032+0.j  0.27146+0.j -0.23246+0.j]
+
+    Extract the real parts:
+
+    >>> realzeros = zeros.real
+    >>> realzeros
+    array([ 2.19714133,  5.42968104,  8.59600587, 11.74915483])
+
+    Plot :math:`Y_1` and the first four computed roots.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y1
+    >>> xmin = 0
+    >>> xmax = 13
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> zeros, grads = y1_zeros(4)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, y1(x), label=r'$Y_1$')
+    >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r',
+    ...            label=r'$Y_1$_zeros', zorder=5)
+    >>> ax.set_ylim(-0.5, 0.5)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+
+    Compute the first 4 complex roots and the derivatives at the roots of
+    :math:`Y_1` by setting ``complex=True``:
+
+    >>> y1_zeros(4, True)
+    (array([ -0.50274327+0.78624371j,  -3.83353519+0.56235654j,
+             -7.01590368+0.55339305j, -10.17357383+0.55127339j]),
+     array([-0.45952768+1.31710194j,  0.04830191-0.69251288j,
+            -0.02012695+0.51864253j,  0.011614  -0.43203296j]))
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 1
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def y1p_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
+
+    The values are given by Y1(z1) at each z1 where Y1'(z1)=0.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z1pn : ndarray
+        Location of nth zero of Y1'(z)
+    y1z1pn : ndarray
+        Value of derivative Y1(z1) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`Y_1'` and the values of
+    :math:`Y_1` at these roots.
+
+    >>> import numpy as np
+    >>> from scipy.special import y1p_zeros
+    >>> y1grad_roots, y1_values = y1p_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Y1' Roots: {y1grad_roots.real}")
+    ...     print(f"Y1 values: {y1_values.real}")
+    Y1' Roots: [ 3.68302  6.9415  10.1234  13.28576]
+    Y1 values: [ 0.41673 -0.30317  0.25091 -0.21897]
+
+    `y1p_zeros` can be used to calculate the extremal points of :math:`Y_1`
+    directly. Here we plot :math:`Y_1` and the first four extrema.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y1, yvp
+    >>> y1_roots, y1_values_at_roots = y1p_zeros(4)
+    >>> real_roots = y1_roots.real
+    >>> xmax = 15
+    >>> x = np.linspace(0, xmax, 500)
+    >>> x[0] += 1e-15
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y1(x), label=r'$Y_1$')
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$")
+    >>> ax.scatter(real_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $Y_1'$", zorder=5)
+    >>> ax.scatter(real_roots, y1_values_at_roots.real, s=30, c='k',
+    ...            label=r"Extrema of $Y_1$", zorder=5)
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.5, 0.5)
+    >>> ax.set_xlim(0, xmax)
+    >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75))
+    >>> plt.tight_layout()
+    >>> plt.show()
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 2
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def _bessel_diff_formula(v, z, n, L, phase):
+    # from AMS55.
+    # L(v, z) = J(v, z), Y(v, z), H1(v, z), H2(v, z), phase = -1
+    # L(v, z) = I(v, z) or exp(v*pi*i)K(v, z), phase = 1
+    # For K, you can pull out the exp((v-k)*pi*i) into the caller
+    v = asarray(v)
+    p = 1.0
+    s = L(v-n, z)
+    for i in range(1, n+1):
+        p = phase * (p * (n-i+1)) / i   # = choose(k, i)
+        s += p*L(v-n + i*2, z)
+    return s / (2.**n)
+
+
+def jvp(v, z, n=1):
+    """Compute derivatives of Bessel functions of the first kind.
+
+    Compute the nth derivative of the Bessel function `Jv` with
+    respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like or float
+        Order of Bessel function
+    z : complex
+        Argument at which to evaluate the derivative; can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Bessel function `jv` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Bessel function.
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+
+    Compute the Bessel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import jvp
+    >>> jvp(0, 1, 0), jvp(0, 1, 1), jvp(0, 1, 2)
+    (0.7651976865579666, -0.44005058574493355, -0.3251471008130331)
+
+    Compute the first derivative of the Bessel function of the first
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> jvp([0, 1, 2], 1, 1)
+    array([-0.44005059,  0.3251471 ,  0.21024362])
+
+    Compute the first derivative of the Bessel function of the first
+    kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0., 1.5, 3.])
+    >>> jvp(0, points, 1)
+    array([-0.        , -0.55793651, -0.33905896])
+
+    Plot the Bessel function of the first kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-10, 10, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jvp(1, x, 0), label=r"$J_1$")
+    >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$")
+    >>> ax.plot(x, jvp(1, x, 2), label=r"$J_1''$")
+    >>> ax.plot(x, jvp(1, x, 3), label=r"$J_1'''$")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return jv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, jv, -1)
+
+
+def yvp(v, z, n=1):
+    """Compute derivatives of Bessel functions of the second kind.
+
+    Compute the nth derivative of the Bessel function `Yv` with
+    respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel function
+    z : complex
+        Argument at which to evaluate the derivative
+    n : int, default 1
+        Order of derivative. For 0 returns the BEssel function `yv`
+
+    Returns
+    -------
+    scalar or ndarray
+        nth derivative of the Bessel function.
+
+    See Also
+    --------
+    yv : Bessel functions of the second kind
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Bessel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import yvp
+    >>> yvp(0, 1, 0), yvp(0, 1, 1), yvp(0, 1, 2)
+    (0.088256964215677, 0.7812128213002889, -0.8694697855159659)
+
+    Compute the first derivative of the Bessel function of the second
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> yvp([0, 1, 2], 1, 1)
+    array([0.78121282, 0.86946979, 2.52015239])
+
+    Compute the first derivative of the Bessel function of the
+    second kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> yvp(0, points, 1)
+    array([ 1.47147239,  0.41230863, -0.32467442])
+
+    Plot the Bessel function of the second kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> x[0] += 1e-15
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, yvp(1, x, 0), label=r"$Y_1$")
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$")
+    >>> ax.plot(x, yvp(1, x, 2), label=r"$Y_1''$")
+    >>> ax.plot(x, yvp(1, x, 3), label=r"$Y_1'''$")
+    >>> ax.set_ylim(-10, 10)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return yv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, yv, -1)
+
+
+def kvp(v, z, n=1):
+    """Compute derivatives of real-order modified Bessel function Kv(z)
+
+    Kv(z) is the modified Bessel function of the second kind.
+    Derivative is calculated with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel function
+    z : array_like of complex
+        Argument at which to evaluate the derivative
+    n : int, default 1
+        Order of derivative. For 0 returns the Bessel function `kv` itself.
+
+    Returns
+    -------
+    out : ndarray
+        The results
+
+    See Also
+    --------
+    kv
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.29.5 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 6.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.29.E5
+
+    Examples
+    --------
+    Compute the modified bessel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import kvp
+    >>> kvp(0, 1, 0), kvp(0, 1, 1), kvp(0, 1, 2)
+    (0.42102443824070834, -0.6019072301972346, 1.0229316684379428)
+
+    Compute the first derivative of the modified Bessel function of the second
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> kvp([0, 1, 2], 1, 1)
+    array([-0.60190723, -1.02293167, -3.85158503])
+
+    Compute the first derivative of the modified Bessel function of the
+    second kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> kvp(0, points, 1)
+    array([-1.65644112, -0.2773878 , -0.04015643])
+
+    Plot the modified bessel function of the second kind and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, kvp(1, x, 0), label=r"$K_1$")
+    >>> ax.plot(x, kvp(1, x, 1), label=r"$K_1'$")
+    >>> ax.plot(x, kvp(1, x, 2), label=r"$K_1''$")
+    >>> ax.plot(x, kvp(1, x, 3), label=r"$K_1'''$")
+    >>> ax.set_ylim(-2.5, 2.5)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return kv(v, z)
+    else:
+        return (-1)**n * _bessel_diff_formula(v, z, n, kv, 1)
+
+
+def ivp(v, z, n=1):
+    """Compute derivatives of modified Bessel functions of the first kind.
+
+    Compute the nth derivative of the modified Bessel function `Iv`
+    with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like or float
+        Order of Bessel function
+    z : array_like
+        Argument at which to evaluate the derivative; can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0, returns the Bessel function `iv` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        nth derivative of the modified Bessel function.
+
+    See Also
+    --------
+    iv
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.29.5 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 6.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.29.E5
+
+    Examples
+    --------
+    Compute the modified Bessel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import ivp
+    >>> ivp(0, 1, 0), ivp(0, 1, 1), ivp(0, 1, 2)
+    (1.2660658777520084, 0.565159103992485, 0.7009067737595233)
+
+    Compute the first derivative of the modified Bessel function of the first
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> ivp([0, 1, 2], 1, 1)
+    array([0.5651591 , 0.70090677, 0.29366376])
+
+    Compute the first derivative of the modified Bessel function of the
+    first kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0., 1.5, 3.])
+    >>> ivp(0, points, 1)
+    array([0.        , 0.98166643, 3.95337022])
+
+    Plot the modified Bessel function of the first kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-5, 5, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ivp(1, x, 0), label=r"$I_1$")
+    >>> ax.plot(x, ivp(1, x, 1), label=r"$I_1'$")
+    >>> ax.plot(x, ivp(1, x, 2), label=r"$I_1''$")
+    >>> ax.plot(x, ivp(1, x, 3), label=r"$I_1'''$")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return iv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, iv, 1)
+
+
+def h1vp(v, z, n=1):
+    """Compute derivatives of Hankel function H1v(z) with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like
+        Order of Hankel function
+    z : array_like
+        Argument at which to evaluate the derivative. Can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Hankel function `h1v` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Hankel function.
+
+    See Also
+    --------
+    hankel1
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Hankel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import h1vp
+    >>> h1vp(0, 1, 0), h1vp(0, 1, 1), h1vp(0, 1, 2)
+    ((0.7651976865579664+0.088256964215677j),
+     (-0.44005058574493355+0.7812128213002889j),
+     (-0.3251471008130329-0.8694697855159659j))
+
+    Compute the first derivative of the Hankel function of the first kind
+    for several orders at 1 by providing an array for `v`.
+
+    >>> h1vp([0, 1, 2], 1, 1)
+    array([-0.44005059+0.78121282j,  0.3251471 +0.86946979j,
+           0.21024362+2.52015239j])
+
+    Compute the first derivative of the Hankel function of the first kind
+    of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> h1vp(0, points, 1)
+    array([-0.24226846+1.47147239j, -0.55793651+0.41230863j,
+           -0.33905896-0.32467442j])
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return hankel1(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, hankel1, -1)
+
+
+def h2vp(v, z, n=1):
+    """Compute derivatives of Hankel function H2v(z) with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like
+        Order of Hankel function
+    z : array_like
+        Argument at which to evaluate the derivative. Can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Hankel function `h2v` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Hankel function.
+
+    See Also
+    --------
+    hankel2
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Hankel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import h2vp
+    >>> h2vp(0, 1, 0), h2vp(0, 1, 1), h2vp(0, 1, 2)
+    ((0.7651976865579664-0.088256964215677j),
+     (-0.44005058574493355-0.7812128213002889j),
+     (-0.3251471008130329+0.8694697855159659j))
+
+    Compute the first derivative of the Hankel function of the second kind
+    for several orders at 1 by providing an array for `v`.
+
+    >>> h2vp([0, 1, 2], 1, 1)
+    array([-0.44005059-0.78121282j,  0.3251471 -0.86946979j,
+           0.21024362-2.52015239j])
+
+    Compute the first derivative of the Hankel function of the second kind
+    of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> h2vp(0, points, 1)
+    array([-0.24226846-1.47147239j, -0.55793651-0.41230863j,
+           -0.33905896+0.32467442j])
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return hankel2(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, hankel2, -1)
+
+
+def riccati_jn(n, x):
+    r"""Compute Ricatti-Bessel function of the first kind and its derivative.
+
+    The Ricatti-Bessel function of the first kind is defined as :math:`x
+    j_n(x)`, where :math:`j_n` is the spherical Bessel function of the first
+    kind of order :math:`n`.
+
+    This function computes the value and first derivative of the
+    Ricatti-Bessel function for all orders up to and including `n`.
+
+    Parameters
+    ----------
+    n : int
+        Maximum order of function to compute
+    x : float
+        Argument at which to evaluate
+
+    Returns
+    -------
+    jn : ndarray
+        Value of j0(x), ..., jn(x)
+    jnp : ndarray
+        First derivative j0'(x), ..., jn'(x)
+
+    Notes
+    -----
+    The computation is carried out via backward recurrence, using the
+    relation DLMF 10.51.1 [2]_.
+
+    Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
+    Jin [1]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.51.E1
+
+    """
+    if not (isscalar(n) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n == 0):
+        n1 = 1
+    else:
+        n1 = n
+
+    jn = np.empty((n1 + 1,), dtype=np.float64)
+    jnp = np.empty_like(jn)
+
+    _rctj(x, out=(jn, jnp))
+    return jn[:(n+1)], jnp[:(n+1)]
+
+
+def riccati_yn(n, x):
+    """Compute Ricatti-Bessel function of the second kind and its derivative.
+
+    The Ricatti-Bessel function of the second kind is defined here as :math:`+x
+    y_n(x)`, where :math:`y_n` is the spherical Bessel function of the second
+    kind of order :math:`n`. *Note that this is in contrast to a common convention
+    that includes a minus sign in the definition.*
+
+    This function computes the value and first derivative of the function for
+    all orders up to and including `n`.
+
+    Parameters
+    ----------
+    n : int
+        Maximum order of function to compute
+    x : float
+        Argument at which to evaluate
+
+    Returns
+    -------
+    yn : ndarray
+        Value of y0(x), ..., yn(x)
+    ynp : ndarray
+        First derivative y0'(x), ..., yn'(x)
+
+    Notes
+    -----
+    The computation is carried out via ascending recurrence, using the
+    relation DLMF 10.51.1 [2]_.
+
+    Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
+    Jin [1]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.51.E1
+
+    """
+    if not (isscalar(n) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n == 0):
+        n1 = 1
+    else:
+        n1 = n
+
+    yn = np.empty((n1 + 1,), dtype=np.float64)
+    ynp = np.empty_like(yn)
+    _rcty(x, out=(yn, ynp))
+
+    return yn[:(n+1)], ynp[:(n+1)]
+
+
+def erf_zeros(nt):
+    """Compute the first nt zero in the first quadrant, ordered by absolute value.
+
+    Zeros in the other quadrants can be obtained by using the symmetries
+    erf(-z) = erf(z) and erf(conj(z)) = conj(erf(z)).
+
+
+    Parameters
+    ----------
+    nt : int
+        The number of zeros to compute
+
+    Returns
+    -------
+    The locations of the zeros of erf : ndarray (complex)
+        Complex values at which zeros of erf(z)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> special.erf_zeros(1)
+    array([1.45061616+1.880943j])
+
+    Check that erf is (close to) zero for the value returned by erf_zeros
+
+    >>> special.erf(special.erf_zeros(1))
+    array([4.95159469e-14-1.16407394e-16j])
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.cerzo(nt)
+
+
+def fresnelc_zeros(nt):
+    """Compute nt complex zeros of cosine Fresnel integral C(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    fresnelc_zeros: ndarray
+        Zeros of the cosine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(1, nt)
+
+
+def fresnels_zeros(nt):
+    """Compute nt complex zeros of sine Fresnel integral S(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    fresnels_zeros: ndarray
+        Zeros of the sine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(2, nt)
+
+
+def fresnel_zeros(nt):
+    """Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    zeros_sine: ndarray
+        Zeros of the sine Fresnel integral
+    zeros_cosine : ndarray
+        Zeros of the cosine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(2, nt), _specfun.fcszo(1, nt)
+
+
+def assoc_laguerre(x, n, k=0.0):
+    """Compute the generalized (associated) Laguerre polynomial of degree n and order k.
+
+    The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``,
+    with weighting function ``exp(-x) * x**k`` with ``k > -1``.
+
+    Parameters
+    ----------
+    x : float or ndarray
+        Points where to evaluate the Laguerre polynomial
+    n : int
+        Degree of the Laguerre polynomial
+    k : int
+        Order of the Laguerre polynomial
+
+    Returns
+    -------
+    assoc_laguerre: float or ndarray
+        Associated laguerre polynomial values
+
+    Notes
+    -----
+    `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with
+    reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
+
+    """
+    return _ufuncs.eval_genlaguerre(n, k, x)
+
+
+digamma = psi
+
+
+def polygamma(n, x):
+    r"""Polygamma functions.
+
+    Defined as :math:`\psi^{(n)}(x)` where :math:`\psi` is the
+    `digamma` function. See [dlmf]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        The order of the derivative of the digamma function; must be
+        integral
+    x : array_like
+        Real valued input
+
+    Returns
+    -------
+    ndarray
+        Function results
+
+    See Also
+    --------
+    digamma
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/5.15
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> x = [2, 3, 25.5]
+    >>> special.polygamma(1, x)
+    array([ 0.64493407,  0.39493407,  0.03999467])
+    >>> special.polygamma(0, x) == special.psi(x)
+    array([ True,  True,  True], dtype=bool)
+
+    """
+    n, x = asarray(n), asarray(x)
+    fac2 = (-1.0)**(n+1) * gamma(n+1.0) * zeta(n+1, x)
+    return where(n == 0, psi(x), fac2)
+
+
+def mathieu_even_coef(m, q):
+    r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+    The Fourier series of the even solutions of the Mathieu differential
+    equation are of the form
+
+    .. math:: \mathrm{ce}_{2n}(z, q) = \sum_{k=0}^{\infty} A_{(2n)}^{(2k)} \cos 2kz
+
+    .. math:: \mathrm{ce}_{2n+1}(z, q) =
+              \sum_{k=0}^{\infty} A_{(2n+1)}^{(2k+1)} \cos (2k+1)z
+
+    This function returns the coefficients :math:`A_{(2n)}^{(2k)}` for even
+    input m=2n, and the coefficients :math:`A_{(2n+1)}^{(2k+1)}` for odd input
+    m=2n+1.
+
+    Parameters
+    ----------
+    m : int
+        Order of Mathieu functions.  Must be non-negative.
+    q : float (>=0)
+        Parameter of Mathieu functions.  Must be non-negative.
+
+    Returns
+    -------
+    Ak : ndarray
+        Even or odd Fourier coefficients, corresponding to even or odd m.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/28.4#i
+
+    """
+    if not (isscalar(m) and isscalar(q)):
+        raise ValueError("m and q must be scalars.")
+    if (q < 0):
+        raise ValueError("q >=0")
+    if (m != floor(m)) or (m < 0):
+        raise ValueError("m must be an integer >=0.")
+
+    if (q <= 1):
+        qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
+    else:
+        qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
+    km = int(qm + 0.5*m)
+    if km > 251:
+        warnings.warn("Too many predicted coefficients.", RuntimeWarning, stacklevel=2)
+    kd = 1
+    m = int(floor(m))
+    if m % 2:
+        kd = 2
+
+    a = mathieu_a(m, q)
+    fc = _specfun.fcoef(kd, m, q, a)
+    return fc[:km]
+
+
+def mathieu_odd_coef(m, q):
+    r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+    The Fourier series of the odd solutions of the Mathieu differential
+    equation are of the form
+
+    .. math:: \mathrm{se}_{2n+1}(z, q) =
+              \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
+
+    .. math:: \mathrm{se}_{2n+2}(z, q) =
+              \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
+
+    This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
+    input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
+    input m=2n+1.
+
+    Parameters
+    ----------
+    m : int
+        Order of Mathieu functions.  Must be non-negative.
+    q : float (>=0)
+        Parameter of Mathieu functions.  Must be non-negative.
+
+    Returns
+    -------
+    Bk : ndarray
+        Even or odd Fourier coefficients, corresponding to even or odd m.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(q)):
+        raise ValueError("m and q must be scalars.")
+    if (q < 0):
+        raise ValueError("q >=0")
+    if (m != floor(m)) or (m <= 0):
+        raise ValueError("m must be an integer > 0")
+
+    if (q <= 1):
+        qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
+    else:
+        qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
+    km = int(qm + 0.5*m)
+    if km > 251:
+        warnings.warn("Too many predicted coefficients.", RuntimeWarning, stacklevel=2)
+    kd = 4
+    m = int(floor(m))
+    if m % 2:
+        kd = 3
+
+    b = mathieu_b(m, q)
+    fc = _specfun.fcoef(kd, m, q, b)
+    return fc[:km]
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("lpmn", "assoc_legendre_p_all"))
+def lpmn(m, n, z):
+    """Sequence of associated Legendre functions of the first kind.
+
+    Computes the associated Legendre function of the first kind of order m and
+    degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
+    ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    This function takes a real argument ``z``. For complex arguments ``z``
+    use clpmn instead.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please `scipy.special.assoc_legendre_p_all` instead.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like
+        Input value.
+
+    Returns
+    -------
+    Pmn_z : (m+1, n+1) array
+       Values for all orders 0..m and degrees 0..n
+    Pmn_d_z : (m+1, n+1) array
+       Derivatives for all orders 0..m and degrees 0..n
+
+    See Also
+    --------
+    clpmn: associated Legendre functions of the first kind for complex z
+
+    Notes
+    -----
+    In the interval (-1, 1), Ferrer's function of the first kind is
+    returned. The phase convention used for the intervals (1, inf)
+    and (-inf, -1) is such that the result is always real.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/14.3
+
+    """
+
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+
+    if (abs(m) > n):
+        raise ValueError("m must be <= n.")
+
+    if np.iscomplexobj(z):
+        raise ValueError("Argument must be real. Use clpmn instead.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+
+    branch_cut = np.where(np.abs(z) <= 1, 2, 3)
+
+    p, pd = assoc_legendre_p_all(n, abs(m), z, branch_cut=branch_cut, diff_n=1)
+    p = np.swapaxes(p, 0, 1)
+    pd = np.swapaxes(pd, 0, 1)
+
+    if (m >= 0):
+        p = p[:(m + 1)]
+        pd = pd[:(m + 1)]
+    else:
+        p = np.insert(p[:(m - 1):-1], 0, p[0], axis=0)
+        pd = np.insert(pd[:(m - 1):-1], 0, pd[0], axis=0)
+
+    return p, pd
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("clpmn", "assoc_legendre_p_all"))
+def clpmn(m, n, z, type=3):
+    """Associated Legendre function of the first kind for complex arguments.
+
+    Computes the associated Legendre function of the first kind of order m and
+    degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
+    ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please use `scipy.special.assoc_legendre_p_all` instead.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like, float or complex
+        Input value.
+    type : int, optional
+       takes values 2 or 3
+       2: cut on the real axis ``|x| > 1``
+       3: cut on the real axis ``-1 < x < 1`` (default)
+
+    Returns
+    -------
+    Pmn_z : (m+1, n+1) array
+       Values for all orders ``0..m`` and degrees ``0..n``
+    Pmn_d_z : (m+1, n+1) array
+       Derivatives for all orders ``0..m`` and degrees ``0..n``
+
+    See Also
+    --------
+    lpmn: associated Legendre functions of the first kind for real z
+
+    Notes
+    -----
+    By default, i.e. for ``type=3``, phase conventions are chosen according
+    to [1]_ such that the function is analytic. The cut lies on the interval
+    (-1, 1). Approaching the cut from above or below in general yields a phase
+    factor with respect to Ferrer's function of the first kind
+    (cf. `lpmn`).
+
+    For ``type=2`` a cut at ``|x| > 1`` is chosen. Approaching the real values
+    on the interval (-1, 1) in the complex plane yields Ferrer's function
+    of the first kind.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/14.21
+
+    """
+
+    if (abs(m) > n):
+        raise ValueError("m must be <= n.")
+
+    if not (type == 2 or type == 3):
+        raise ValueError("type must be either 2 or 3.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+
+    if not np.iscomplexobj(z):
+        z = np.asarray(z, dtype=complex)
+
+    out, out_jac = assoc_legendre_p_all(n, abs(m), z, branch_cut=type, diff_n=1)
+    out = np.swapaxes(out, 0, 1)
+    out_jac = np.swapaxes(out_jac, 0, 1)
+
+    if (m >= 0):
+        out = out[:(m + 1)]
+        out_jac = out_jac[:(m + 1)]
+    else:
+        out = np.insert(out[:(m - 1):-1], 0, out[0], axis=0)
+        out_jac = np.insert(out_jac[:(m - 1):-1], 0, out_jac[0], axis=0)
+
+    return out, out_jac
+
+
+def lqmn(m, n, z):
+    """Sequence of associated Legendre functions of the second kind.
+
+    Computes the associated Legendre function of the second kind of order m and
+    degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
+    ``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like, complex
+        Input value.
+
+    Returns
+    -------
+    Qmn_z : (m+1, n+1) array
+       Values for all orders 0..m and degrees 0..n
+    Qmn_d_z : (m+1, n+1) array
+       Derivatives for all orders 0..m and degrees 0..n
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(m) or (m < 0):
+        raise ValueError("m must be a non-negative integer.")
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+    # Ensure neither m nor n == 0
+    mm = max(1, m)
+    nn = max(1, n)
+
+    z = np.asarray(z)
+    if (not np.issubdtype(z.dtype, np.inexact)):
+        z = z.astype(np.float64)
+
+    if np.iscomplexobj(z):
+        q = np.empty((mm + 1, nn + 1) + z.shape, dtype=np.complex128)
+    else:
+        q = np.empty((mm + 1, nn + 1) + z.shape, dtype=np.float64)
+    qd = np.empty_like(q)
+    if (z.ndim == 0):
+        _lqmn(z, out=(q, qd))
+    else:
+        # new axes must be last for the ufunc
+        _lqmn(z,
+              out=(np.moveaxis(q, (0, 1), (-2, -1)),
+                   np.moveaxis(qd, (0, 1), (-2, -1))))
+
+    return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)]
+
+
+def bernoulli(n):
+    """Bernoulli numbers B0..Bn (inclusive).
+
+    Parameters
+    ----------
+    n : int
+        Indicated the number of terms in the Bernoulli series to generate.
+
+    Returns
+    -------
+    ndarray
+        The Bernoulli numbers ``[B(0), B(1), ..., B(n)]``.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] "Bernoulli number", Wikipedia, https://en.wikipedia.org/wiki/Bernoulli_number
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import bernoulli, zeta
+    >>> bernoulli(4)
+    array([ 1.        , -0.5       ,  0.16666667,  0.        , -0.03333333])
+
+    The Wikipedia article ([2]_) points out the relationship between the
+    Bernoulli numbers and the zeta function, ``B_n^+ = -n * zeta(1 - n)``
+    for ``n > 0``:
+
+    >>> n = np.arange(1, 5)
+    >>> -n * zeta(1 - n)
+    array([ 0.5       ,  0.16666667, -0.        , -0.03333333])
+
+    Note that, in the notation used in the wikipedia article,
+    `bernoulli` computes ``B_n^-`` (i.e. it used the convention that
+    ``B_1`` is -1/2).  The relation given above is for ``B_n^+``, so the
+    sign of 0.5 does not match the output of ``bernoulli(4)``.
+
+    """
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    n = int(n)
+    if (n < 2):
+        n1 = 2
+    else:
+        n1 = n
+    return _specfun.bernob(int(n1))[:(n+1)]
+
+
+def euler(n):
+    """Euler numbers E(0), E(1), ..., E(n).
+
+    The Euler numbers [1]_ are also known as the secant numbers.
+
+    Because ``euler(n)`` returns floating point values, it does not give
+    exact values for large `n`.  The first inexact value is E(22).
+
+    Parameters
+    ----------
+    n : int
+        The highest index of the Euler number to be returned.
+
+    Returns
+    -------
+    ndarray
+        The Euler numbers [E(0), E(1), ..., E(n)].
+        The odd Euler numbers, which are all zero, are included.
+
+    References
+    ----------
+    .. [1] Sequence A122045, The On-Line Encyclopedia of Integer Sequences,
+           https://oeis.org/A122045
+    .. [2] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import euler
+    >>> euler(6)
+    array([  1.,   0.,  -1.,   0.,   5.,   0., -61.])
+
+    >>> euler(13).astype(np.int64)
+    array([      1,       0,      -1,       0,       5,       0,     -61,
+                 0,    1385,       0,  -50521,       0, 2702765,       0])
+
+    >>> euler(22)[-1]  # Exact value of E(22) is -69348874393137901.
+    -69348874393137976.0
+
+    """
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    n = int(n)
+    if (n < 2):
+        n1 = 2
+    else:
+        n1 = n
+    return _specfun.eulerb(n1)[:(n+1)]
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("lpn", "legendre_p_all"))
+def lpn(n, z):
+    """Legendre function of the first kind.
+
+    Compute sequence of Legendre functions of the first kind (polynomials),
+    Pn(z) and derivatives for all degrees from 0 to n (inclusive).
+
+    See also special.legendre for polynomial class.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please use `scipy.special.legendre_p_all` instead.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    """
+
+    return legendre_p_all(n, z, diff_n=1)
+
+
+def lqn(n, z):
+    """Legendre function of the second kind.
+
+    Compute sequence of Legendre functions of the second kind, Qn(z) and
+    derivatives for all degrees from 0 to n (inclusive).
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+
+    z = np.asarray(z)
+    if (not np.issubdtype(z.dtype, np.inexact)):
+        z = z.astype(float)
+
+    if np.iscomplexobj(z):
+        qn = np.empty((n1 + 1,) + z.shape, dtype=np.complex128)
+    else:
+        qn = np.empty((n1 + 1,) + z.shape, dtype=np.float64)
+    qd = np.empty_like(qn)
+    if (z.ndim == 0):
+        _lqn(z, out=(qn, qd))
+    else:
+          # new axes must be last for the ufunc
+        _lqn(z,
+             out=(np.moveaxis(qn, 0, -1),
+                  np.moveaxis(qd, 0, -1)))
+
+    return qn[:(n+1)], qd[:(n+1)]
+
+
+def ai_zeros(nt):
+    """
+    Compute `nt` zeros and values of the Airy function Ai and its derivative.
+
+    Computes the first `nt` zeros, `a`, of the Airy function Ai(x);
+    first `nt` zeros, `ap`, of the derivative of the Airy function Ai'(x);
+    the corresponding values Ai(a');
+    and the corresponding values Ai'(a).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    a : ndarray
+        First `nt` zeros of Ai(x)
+    ap : ndarray
+        First `nt` zeros of Ai'(x)
+    ai : ndarray
+        Values of Ai(x) evaluated at first `nt` zeros of Ai'(x)
+    aip : ndarray
+        Values of Ai'(x) evaluated at first `nt` zeros of Ai(x)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> a, ap, ai, aip = special.ai_zeros(3)
+    >>> a
+    array([-2.33810741, -4.08794944, -5.52055983])
+    >>> ap
+    array([-1.01879297, -3.24819758, -4.82009921])
+    >>> ai
+    array([ 0.53565666, -0.41901548,  0.38040647])
+    >>> aip
+    array([ 0.70121082, -0.80311137,  0.86520403])
+
+    """
+    kf = 1
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be a positive integer scalar.")
+    return _specfun.airyzo(nt, kf)
+
+
+def bi_zeros(nt):
+    """
+    Compute `nt` zeros and values of the Airy function Bi and its derivative.
+
+    Computes the first `nt` zeros, b, of the Airy function Bi(x);
+    first `nt` zeros, b', of the derivative of the Airy function Bi'(x);
+    the corresponding values Bi(b');
+    and the corresponding values Bi'(b).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    b : ndarray
+        First `nt` zeros of Bi(x)
+    bp : ndarray
+        First `nt` zeros of Bi'(x)
+    bi : ndarray
+        Values of Bi(x) evaluated at first `nt` zeros of Bi'(x)
+    bip : ndarray
+        Values of Bi'(x) evaluated at first `nt` zeros of Bi(x)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> b, bp, bi, bip = special.bi_zeros(3)
+    >>> b
+    array([-1.17371322, -3.2710933 , -4.83073784])
+    >>> bp
+    array([-2.29443968, -4.07315509, -5.51239573])
+    >>> bi
+    array([-0.45494438,  0.39652284, -0.36796916])
+    >>> bip
+    array([ 0.60195789, -0.76031014,  0.83699101])
+
+    """
+    kf = 2
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be a positive integer scalar.")
+    return _specfun.airyzo(nt, kf)
+
+
+def lmbda(v, x):
+    r"""Jahnke-Emden Lambda function, Lambdav(x).
+
+    This function is defined as [2]_,
+
+    .. math:: \Lambda_v(x) = \Gamma(v+1) \frac{J_v(x)}{(x/2)^v},
+
+    where :math:`\Gamma` is the gamma function and :math:`J_v` is the
+    Bessel function of the first kind.
+
+    Parameters
+    ----------
+    v : float
+        Order of the Lambda function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    vl : ndarray
+        Values of Lambda_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dl : ndarray
+        Derivatives Lambda_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] Jahnke, E. and Emde, F. "Tables of Functions with Formulae and
+           Curves" (4th ed.), Dover, 1945
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    if (v < 0):
+        raise ValueError("argument must be > 0.")
+    n = int(v)
+    v0 = v - n
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    if (v != floor(v)):
+        vm, vl, dl = _specfun.lamv(v1, x)
+    else:
+        vm, vl, dl = _specfun.lamn(v1, x)
+    return vl[:(n+1)], dl[:(n+1)]
+
+
+def pbdv_seq(v, x):
+    """Parabolic cylinder functions Dv(x) and derivatives.
+
+    Parameters
+    ----------
+    v : float
+        Order of the parabolic cylinder function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of D_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dp : ndarray
+        Derivatives D_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = int(v)
+    v0 = v-n
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    dv, dp, pdf, pdd = _specfun.pbdv(v1, x)
+    return dv[:n1+1], dp[:n1+1]
+
+
+def pbvv_seq(v, x):
+    """Parabolic cylinder functions Vv(x) and derivatives.
+
+    Parameters
+    ----------
+    v : float
+        Order of the parabolic cylinder function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of V_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dp : ndarray
+        Derivatives V_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = int(v)
+    v0 = v-n
+    if (n <= 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    dv, dp, pdf, pdd = _specfun.pbvv(v1, x)
+    return dv[:n1+1], dp[:n1+1]
+
+
+def pbdn_seq(n, z):
+    """Parabolic cylinder functions Dn(z) and derivatives.
+
+    Parameters
+    ----------
+    n : int
+        Order of the parabolic cylinder function
+    z : complex
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of D_i(z), for i=0, ..., i=n.
+    dp : ndarray
+        Derivatives D_i'(z), for i=0, ..., i=n.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(n) and isscalar(z)):
+        raise ValueError("arguments must be scalars.")
+    if (floor(n) != n):
+        raise ValueError("n must be an integer.")
+    if (abs(n) <= 1):
+        n1 = 1
+    else:
+        n1 = n
+    cpb, cpd = _specfun.cpbdn(n1, z)
+    return cpb[:n1+1], cpd[:n1+1]
+
+
+def ber_zeros(nt):
+    """Compute nt zeros of the Kelvin function ber.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    ber
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 1)
+
+
+def bei_zeros(nt):
+    """Compute nt zeros of the Kelvin function bei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    bei
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 2)
+
+
+def ker_zeros(nt):
+    """Compute nt zeros of the Kelvin function ker.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    ker
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 3)
+
+
+def kei_zeros(nt):
+    """Compute nt zeros of the Kelvin function kei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    kei
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 4)
+
+
+def berp_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function ber.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    ber, berp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+
+    Examples
+    --------
+    Compute the first 5 zeros of the derivative of the Kelvin function.
+
+    >>> from scipy.special import berp_zeros
+    >>> berp_zeros(5)
+    array([ 6.03871081, 10.51364251, 14.96844542, 19.41757493, 23.86430432])
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 5)
+
+
+def beip_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function bei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    bei, beip
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 6)
+
+
+def kerp_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function ker.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    ker, kerp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 7)
+
+
+def keip_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function kei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    kei, keip
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 8)
+
+
+def kelvin_zeros(nt):
+    """Compute nt zeros of all Kelvin functions.
+
+    Returned in a length-8 tuple of arrays of length nt.  The tuple contains
+    the arrays of zeros of (ber, bei, ker, kei, ber', bei', ker', kei').
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return (_specfun.klvnzo(nt, 1),
+            _specfun.klvnzo(nt, 2),
+            _specfun.klvnzo(nt, 3),
+            _specfun.klvnzo(nt, 4),
+            _specfun.klvnzo(nt, 5),
+            _specfun.klvnzo(nt, 6),
+            _specfun.klvnzo(nt, 7),
+            _specfun.klvnzo(nt, 8))
+
+
+def pro_cv_seq(m, n, c):
+    """Characteristic values for prolate spheroidal wave functions.
+
+    Compute a sequence of characteristic values for the prolate
+    spheroidal wave functions for mode m and n'=m..n and spheroidal
+    parameter c.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(n) and isscalar(c)):
+        raise ValueError("Arguments must be scalars.")
+    if (n != floor(n)) or (m != floor(m)):
+        raise ValueError("Modes must be integers.")
+    if (n-m > 199):
+        raise ValueError("Difference between n and m is too large.")
+    maxL = n-m+1
+    return _specfun.segv(m, n, c, 1)[1][:maxL]
+
+
+def obl_cv_seq(m, n, c):
+    """Characteristic values for oblate spheroidal wave functions.
+
+    Compute a sequence of characteristic values for the oblate
+    spheroidal wave functions for mode m and n'=m..n and spheroidal
+    parameter c.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(n) and isscalar(c)):
+        raise ValueError("Arguments must be scalars.")
+    if (n != floor(n)) or (m != floor(m)):
+        raise ValueError("Modes must be integers.")
+    if (n-m > 199):
+        raise ValueError("Difference between n and m is too large.")
+    maxL = n-m+1
+    return _specfun.segv(m, n, c, -1)[1][:maxL]
+
+
+def comb(N, k, *, exact=False, repetition=False):
+    """The number of combinations of N things taken k at a time.
+
+    This is often expressed as "N choose k".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    k : int, ndarray
+        Number of elements taken.
+    exact : bool, optional
+        For integers, if `exact` is False, then floating point precision is
+        used, otherwise the result is computed exactly.
+
+        .. deprecated:: 1.14.0
+            ``exact=True`` is deprecated for non-integer `N` and `k` and will raise an
+            error in SciPy 1.16.0
+    repetition : bool, optional
+        If `repetition` is True, then the number of combinations with
+        repetition is computed.
+
+    Returns
+    -------
+    val : int, float, ndarray
+        The total number of combinations.
+
+    See Also
+    --------
+    binom : Binomial coefficient considered as a function of two real
+            variables.
+
+    Notes
+    -----
+    - Array arguments accepted only for exact=False case.
+    - If N < 0, or k < 0, then 0 is returned.
+    - If k > N and repetition=False, then 0 is returned.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import comb
+    >>> k = np.array([3, 4])
+    >>> n = np.array([10, 10])
+    >>> comb(n, k, exact=False)
+    array([ 120.,  210.])
+    >>> comb(10, 3, exact=True)
+    120
+    >>> comb(10, 3, exact=True, repetition=True)
+    220
+
+    """
+    if repetition:
+        return comb(N + k - 1, k, exact=exact)
+    if exact:
+        if int(N) == N and int(k) == k:
+            # _comb_int casts inputs to integers, which is safe & intended here
+            return _comb_int(N, k)
+        # otherwise, we disregard `exact=True`; it makes no sense for
+        # non-integral arguments
+        msg = ("`exact=True` is deprecated for non-integer `N` and `k` and will raise "
+               "an error in SciPy 1.16.0")
+        warnings.warn(msg, DeprecationWarning, stacklevel=2)
+        return comb(N, k)
+    else:
+        k, N = asarray(k), asarray(N)
+        cond = (k <= N) & (N >= 0) & (k >= 0)
+        vals = binom(N, k)
+        if isinstance(vals, np.ndarray):
+            vals[~cond] = 0
+        elif not cond:
+            vals = np.float64(0)
+        return vals
+
+
+def perm(N, k, exact=False):
+    """Permutations of N things taken k at a time, i.e., k-permutations of N.
+
+    It's also known as "partial permutations".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    k : int, ndarray
+        Number of elements taken.
+    exact : bool, optional
+        If ``True``, calculate the answer exactly using long integer arithmetic (`N`
+        and `k` must be scalar integers). If ``False``, a floating point approximation
+        is calculated (more rapidly) using `poch`. Default is ``False``.
+
+    Returns
+    -------
+    val : int, ndarray
+        The number of k-permutations of N.
+
+    Notes
+    -----
+    - Array arguments accepted only for exact=False case.
+    - If k > N, N < 0, or k < 0, then a 0 is returned.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import perm
+    >>> k = np.array([3, 4])
+    >>> n = np.array([10, 10])
+    >>> perm(n, k)
+    array([  720.,  5040.])
+    >>> perm(10, 3, exact=True)
+    720
+
+    """
+    if exact:
+        N = np.squeeze(N)[()]  # for backward compatibility (accepted size 1 arrays)
+        k = np.squeeze(k)[()]
+        if not (isscalar(N) and isscalar(k)):
+            raise ValueError("`N` and `k` must scalar integers be with `exact=True`.")
+
+        floor_N, floor_k = int(N), int(k)
+        non_integral = not (floor_N == N and floor_k == k)
+        if (k > N) or (N < 0) or (k < 0):
+            if non_integral:
+                msg = ("Non-integer `N` and `k` with `exact=True` is deprecated and "
+                       "will raise an error in SciPy 1.16.0.")
+                warnings.warn(msg, DeprecationWarning, stacklevel=2)
+            return 0
+        if non_integral:
+            raise ValueError("Non-integer `N` and `k` with `exact=True` is not "
+                             "supported.")
+        val = 1
+        for i in range(floor_N - floor_k + 1, floor_N + 1):
+            val *= i
+        return val
+    else:
+        k, N = asarray(k), asarray(N)
+        cond = (k <= N) & (N >= 0) & (k >= 0)
+        vals = poch(N - k + 1, k)
+        if isinstance(vals, np.ndarray):
+            vals[~cond] = 0
+        elif not cond:
+            vals = np.float64(0)
+        return vals
+
+
+# https://stackoverflow.com/a/16327037
+def _range_prod(lo, hi, k=1):
+    """
+    Product of a range of numbers spaced k apart (from hi).
+
+    For k=1, this returns the product of
+    lo * (lo+1) * (lo+2) * ... * (hi-2) * (hi-1) * hi
+    = hi! / (lo-1)!
+
+    For k>1, it correspond to taking only every k'th number when
+    counting down from hi - e.g. 18!!!! = _range_prod(1, 18, 4).
+
+    Breaks into smaller products first for speed:
+    _range_prod(2, 9) = ((2*3)*(4*5))*((6*7)*(8*9))
+    """
+    if lo == 1 and k == 1:
+        return math.factorial(hi)
+
+    if lo + k < hi:
+        mid = (hi + lo) // 2
+        if k > 1:
+            # make sure mid is a multiple of k away from hi
+            mid = mid - ((mid - hi) % k)
+        return _range_prod(lo, mid, k) * _range_prod(mid + k, hi, k)
+    elif lo + k == hi:
+        return lo * hi
+    else:
+        return hi
+
+
+def _factorialx_array_exact(n, k=1):
+    """
+    Exact computation of factorial for an array.
+
+    The factorials are computed in incremental fashion, by taking
+    the sorted unique values of n and multiplying the intervening
+    numbers between the different unique values.
+
+    In other words, the factorial for the largest input is only
+    computed once, with each other result computed in the process.
+
+    k > 1 corresponds to the multifactorial.
+    """
+    un = np.unique(n)
+    # numpy changed nan-sorting behaviour with 1.21, see numpy/numpy#18070;
+    # to unify the behaviour, we remove the nan's here; the respective
+    # values will be set separately at the end
+    un = un[~np.isnan(un)]
+
+    # Convert to object array if np.int64 can't handle size
+    if np.isnan(n).any():
+        dt = float
+    elif k in _FACTORIALK_LIMITS_64BITS.keys():
+        if un[-1] > _FACTORIALK_LIMITS_64BITS[k]:
+            # e.g. k=1: 21! > np.iinfo(np.int64).max
+            dt = object
+        elif un[-1] > _FACTORIALK_LIMITS_32BITS[k]:
+            # e.g. k=3: 26!!! > np.iinfo(np.int32).max
+            dt = np.int64
+        else:
+            dt = np.dtype("long")
+    else:
+        # for k >= 10, we always use object
+        dt = object
+
+    out = np.empty_like(n, dtype=dt)
+
+    # Handle invalid/trivial values
+    un = un[un > 1]
+    out[n < 2] = 1
+    out[n < 0] = 0
+
+    # Calculate products of each range of numbers
+    # we can only multiply incrementally if the values are k apart;
+    # therefore we partition `un` into "lanes", i.e. its residues modulo k
+    for lane in range(0, k):
+        ul = un[(un % k) == lane] if k > 1 else un
+        if ul.size:
+            # after np.unique, un resp. ul are sorted, ul[0] is the smallest;
+            # cast to python ints to avoid overflow with np.int-types
+            val = _range_prod(1, int(ul[0]), k=k)
+            out[n == ul[0]] = val
+            for i in range(len(ul) - 1):
+                # by the filtering above, we have ensured that prev & current
+                # are a multiple of k apart
+                prev = ul[i]
+                current = ul[i + 1]
+                # we already multiplied all factors until prev; continue
+                # building the full factorial from the following (`prev + 1`);
+                # use int() for the same reason as above
+                val *= _range_prod(int(prev + 1), int(current), k=k)
+                out[n == current] = val
+
+    if np.isnan(n).any():
+        out = out.astype(np.float64)
+        out[np.isnan(n)] = np.nan
+    return out
+
+
+def _factorialx_array_approx(n, k, extend):
+    """
+    Calculate approximation to multifactorial for array n and integer k.
+
+    Ensure that values aren't calculated unnecessarily.
+    """
+    if extend == "complex":
+        return _factorialx_approx_core(n, k=k, extend=extend)
+
+    # at this point we are guaranteed that extend='zero' and that k>0 is an integer
+    result = zeros(n.shape)
+    # keep nans as nans
+    place(result, np.isnan(n), np.nan)
+    # only compute where n >= 0 (excludes nans), everything else is 0
+    cond = (n >= 0)
+    n_to_compute = extract(cond, n)
+    place(result, cond, _factorialx_approx_core(n_to_compute, k=k, extend=extend))
+    return result
+
+
+def _gamma1p(vals):
+    """
+    returns gamma(n+1), though with NaN at -1 instead of inf, c.f. #21827
+    """
+    res = gamma(vals + 1)
+    # replace infinities at -1 (from gamma function at 0) with nan
+    # gamma only returns inf for real inputs; can ignore complex case
+    if isinstance(res, np.ndarray):
+        if not _is_subdtype(vals.dtype, "c"):
+            res[vals == -1] = np.nan
+    elif np.isinf(res) and vals == -1:
+        res = np.float64("nan")
+    return res
+
+
+def _factorialx_approx_core(n, k, extend):
+    """
+    Core approximation to multifactorial for array n and integer k.
+    """
+    if k == 1:
+        # shortcut for k=1; same for both extensions, because we assume the
+        # handling of extend == 'zero' happens in _factorialx_array_approx
+        result = _gamma1p(n)
+        if isinstance(n, np.ndarray):
+            # gamma does not maintain 0-dim arrays; fix it
+            result = np.array(result)
+        return result
+
+    if extend == "complex":
+        # see https://numpy.org/doc/stable/reference/generated/numpy.power.html
+        p_dtype = complex if (_is_subdtype(type(k), "c") or k < 0) else None
+        with warnings.catch_warnings():
+            # do not warn about 0 * inf, nan / nan etc.; the results are correct
+            warnings.simplefilter("ignore", RuntimeWarning)
+            # don't use `(n-1)/k` in np.power; underflows if 0 is of a uintX type
+            result = np.power(k, n / k, dtype=p_dtype) * _gamma1p(n / k)
+            result *= rgamma(1 / k + 1) / np.power(k, 1 / k, dtype=p_dtype)
+        if isinstance(n, np.ndarray):
+            # ensure we keep array-ness for 0-dim inputs; already n/k above loses it
+            result = np.array(result)
+        return result
+
+    # at this point we are guaranteed that extend='zero' and that k>0 is an integer
+    n_mod_k = n % k
+    # scalar case separately, unified handling would be inefficient for arrays;
+    # don't use isscalar due to numpy/numpy#23574; 0-dim arrays treated below
+    if not isinstance(n, np.ndarray):
+        return (
+            np.power(k, (n - n_mod_k) / k)
+            * gamma(n / k + 1) / gamma(n_mod_k / k + 1)
+            * max(n_mod_k, 1)
+        )
+
+    # factor that's independent of the residue class (see factorialk docstring)
+    result = np.power(k, n / k) * gamma(n / k + 1)
+    # factor dependent on residue r (for `r=0` it's 1, so we skip `r=0`
+    # below and thus also avoid evaluating `max(r, 1)`)
+    def corr(k, r): return np.power(k, -r / k) / gamma(r / k + 1) * r
+    for r in np.unique(n_mod_k):
+        if r == 0:
+            continue
+        # cast to int because uint types break on `-r`
+        result[n_mod_k == r] *= corr(k, int(r))
+    return result
+
+
+def _is_subdtype(dtype, dtypes):
+    """
+    Shorthand for calculating whether dtype is subtype of some dtypes.
+
+    Also allows specifying a list instead of just a single dtype.
+
+    Additionaly, the most important supertypes from
+        https://numpy.org/doc/stable/reference/arrays.scalars.html
+    can optionally be specified using abbreviations as follows:
+        "i": np.integer
+        "f": np.floating
+        "c": np.complexfloating
+        "n": np.number (contains the other three)
+    """
+    dtypes = dtypes if isinstance(dtypes, list) else [dtypes]
+    # map single character abbreviations, if they are in dtypes
+    mapping = {
+        "i": np.integer,
+        "f": np.floating,
+        "c": np.complexfloating,
+        "n": np.number
+    }
+    dtypes = [mapping.get(x, x) for x in dtypes]
+    return any(np.issubdtype(dtype, dt) for dt in dtypes)
+
+
+def _factorialx_wrapper(fname, n, k, exact, extend):
+    """
+    Shared implementation for factorial, factorial2 & factorialk.
+    """
+    if extend not in ("zero", "complex"):
+        raise ValueError(
+            f"argument `extend` must be either 'zero' or 'complex', received: {extend}"
+        )
+    if exact and extend == "complex":
+        raise ValueError("Incompatible options: `exact=True` and `extend='complex'`")
+
+    msg_unsup = (
+        "Unsupported data type for {vname} in {fname}: {dtype}\n"
+    )
+    if fname == "factorial":
+        msg_unsup += (
+            "Permitted data types are integers and floating point numbers, "
+            "as well as complex numbers if `extend='complex' is passed."
+        )
+    else:
+        msg_unsup += (
+            "Permitted data types are integers, as well as floating point "
+            "numbers and complex numbers if `extend='complex' is passed."
+        )
+    msg_exact_not_possible = (
+        "`exact=True` only supports integers, cannot use data type {dtype}"
+    )
+    msg_needs_complex = (
+        "In order to use non-integer arguments, you must opt into this by passing "
+        "`extend='complex'`. Note that this changes the result for all negative "
+        "arguments (which by default return 0)."
+    )
+
+    if fname == "factorial2":
+        msg_needs_complex += (" Additionally, it will rescale the values of the double"
+                              " factorial at even integers by a factor of sqrt(2/pi).")
+    elif fname == "factorialk":
+        msg_needs_complex += (" Additionally, it will perturb the values of the"
+                              " multifactorial at most positive integers `n`.")
+        # check type of k
+        if not _is_subdtype(type(k), ["i", "f", "c"]):
+            raise ValueError(msg_unsup.format(vname="`k`", fname=fname, dtype=type(k)))
+        elif _is_subdtype(type(k), ["f", "c"]) and extend != "complex":
+            raise ValueError(msg_needs_complex)
+        # check value of k
+        if extend == "zero" and k < 1:
+            msg = f"For `extend='zero'`, k must be a positive integer, received: {k}"
+            raise ValueError(msg)
+        elif k == 0:
+            raise ValueError("Parameter k cannot be zero!")
+
+    # factorial allows floats also for extend="zero"
+    types_requiring_complex = "c" if fname == "factorial" else ["f", "c"]
+
+    # don't use isscalar due to numpy/numpy#23574; 0-dim arrays treated below
+    if np.ndim(n) == 0 and not isinstance(n, np.ndarray):
+        # scalar cases
+        if not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            raise ValueError(msg_unsup.format(vname="`n`", fname=fname, dtype=type(n)))
+        elif _is_subdtype(type(n), types_requiring_complex) and extend != "complex":
+            raise ValueError(msg_needs_complex)
+        elif n is None or np.isnan(n):
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            return np.complex128("nan+nanj") if complexify else np.float64("nan")
+        elif extend == "zero" and n < 0:
+            return 0 if exact else np.float64(0)
+        elif n in {0, 1}:
+            return 1 if exact else np.float64(1)
+        elif exact and _is_subdtype(type(n), "i"):
+            # calculate with integers
+            return _range_prod(1, n, k=k)
+        elif exact:
+            # only relevant for factorial
+            raise ValueError(msg_exact_not_possible.format(dtype=type(n)))
+        # approximation
+        return _factorialx_approx_core(n, k=k, extend=extend)
+
+    # arrays & array-likes
+    n = asarray(n)
+
+    if not _is_subdtype(n.dtype, ["i", "f", "c"]):
+        raise ValueError(msg_unsup.format(vname="`n`", fname=fname, dtype=n.dtype))
+    elif _is_subdtype(n.dtype, types_requiring_complex) and extend != "complex":
+        raise ValueError(msg_needs_complex)
+    elif exact and _is_subdtype(n.dtype, ["f"]):
+        # only relevant for factorial
+        raise ValueError(msg_exact_not_possible.format(dtype=n.dtype))
+
+    if n.size == 0:
+        # return empty arrays unchanged
+        return n
+    elif exact:
+        # calculate with integers
+        return _factorialx_array_exact(n, k=k)
+    # approximation
+    return _factorialx_array_approx(n, k=k, extend=extend)
+
+
+def factorial(n, exact=False, extend="zero"):
+    """
+    The factorial of a number or array of numbers.
+
+    The factorial of non-negative integer `n` is the product of all
+    positive integers less than or equal to `n`::
+
+        n! = n * (n - 1) * (n - 2) * ... * 1
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for ``n!``. Complex values require ``extend='complex'``.
+        By default, the return value for ``n < 0`` is 0.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise approximate using the gamma function
+        (faster, but yields floats instead of integers).
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0``
+        are handled - by default they are 0, but it is possible to opt into the
+        complex extension of the factorial (see below).
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Factorial of ``n``, as integer, float or complex (depending on ``exact``
+        and ``extend``). Array inputs are returned as arrays.
+
+    Notes
+    -----
+    For arrays with ``exact=True``, the factorial is computed only once, for
+    the largest input, with each other result computed in the process.
+    The output dtype is increased to ``int64`` or ``object`` if necessary.
+
+    With ``exact=False`` the factorial is approximated using the gamma
+    function (which is also the definition of the complex extension):
+
+    .. math:: n! = \\Gamma(n+1)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import factorial
+    >>> arr = np.array([3, 4, 5])
+    >>> factorial(arr, exact=False)
+    array([   6.,   24.,  120.])
+    >>> factorial(arr, exact=True)
+    array([  6,  24, 120])
+    >>> factorial(5, exact=True)
+    120
+
+    """
+    return _factorialx_wrapper("factorial", n, k=1, exact=exact, extend=extend)
+
+
+def factorial2(n, exact=False, extend="zero"):
+    """Double factorial.
+
+    This is the factorial with every second value skipped.  E.g., ``7!! = 7 * 5
+    * 3 * 1``.  It can be approximated numerically as::
+
+      n!! = 2 ** (n / 2) * gamma(n / 2 + 1) * sqrt(2 / pi)  n odd
+          = 2 ** (n / 2) * gamma(n / 2 + 1)                 n even
+          = 2 ** (n / 2) * (n / 2)!                         n even
+
+    The formula for odd ``n`` is the basis for the complex extension.
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for ``n!!``. Non-integer values require ``extend='complex'``.
+        By default, the return value for ``n < 0`` is 0.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise use above approximation (faster,
+        but yields floats instead of integers).
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0``
+        are handled - by default they are 0, but it is possible to opt into the
+        complex extension of the double factorial. This also enables passing
+        complex values to ``n``.
+
+        .. warning::
+
+           Using the ``'complex'`` extension also changes the values of the
+           double factorial for even integers, reducing them by a factor of
+           ``sqrt(2/pi) ~= 0.79``, see [1].
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Double factorial of ``n``, as integer, float or complex (depending on
+        ``exact`` and ``extend``). Array inputs are returned as arrays.
+
+    Examples
+    --------
+    >>> from scipy.special import factorial2
+    >>> factorial2(7, exact=False)
+    array(105.00000000000001)
+    >>> factorial2(7, exact=True)
+    105
+
+    References
+    ----------
+    .. [1] Complex extension to double factorial
+            https://en.wikipedia.org/wiki/Double_factorial#Complex_arguments
+    """
+    return _factorialx_wrapper("factorial2", n, k=2, exact=exact, extend=extend)
+
+
+def factorialk(n, k, exact=False, extend="zero"):
+    """Multifactorial of n of order k, n(!!...!).
+
+    This is the multifactorial of n skipping k values.  For example,
+
+      factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
+
+    In particular, for any integer ``n``, we have
+
+      factorialk(n, 1) = factorial(n)
+
+      factorialk(n, 2) = factorial2(n)
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for multifactorial. Non-integer values require
+        ``extend='complex'``. By default, the return value for ``n < 0`` is 0.
+    n : int or float or complex (or array_like thereof)
+        Order of multifactorial. Non-integer values require ``extend='complex'``.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise use an approximation (faster,
+        but yields floats instead of integers)
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0`` are
+        handled - by default they are 0, but it is possible to opt into the complex
+        extension of the multifactorial. This enables passing complex values,
+        not only to ``n`` but also to ``k``.
+
+        .. warning::
+
+           Using the ``'complex'`` extension also changes the values of the
+           multifactorial at integers ``n != 1 (mod k)`` by a factor depending
+           on both ``k`` and ``n % k``, see below or [1].
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Multifactorial (order ``k``) of ``n``, as integer, float or complex (depending
+        on ``exact`` and ``extend``). Array inputs are returned as arrays.
+
+    Examples
+    --------
+    >>> from scipy.special import factorialk
+    >>> factorialk(5, k=1, exact=True)
+    120
+    >>> factorialk(5, k=3, exact=True)
+    10
+    >>> factorialk([5, 7, 9], k=3, exact=True)
+    array([ 10,  28, 162])
+    >>> factorialk([5, 7, 9], k=3, exact=False)
+    array([ 10.,  28., 162.])
+
+    Notes
+    -----
+    While less straight-forward than for the double-factorial, it's possible to
+    calculate a general approximation formula of n!(k) by studying ``n`` for a given
+    remainder ``r < k`` (thus ``n = m * k + r``, resp. ``r = n % k``), which can be
+    put together into something valid for all integer values ``n >= 0`` & ``k > 0``::
+
+      n!(k) = k ** ((n - r)/k) * gamma(n/k + 1) / gamma(r/k + 1) * max(r, 1)
+
+    This is the basis of the approximation when ``exact=False``.
+
+    In principle, any fixed choice of ``r`` (ignoring its relation ``r = n%k``
+    to ``n``) would provide a suitable analytic continuation from integer ``n``
+    to complex ``z`` (not only satisfying the functional equation but also
+    being logarithmically convex, c.f. Bohr-Mollerup theorem) -- in fact, the
+    choice of ``r`` above only changes the function by a constant factor. The
+    final constraint that determines the canonical continuation is ``f(1) = 1``,
+    which forces ``r = 1`` (see also [1]).::
+
+      z!(k) = k ** ((z - 1)/k) * gamma(z/k + 1) / gamma(1/k + 1)
+
+    References
+    ----------
+    .. [1] Complex extension to multifactorial
+            https://en.wikipedia.org/wiki/Double_factorial#Alternative_extension_of_the_multifactorial
+    """
+    return _factorialx_wrapper("factorialk", n, k=k, exact=exact, extend=extend)
+
+
+def stirling2(N, K, *, exact=False):
+    r"""Generate Stirling number(s) of the second kind.
+
+    Stirling numbers of the second kind count the number of ways to
+    partition a set with N elements into K non-empty subsets.
+
+    The values this function returns are calculated using a dynamic
+    program which avoids redundant computation across the subproblems
+    in the solution. For array-like input, this implementation also
+    avoids redundant computation across the different Stirling number
+    calculations.
+
+    The numbers are sometimes denoted
+
+    .. math::
+
+        {N \brace{K}}
+
+    see [1]_ for details. This is often expressed-verbally-as
+    "N subset K".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    K : int, ndarray
+        Number of non-empty subsets taken.
+    exact : bool, optional
+        Uses dynamic programming (DP) with floating point
+        numbers for smaller arrays and uses a second order approximation due to
+        Temme for larger entries  of `N` and `K` that allows trading speed for
+        accuracy. See [2]_ for a description. Temme approximation is used for
+        values ``n>50``. The max error from the DP has max relative error
+        ``4.5*10^-16`` for ``n<=50`` and the max error from the Temme approximation
+        has max relative error ``5*10^-5`` for ``51 <= n < 70`` and
+        ``9*10^-6`` for ``70 <= n < 101``. Note that these max relative errors will
+        decrease further as `n` increases.
+
+    Returns
+    -------
+    val : int, float, ndarray
+        The number of partitions.
+
+    See Also
+    --------
+    comb : The number of combinations of N things taken k at a time.
+
+    Notes
+    -----
+    - If N < 0, or K < 0, then 0 is returned.
+    - If K > N, then 0 is returned.
+
+    The output type will always be `int` or ndarray of `object`.
+    The input must contain either numpy or python integers otherwise a
+    TypeError is raised.
+
+    References
+    ----------
+    .. [1] R. L. Graham, D. E. Knuth and O. Patashnik, "Concrete
+        Mathematics: A Foundation for Computer Science," Addison-Wesley
+        Publishing Company, Boston, 1989. Chapter 6, page 258.
+
+    .. [2] Temme, Nico M. "Asymptotic estimates of Stirling numbers."
+        Studies in Applied Mathematics 89.3 (1993): 233-243.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import stirling2
+    >>> k = np.array([3, -1, 3])
+    >>> n = np.array([10, 10, 9])
+    >>> stirling2(n, k)
+    array([9330.0, 0.0, 3025.0])
+
+    """
+    output_is_scalar = np.isscalar(N) and np.isscalar(K)
+    # make a min-heap of unique (n,k) pairs
+    N, K = asarray(N), asarray(K)
+    if not np.issubdtype(N.dtype, np.integer):
+        raise TypeError("Argument `N` must contain only integers")
+    if not np.issubdtype(K.dtype, np.integer):
+        raise TypeError("Argument `K` must contain only integers")
+    if not exact:
+        # NOTE: here we allow np.uint via casting to double types prior to
+        # passing to private ufunc dispatcher. All dispatched functions
+        # take double type for (n,k) arguments and return double.
+        return _stirling2_inexact(N.astype(float), K.astype(float))
+    nk_pairs = list(
+        set([(n.take(0), k.take(0))
+             for n, k in np.nditer([N, K], ['refs_ok'])])
+    )
+    heapify(nk_pairs)
+    # base mapping for small values
+    snsk_vals = defaultdict(int)
+    for pair in [(0, 0), (1, 1), (2, 1), (2, 2)]:
+        snsk_vals[pair] = 1
+    # for each pair in the min-heap, calculate the value, store for later
+    n_old, n_row = 2, [0, 1, 1]
+    while nk_pairs:
+        n, k = heappop(nk_pairs)
+        if n < 2 or k > n or k <= 0:
+            continue
+        elif k == n or k == 1:
+            snsk_vals[(n, k)] = 1
+            continue
+        elif n != n_old:
+            num_iters = n - n_old
+            while num_iters > 0:
+                n_row.append(1)
+                # traverse from back to remove second row
+                for j in range(len(n_row)-2, 1, -1):
+                    n_row[j] = n_row[j]*j + n_row[j-1]
+                num_iters -= 1
+            snsk_vals[(n, k)] = n_row[k]
+        else:
+            snsk_vals[(n, k)] = n_row[k]
+        n_old, n_row = n, n_row
+    out_types = [object, object, object] if exact else [float, float, float]
+    # for each pair in the map, fetch the value, and populate the array
+    it = np.nditer(
+        [N, K, None],
+        ['buffered', 'refs_ok'],
+        [['readonly'], ['readonly'], ['writeonly', 'allocate']],
+        op_dtypes=out_types,
+    )
+    with it:
+        while not it.finished:
+            it[2] = snsk_vals[(int(it[0]), int(it[1]))]
+            it.iternext()
+        output = it.operands[2]
+        # If N and K were both scalars, convert output to scalar.
+        if output_is_scalar:
+            output = output.take(0)
+    return output
+
+
+def zeta(x, q=None, out=None):
+    r"""
+    Riemann or Hurwitz zeta function.
+
+    Parameters
+    ----------
+    x : array_like of float or complex.
+        Input data
+    q : array_like of float, optional
+        Input data, must be real.  Defaults to Riemann zeta. When `q` is
+        ``None``, complex inputs `x` are supported. If `q` is not ``None``,
+        then currently only real inputs `x` with ``x >= 1`` are supported,
+        even when ``q = 1.0`` (corresponding to the Riemann zeta function).
+
+    out : ndarray, optional
+        Output array for the computed values.
+
+    Returns
+    -------
+    out : array_like
+        Values of zeta(x).
+
+    See Also
+    --------
+    zetac
+
+    Notes
+    -----
+    The two-argument version is the Hurwitz zeta function
+
+    .. math::
+
+        \zeta(x, q) = \sum_{k=0}^{\infty} \frac{1}{(k + q)^x};
+
+    see [dlmf]_ for details. The Riemann zeta function corresponds to
+    the case when ``q = 1``.
+
+    For complex inputs with ``q = None``, points with
+    ``abs(z.imag) > 1e9`` and ``0 <= abs(z.real) < 2.5`` are currently not
+    supported due to slow convergence causing excessive runtime.
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/25.11#i
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import zeta, polygamma, factorial
+
+    Some specific values:
+
+    >>> zeta(2), np.pi**2/6
+    (1.6449340668482266, 1.6449340668482264)
+
+    >>> zeta(4), np.pi**4/90
+    (1.0823232337111381, 1.082323233711138)
+
+    First nontrivial zero:
+
+    >>> zeta(0.5 + 14.134725141734695j)
+    0 + 0j
+
+    Relation to the `polygamma` function:
+
+    >>> m = 3
+    >>> x = 1.25
+    >>> polygamma(m, x)
+    array(2.782144009188397)
+    >>> (-1)**(m+1) * factorial(m) * zeta(m+1, x)
+    2.7821440091883969
+
+    """
+    if q is None:
+        return _ufuncs._riemann_zeta(x, out)
+    else:
+        return _ufuncs._zeta(x, q, out)
+
+
+def softplus(x, **kwargs):
+    r"""
+    Compute the softplus function element-wise.
+
+    The softplus function is defined as: ``softplus(x) = log(1 + exp(x))``.
+    It is a smooth approximation of the rectifier function (ReLU).
+
+    Parameters
+    ----------
+    x : array_like
+        Input value.
+    **kwargs
+        For other keyword-only arguments, see the
+        `ufunc docs `_.
+
+    Returns
+    -------
+    softplus : ndarray
+        Logarithm of ``exp(0) + exp(x)``.
+
+    Examples
+    --------
+    >>> from scipy import special
+
+    >>> special.softplus(0)
+    0.6931471805599453
+
+    >>> special.softplus([-1, 0, 1])
+    array([0.31326169, 0.69314718, 1.31326169])
+    """
+    return np.logaddexp(0, x, **kwargs)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..e0598ff2d395e08055065c94341de42ce84c5651
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b1ce34aa58054be13edfd5d87f2059e8a0d9224
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py
@@ -0,0 +1,214 @@
+import numpy as np
+
+from ._ufuncs import _ellip_harm
+from ._ellip_harm_2 import _ellipsoid, _ellipsoid_norm
+
+
+def ellip_harm(h2, k2, n, p, s, signm=1, signn=1):
+    r"""
+    Ellipsoidal harmonic functions E^p_n(l)
+
+    These are also known as Lame functions of the first kind, and are
+    solutions to the Lame equation:
+
+    .. math:: (s^2 - h^2)(s^2 - k^2)E''(s)
+              + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0
+
+    where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
+    returned) corresponding to the solutions.
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree
+    s : float
+        Coordinate
+    p : int
+        Order, can range between [1,2n+1]
+    signm : {1, -1}, optional
+        Sign of prefactor of functions. Can be +/-1. See Notes.
+    signn : {1, -1}, optional
+        Sign of prefactor of functions. Can be +/-1. See Notes.
+
+    Returns
+    -------
+    E : float
+        the harmonic :math:`E^p_n(s)`
+
+    See Also
+    --------
+    ellip_harm_2, ellip_normal
+
+    Notes
+    -----
+    The geometric interpretation of the ellipsoidal functions is
+    explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the
+    sign of prefactors for functions according to their type::
+
+        K : +1
+        L : signm
+        M : signn
+        N : signm*signn
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Digital Library of Mathematical Functions 29.12
+       https://dlmf.nist.gov/29.12
+    .. [2] Bardhan and Knepley, "Computational science and
+       re-discovery: open-source implementations of
+       ellipsoidal harmonics for problems in potential theory",
+       Comput. Sci. Disc. 5, 014006 (2012)
+       :doi:`10.1088/1749-4699/5/1/014006`.
+    .. [3] David J.and Dechambre P, "Computation of Ellipsoidal
+       Gravity Field Harmonics for small solar system bodies"
+       pp. 30-36, 2000
+    .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications"
+       pp. 418, 2012
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_harm
+    >>> w = ellip_harm(5,8,1,1,2.5)
+    >>> w
+    2.5
+
+    Check that the functions indeed are solutions to the Lame equation:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> def eigenvalue(f, df, ddf):
+    ...     r = (((s**2 - h**2) * (s**2 - k**2) * ddf
+    ...           + s * (2*s**2 - h**2 - k**2) * df
+    ...           - n * (n + 1)*s**2*f) / f)
+    ...     return -r.mean(), r.std()
+    >>> s = np.linspace(0.1, 10, 200)
+    >>> k, h, n, p = 8.0, 2.2, 3, 2
+    >>> E = ellip_harm(h**2, k**2, n, p, s)
+    >>> E_spl = UnivariateSpline(s, E)
+    >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2))
+    >>> a, a_err
+    (583.44366156701483, 6.4580890640310646e-11)
+
+    """  # noqa: E501
+    return _ellip_harm(h2, k2, n, p, s, signm, signn)
+
+
+_ellip_harm_2_vec = np.vectorize(_ellipsoid, otypes='d')
+
+
+def ellip_harm_2(h2, k2, n, p, s):
+    r"""
+    Ellipsoidal harmonic functions F^p_n(l)
+
+    These are also known as Lame functions of the second kind, and are
+    solutions to the Lame equation:
+
+    .. math:: (s^2 - h^2)(s^2 - k^2)F''(s)
+              + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0
+
+    where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
+    returned) corresponding to the solutions.
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree.
+    p : int
+        Order, can range between [1,2n+1].
+    s : float
+        Coordinate
+
+    Returns
+    -------
+    F : float
+        The harmonic :math:`F^p_n(s)`
+
+    See Also
+    --------
+    ellip_harm, ellip_normal
+
+    Notes
+    -----
+    Lame functions of the second kind are related to the functions of the first kind:
+
+    .. math::
+
+       F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s}
+       \frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}}
+
+    .. versionadded:: 0.15.0
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_harm_2
+    >>> w = ellip_harm_2(5,8,2,1,10)
+    >>> w
+    0.00108056853382
+
+    """
+    with np.errstate(all='ignore'):
+        return _ellip_harm_2_vec(h2, k2, n, p, s)
+
+
+def _ellip_normal_vec(h2, k2, n, p):
+    return _ellipsoid_norm(h2, k2, n, p)
+
+
+_ellip_normal_vec = np.vectorize(_ellip_normal_vec, otypes='d')
+
+
+def ellip_normal(h2, k2, n, p):
+    r"""
+    Ellipsoidal harmonic normalization constants gamma^p_n
+
+    The normalization constant is defined as
+
+    .. math::
+
+       \gamma^p_n=8\int_{0}^{h}dx\int_{h}^{k}dy
+       \frac{(y^2-x^2)(E^p_n(y)E^p_n(x))^2}{\sqrt((k^2-y^2)(y^2-h^2)(h^2-x^2)(k^2-x^2)}
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree.
+    p : int
+        Order, can range between [1,2n+1].
+
+    Returns
+    -------
+    gamma : float
+        The normalization constant :math:`\gamma^p_n`
+
+    See Also
+    --------
+    ellip_harm, ellip_harm_2
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_normal
+    >>> w = ellip_normal(5,8,3,7)
+    >>> w
+    1723.38796997
+
+    """
+    with np.errstate(all='ignore'):
+        return _ellip_normal_vec(h2, k2, n, p)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5b7fe36df87617bf91655623ee0076c37a4d08a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py
@@ -0,0 +1,17 @@
+import math
+import operator
+
+def _nonneg_int_or_fail(n, var_name, strict=True):
+    try:
+        if strict:
+            # Raises an exception if float
+            n = operator.index(n)
+        elif n == math.floor(n):
+            n = int(n)
+        else:
+            raise ValueError()
+        if n < 0:
+            raise ValueError()
+    except (ValueError, TypeError) as err:
+        raise err.__class__(f"{var_name} must be a non-negative integer") from err
+    return n
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..f758c7c21fdddc0ec1b84727d90c6de7f34a094e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py
@@ -0,0 +1,149 @@
+from ._ufuncs import _lambertw
+
+import numpy as np
+
+
+def lambertw(z, k=0, tol=1e-8):
+    r"""
+    lambertw(z, k=0, tol=1e-8)
+
+    Lambert W function.
+
+    The Lambert W function `W(z)` is defined as the inverse function
+    of ``w * exp(w)``. In other words, the value of ``W(z)`` is
+    such that ``z = W(z) * exp(W(z))`` for any complex number
+    ``z``.
+
+    The Lambert W function is a multivalued function with infinitely
+    many branches. Each branch gives a separate solution of the
+    equation ``z = w exp(w)``. Here, the branches are indexed by the
+    integer `k`.
+
+    Parameters
+    ----------
+    z : array_like
+        Input argument.
+    k : int, optional
+        Branch index.
+    tol : float, optional
+        Evaluation tolerance.
+
+    Returns
+    -------
+    w : array
+        `w` will have the same shape as `z`.
+
+    See Also
+    --------
+    wrightomega : the Wright Omega function
+
+    Notes
+    -----
+    All branches are supported by `lambertw`:
+
+    * ``lambertw(z)`` gives the principal solution (branch 0)
+    * ``lambertw(z, k)`` gives the solution on branch `k`
+
+    The Lambert W function has two partially real branches: the
+    principal branch (`k = 0`) is real for real ``z > -1/e``, and the
+    ``k = -1`` branch is real for ``-1/e < z < 0``. All branches except
+    ``k = 0`` have a logarithmic singularity at ``z = 0``.
+
+    **Possible issues**
+
+    The evaluation can become inaccurate very close to the branch point
+    at ``-1/e``. In some corner cases, `lambertw` might currently
+    fail to converge, or can end up on the wrong branch.
+
+    **Algorithm**
+
+    Halley's iteration is used to invert ``w * exp(w)``, using a first-order
+    asymptotic approximation (O(log(w)) or `O(w)`) as the initial estimate.
+
+    The definition, implementation and choice of branches is based on [2]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Lambert_W_function
+    .. [2] Corless et al, "On the Lambert W function", Adv. Comp. Math. 5
+       (1996) 329-359.
+       https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
+
+    Examples
+    --------
+    The Lambert W function is the inverse of ``w exp(w)``:
+
+    >>> import numpy as np
+    >>> from scipy.special import lambertw
+    >>> w = lambertw(1)
+    >>> w
+    (0.56714329040978384+0j)
+    >>> w * np.exp(w)
+    (1.0+0j)
+
+    Any branch gives a valid inverse:
+
+    >>> w = lambertw(1, k=3)
+    >>> w
+    (-2.8535817554090377+17.113535539412148j)
+    >>> w*np.exp(w)
+    (1.0000000000000002+1.609823385706477e-15j)
+
+    **Applications to equation-solving**
+
+    The Lambert W function may be used to solve various kinds of
+    equations.  We give two examples here.
+
+    First, the function can be used to solve implicit equations of the
+    form
+
+        :math:`x = a + b e^{c x}`
+
+    for :math:`x`.  We assume :math:`c` is not zero.  After a little
+    algebra, the equation may be written
+
+        :math:`z e^z = -b c e^{a c}`
+
+    where :math:`z = c (a - x)`.  :math:`z` may then be expressed using
+    the Lambert W function
+
+        :math:`z = W(-b c e^{a c})`
+
+    giving
+
+        :math:`x = a - W(-b c e^{a c})/c`
+
+    For example,
+
+    >>> a = 3
+    >>> b = 2
+    >>> c = -0.5
+
+    The solution to :math:`x = a + b e^{c x}` is:
+
+    >>> x = a - lambertw(-b*c*np.exp(a*c))/c
+    >>> x
+    (3.3707498368978794+0j)
+
+    Verify that it solves the equation:
+
+    >>> a + b*np.exp(c*x)
+    (3.37074983689788+0j)
+
+    The Lambert W function may also be used find the value of the infinite
+    power tower :math:`z^{z^{z^{\ldots}}}`:
+
+    >>> def tower(z, n):
+    ...     if n == 0:
+    ...         return z
+    ...     return z ** tower(z, n-1)
+    ...
+    >>> tower(0.5, 100)
+    0.641185744504986
+    >>> -lambertw(-np.log(0.5)) / np.log(0.5)
+    (0.64118574450498589+0j)
+    """
+    # TODO: special expert should inspect this
+    # interception; better place to do it?
+    k = np.asarray(k, dtype=np.dtype("long"))
+    return _lambertw(z, k, tol)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b0da953464e8d92925ebdaba79ce062c38fc7e5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py
@@ -0,0 +1,417 @@
+import math
+import numpy as np
+from scipy._lib._util import _asarray_validated
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_broadcast_promote,
+    xp_copy,
+    xp_float_to_complex,
+    is_complex,
+)
+from scipy._lib import array_api_extra as xpx
+
+__all__ = ["logsumexp", "softmax", "log_softmax"]
+
+
+def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):
+    """Compute the log of the sum of exponentials of input elements.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : None or int or tuple of ints, optional
+        Axis or axes over which the sum is taken. By default `axis` is None,
+        and all elements are summed.
+
+        .. versionadded:: 0.11.0
+    b : array-like, optional
+        Scaling factor for exp(`a`) must be of the same shape as `a` or
+        broadcastable to `a`. These values may be negative in order to
+        implement subtraction.
+
+        .. versionadded:: 0.12.0
+    keepdims : bool, optional
+        If this is set to True, the axes which are reduced are left in the
+        result as dimensions with size one. With this option, the result
+        will broadcast correctly against the original array.
+
+        .. versionadded:: 0.15.0
+    return_sign : bool, optional
+        If this is set to True, the result will be a pair containing sign
+        information; if False, results that are negative will be returned
+        as NaN. Default is False (no sign information).
+
+        .. versionadded:: 0.16.0
+
+    Returns
+    -------
+    res : ndarray
+        The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically
+        more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))``
+        is returned. If ``return_sign`` is True, ``res`` contains the log of
+        the absolute value of the argument.
+    sgn : ndarray
+        If ``return_sign`` is True, this will be an array of floating-point
+        numbers matching res containing +1, 0, -1 (for real-valued inputs)
+        or a complex phase (for complex inputs). This gives the sign of the
+        argument of the logarithm in ``res``.
+        If ``return_sign`` is False, only one result is returned.
+
+    See Also
+    --------
+    numpy.logaddexp, numpy.logaddexp2
+
+    Notes
+    -----
+    NumPy has a logaddexp function which is very similar to `logsumexp`, but
+    only handles two arguments. `logaddexp.reduce` is similar to this
+    function, but may be less stable.
+
+    The logarithm is a multivalued function: for each :math:`x` there is an
+    infinite number of :math:`z` such that :math:`exp(z) = x`. The convention
+    is to return the :math:`z` whose imaginary part lies in :math:`(-pi, pi]`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import logsumexp
+    >>> a = np.arange(10)
+    >>> logsumexp(a)
+    9.4586297444267107
+    >>> np.log(np.sum(np.exp(a)))
+    9.4586297444267107
+
+    With weights
+
+    >>> a = np.arange(10)
+    >>> b = np.arange(10, 0, -1)
+    >>> logsumexp(a, b=b)
+    9.9170178533034665
+    >>> np.log(np.sum(b*np.exp(a)))
+    9.9170178533034647
+
+    Returning a sign flag
+
+    >>> logsumexp([1,2],b=[1,-1],return_sign=True)
+    (1.5413248546129181, -1.0)
+
+    Notice that `logsumexp` does not directly support masked arrays. To use it
+    on a masked array, convert the mask into zero weights:
+
+    >>> a = np.ma.array([np.log(2), 2, np.log(3)],
+    ...                  mask=[False, True, False])
+    >>> b = (~a.mask).astype(int)
+    >>> logsumexp(a.data, b=b), np.log(5)
+    1.6094379124341005, 1.6094379124341005
+
+    """
+    xp = array_namespace(a, b)
+    a, b = xp_broadcast_promote(a, b, ensure_writeable=True, force_floating=True, xp=xp)
+    a = xpx.atleast_nd(a, ndim=1, xp=xp)
+    b = xpx.atleast_nd(b, ndim=1, xp=xp) if b is not None else b
+    axis = tuple(range(a.ndim)) if axis is None else axis
+
+    if xp_size(a) != 0:
+        with np.errstate(divide='ignore', invalid='ignore'):  # log of zero is OK
+            out, sgn = _logsumexp(a, b, axis=axis, return_sign=return_sign, xp=xp)
+    else:
+        shape = np.asarray(a.shape)  # NumPy is convenient for shape manipulation
+        shape[axis] = 1
+        out = xp.full(tuple(shape), -xp.inf, dtype=a.dtype)
+        sgn = xp.sign(out)
+
+    if xp.isdtype(out.dtype, 'complex floating'):
+        if return_sign:
+            real = xp.real(sgn)
+            imag = xp_float_to_complex(_wrap_radians(xp.imag(sgn), xp))
+            sgn = real + imag*1j
+        else:
+            real = xp.real(out)
+            imag = xp_float_to_complex(_wrap_radians(xp.imag(out), xp))
+            out = real + imag*1j
+
+    # Deal with shape details - reducing dimensions and convert 0-D to scalar for NumPy
+    out = xp.squeeze(out, axis=axis) if not keepdims else out
+    sgn = xp.squeeze(sgn, axis=axis) if (sgn is not None and not keepdims) else sgn
+    out = out[()] if out.ndim == 0 else out
+    sgn = sgn[()] if (sgn is not None and sgn.ndim == 0) else sgn
+
+    return (out, sgn) if return_sign else out
+
+
+def _wrap_radians(x, xp=None):
+    xp = array_namespace(x) if xp is None else xp
+    # Wrap radians to (-pi, pi] interval
+    out = -((-x + math.pi) % (2 * math.pi) - math.pi)
+    # preserve relative precision
+    no_wrap = xp.abs(x) < xp.pi
+    out[no_wrap] = x[no_wrap]
+    return out
+
+
+def _elements_and_indices_with_max_real(a, axis=-1, xp=None):
+    # This is an array-API compatible `max` function that works something
+    # like `np.max` for complex input. The important part is that it finds
+    # the element with maximum real part. When there are multiple complex values
+    # with this real part, it doesn't matter which we choose.
+    # We could use `argmax` on real component, but array API doesn't yet have
+    # `take_along_axis`, and even if it did, we would have problems with axis tuples.
+    # Feel free to rewrite! It's ugly, but it's not the purpose of the PR, and
+    # it gets the job done.
+    xp = array_namespace(a) if xp is None else xp
+
+    if xp.isdtype(a.dtype, "complex floating"):
+        # select all elements with max real part.
+        real_a = xp.real(a)
+        max = xp.max(real_a, axis=axis, keepdims=True)
+        mask = real_a == max
+
+        # Of those, choose one arbitrarily. This is a reasonably
+        # simple, array-API compatible way of doing so that doesn't
+        # have a problem with `axis` being a tuple or None.
+        i = xp.reshape(xp.arange(xp_size(a)), a.shape)
+        i[~mask] = -1
+        max_i = xp.max(i, axis=axis, keepdims=True)
+        mask = i == max_i
+        a = xp_copy(a)
+        a[~mask] = 0
+        max = xp.sum(a, axis=axis, dtype=a.dtype, keepdims=True)
+    else:
+        max = xp.max(a, axis=axis, keepdims=True)
+        mask = a == max
+
+    return xp.asarray(max), xp.asarray(mask)
+
+
+def _sign(x, xp):
+    return x / xp.where(x == 0, xp.asarray(1, dtype=x.dtype), xp.abs(x))
+
+
+def _logsumexp(a, b, axis, return_sign, xp):
+
+    # This has been around for about a decade, so let's consider it a feature:
+    # Even if element of `a` is infinite or NaN, it adds nothing to the sum if
+    # the corresponding weight is zero.
+    if b is not None:
+        a[b == 0] = -xp.inf
+
+    # Find element with maximum real part, since this is what affects the magnitude
+    # of the exponential. Possible enhancement: include log of `b` magnitude in `a`.
+    a_max, i_max = _elements_and_indices_with_max_real(a, axis=axis, xp=xp)
+
+    # for precision, these terms are separated out of the main sum.
+    a[i_max] = -xp.inf
+    i_max_dt = xp.astype(i_max, a.dtype)
+    # This is an inefficient way of getting `m` because it is the sum of a sparse
+    # array; however, this is the simplest way I can think of to get the right shape.
+    m = (xp.sum(i_max_dt, axis=axis, keepdims=True, dtype=a.dtype) if b is None
+         else xp.sum(b * i_max_dt, axis=axis, keepdims=True, dtype=a.dtype))
+
+    # Arithmetic between infinities will introduce NaNs.
+    # `+ a_max` at the end naturally corrects for removing them here.
+    shift = xp.where(xp.isfinite(a_max), a_max, xp.asarray(0, dtype=a_max.dtype))
+
+    # Shift, exponentiate, scale, and sum
+    exp = b * xp.exp(a - shift) if b is not None else xp.exp(a - shift)
+    s = xp.sum(exp, axis=axis, keepdims=True, dtype=exp.dtype)
+    s = xp.where(s == 0, s, s/m)
+
+    # Separate sign/magnitude information
+    # Originally, this was only performed if `return_sign=True`.
+    # However, this is also needed if any elements of `m < 0` or `s < -1`.
+    # An improvement would be to perform the calculations only on these entries.
+
+    # Use the numpy>=2.0 convention for sign.
+    # When all array libraries agree, this can become sng = xp.sign(s).
+    sgn = _sign(s + 1, xp=xp) * _sign(m, xp=xp)
+
+    if xp.isdtype(s.dtype, "real floating"):
+        # The log functions need positive arguments
+        s = xp.where(s < -1, -s - 2, s)
+        m = xp.abs(m)
+    else:
+        # `a_max` can have a sign component for complex input
+        sgn = sgn * xp.exp(xp.imag(a_max) * xp.asarray(1.0j, dtype=a_max.dtype))
+
+    # Take log and undo shift
+    out = xp.log1p(s) + xp.log(m) + a_max
+
+    if return_sign:
+        if is_complex(out, xp):
+            out = xp.real(out)
+    elif xp.isdtype(out.dtype, 'real floating'):
+        out[sgn < 0] = xp.nan
+
+    return out, sgn
+
+
+def softmax(x, axis=None):
+    r"""Compute the softmax function.
+
+    The softmax function transforms each element of a collection by
+    computing the exponential of each element divided by the sum of the
+    exponentials of all the elements. That is, if `x` is a one-dimensional
+    numpy array::
+
+        softmax(x) = np.exp(x)/sum(np.exp(x))
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axis : int or tuple of ints, optional
+        Axis to compute values along. Default is None and softmax will be
+        computed over the entire array `x`.
+
+    Returns
+    -------
+    s : ndarray
+        An array the same shape as `x`. The result will sum to 1 along the
+        specified axis.
+
+    Notes
+    -----
+    The formula for the softmax function :math:`\sigma(x)` for a vector
+    :math:`x = \{x_0, x_1, ..., x_{n-1}\}` is
+
+    .. math:: \sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}}
+
+    The `softmax` function is the gradient of `logsumexp`.
+
+    The implementation uses shifting to avoid overflow. See [1]_ for more
+    details.
+
+    .. versionadded:: 1.2.0
+
+    References
+    ----------
+    .. [1] P. Blanchard, D.J. Higham, N.J. Higham, "Accurately computing the
+       log-sum-exp and softmax functions", IMA Journal of Numerical Analysis,
+       Vol.41(4), :doi:`10.1093/imanum/draa038`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import softmax
+    >>> np.set_printoptions(precision=5)
+
+    >>> x = np.array([[1, 0.5, 0.2, 3],
+    ...               [1,  -1,   7, 3],
+    ...               [2,  12,  13, 3]])
+    ...
+
+    Compute the softmax transformation over the entire array.
+
+    >>> m = softmax(x)
+    >>> m
+    array([[  4.48309e-06,   2.71913e-06,   2.01438e-06,   3.31258e-05],
+           [  4.48309e-06,   6.06720e-07,   1.80861e-03,   3.31258e-05],
+           [  1.21863e-05,   2.68421e-01,   7.29644e-01,   3.31258e-05]])
+
+    >>> m.sum()
+    1.0
+
+    Compute the softmax transformation along the first axis (i.e., the
+    columns).
+
+    >>> m = softmax(x, axis=0)
+
+    >>> m
+    array([[  2.11942e-01,   1.01300e-05,   2.75394e-06,   3.33333e-01],
+           [  2.11942e-01,   2.26030e-06,   2.47262e-03,   3.33333e-01],
+           [  5.76117e-01,   9.99988e-01,   9.97525e-01,   3.33333e-01]])
+
+    >>> m.sum(axis=0)
+    array([ 1.,  1.,  1.,  1.])
+
+    Compute the softmax transformation along the second axis (i.e., the rows).
+
+    >>> m = softmax(x, axis=1)
+    >>> m
+    array([[  1.05877e-01,   6.42177e-02,   4.75736e-02,   7.82332e-01],
+           [  2.42746e-03,   3.28521e-04,   9.79307e-01,   1.79366e-02],
+           [  1.22094e-05,   2.68929e-01,   7.31025e-01,   3.31885e-05]])
+
+    >>> m.sum(axis=1)
+    array([ 1.,  1.,  1.])
+
+    """
+    x = _asarray_validated(x, check_finite=False)
+    x_max = np.amax(x, axis=axis, keepdims=True)
+    exp_x_shifted = np.exp(x - x_max)
+    return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
+
+
+def log_softmax(x, axis=None):
+    r"""Compute the logarithm of the softmax function.
+
+    In principle::
+
+        log_softmax(x) = log(softmax(x))
+
+    but using a more accurate implementation.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axis : int or tuple of ints, optional
+        Axis to compute values along. Default is None and softmax will be
+        computed over the entire array `x`.
+
+    Returns
+    -------
+    s : ndarray or scalar
+        An array with the same shape as `x`. Exponential of the result will
+        sum to 1 along the specified axis. If `x` is a scalar, a scalar is
+        returned.
+
+    Notes
+    -----
+    `log_softmax` is more accurate than ``np.log(softmax(x))`` with inputs that
+    make `softmax` saturate (see examples below).
+
+    .. versionadded:: 1.5.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import log_softmax
+    >>> from scipy.special import softmax
+    >>> np.set_printoptions(precision=5)
+
+    >>> x = np.array([1000.0, 1.0])
+
+    >>> y = log_softmax(x)
+    >>> y
+    array([   0., -999.])
+
+    >>> with np.errstate(divide='ignore'):
+    ...   y = np.log(softmax(x))
+    ...
+    >>> y
+    array([  0., -inf])
+
+    """
+
+    x = _asarray_validated(x, check_finite=False)
+
+    x_max = np.amax(x, axis=axis, keepdims=True)
+
+    if x_max.ndim > 0:
+        x_max[~np.isfinite(x_max)] = 0
+    elif not np.isfinite(x_max):
+        x_max = 0
+
+    tmp = x - x_max
+    exp_tmp = np.exp(tmp)
+
+    # suppress warnings about log of zero
+    with np.errstate(divide='ignore'):
+        s = np.sum(exp_tmp, axis=axis, keepdims=True)
+        out = np.log(s)
+
+    out = tmp - out
+    return out
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e519093dface79e21f16d7063541ad107f5ca96
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py
@@ -0,0 +1,453 @@
+import os
+import sys
+import time
+from itertools import zip_longest
+
+import numpy as np
+from numpy.testing import assert_
+import pytest
+
+from scipy.special._testutils import assert_func_equal
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+# ------------------------------------------------------------------------------
+# Machinery for systematic tests with mpmath
+# ------------------------------------------------------------------------------
+
+class Arg:
+    """Generate a set of numbers on the real axis, concentrating on
+    'interesting' regions and covering all orders of magnitude.
+
+    """
+
+    def __init__(self, a=-np.inf, b=np.inf, inclusive_a=True, inclusive_b=True):
+        if a > b:
+            raise ValueError("a should be less than or equal to b")
+        if a == -np.inf:
+            a = -0.5*np.finfo(float).max
+        if b == np.inf:
+            b = 0.5*np.finfo(float).max
+        self.a, self.b = a, b
+
+        self.inclusive_a, self.inclusive_b = inclusive_a, inclusive_b
+
+    def _positive_values(self, a, b, n):
+        if a < 0:
+            raise ValueError("a should be positive")
+
+        # Try to put half of the points into a linspace between a and
+        # 10 the other half in a logspace.
+        if n % 2 == 0:
+            nlogpts = n//2
+            nlinpts = nlogpts
+        else:
+            nlogpts = n//2
+            nlinpts = nlogpts + 1
+
+        if a >= 10:
+            # Outside of linspace range; just return a logspace.
+            pts = np.logspace(np.log10(a), np.log10(b), n)
+        elif a > 0 and b < 10:
+            # Outside of logspace range; just return a linspace
+            pts = np.linspace(a, b, n)
+        elif a > 0:
+            # Linspace between a and 10 and a logspace between 10 and
+            # b.
+            linpts = np.linspace(a, 10, nlinpts, endpoint=False)
+            logpts = np.logspace(1, np.log10(b), nlogpts)
+            pts = np.hstack((linpts, logpts))
+        elif a == 0 and b <= 10:
+            # Linspace between 0 and b and a logspace between 0 and
+            # the smallest positive point of the linspace
+            linpts = np.linspace(0, b, nlinpts)
+            if linpts.size > 1:
+                right = np.log10(linpts[1])
+            else:
+                right = -30
+            logpts = np.logspace(-30, right, nlogpts, endpoint=False)
+            pts = np.hstack((logpts, linpts))
+        else:
+            # Linspace between 0 and 10, logspace between 0 and the
+            # smallest positive point of the linspace, and a logspace
+            # between 10 and b.
+            if nlogpts % 2 == 0:
+                nlogpts1 = nlogpts//2
+                nlogpts2 = nlogpts1
+            else:
+                nlogpts1 = nlogpts//2
+                nlogpts2 = nlogpts1 + 1
+            linpts = np.linspace(0, 10, nlinpts, endpoint=False)
+            if linpts.size > 1:
+                right = np.log10(linpts[1])
+            else:
+                right = -30
+            logpts1 = np.logspace(-30, right, nlogpts1, endpoint=False)
+            logpts2 = np.logspace(1, np.log10(b), nlogpts2)
+            pts = np.hstack((logpts1, linpts, logpts2))
+
+        return np.sort(pts)
+
+    def values(self, n):
+        """Return an array containing n numbers."""
+        a, b = self.a, self.b
+        if a == b:
+            return np.zeros(n)
+
+        if not self.inclusive_a:
+            n += 1
+        if not self.inclusive_b:
+            n += 1
+
+        if n % 2 == 0:
+            n1 = n//2
+            n2 = n1
+        else:
+            n1 = n//2
+            n2 = n1 + 1
+
+        if a >= 0:
+            pospts = self._positive_values(a, b, n)
+            negpts = []
+        elif b <= 0:
+            pospts = []
+            negpts = -self._positive_values(-b, -a, n)
+        else:
+            pospts = self._positive_values(0, b, n1)
+            negpts = -self._positive_values(0, -a, n2 + 1)
+            # Don't want to get zero twice
+            negpts = negpts[1:]
+        pts = np.hstack((negpts[::-1], pospts))
+
+        if not self.inclusive_a:
+            pts = pts[1:]
+        if not self.inclusive_b:
+            pts = pts[:-1]
+        return pts
+
+
+class FixedArg:
+    def __init__(self, values):
+        self._values = np.asarray(values)
+
+    def values(self, n):
+        return self._values
+
+
+class ComplexArg:
+    def __init__(self, a=complex(-np.inf, -np.inf), b=complex(np.inf, np.inf)):
+        self.real = Arg(a.real, b.real)
+        self.imag = Arg(a.imag, b.imag)
+
+    def values(self, n):
+        m = int(np.floor(np.sqrt(n)))
+        x = self.real.values(m)
+        y = self.imag.values(m + 1)
+        return (x[:,None] + 1j*y[None,:]).ravel()
+
+
+class IntArg:
+    def __init__(self, a=-1000, b=1000):
+        self.a = a
+        self.b = b
+
+    def values(self, n):
+        v1 = Arg(self.a, self.b).values(max(1 + n//2, n-5)).astype(int)
+        v2 = np.arange(-5, 5)
+        v = np.unique(np.r_[v1, v2])
+        v = v[(v >= self.a) & (v < self.b)]
+        return v
+
+
+def get_args(argspec, n):
+    if isinstance(argspec, np.ndarray):
+        args = argspec.copy()
+    else:
+        nargs = len(argspec)
+        ms = np.asarray(
+            [1.5 if isinstance(spec, ComplexArg) else 1.0 for spec in argspec]
+        )
+        ms = (n**(ms/sum(ms))).astype(int) + 1
+
+        args = [spec.values(m) for spec, m in zip(argspec, ms)]
+        args = np.array(np.broadcast_arrays(*np.ix_(*args))).reshape(nargs, -1).T
+
+    return args
+
+
+class MpmathData:
+    def __init__(self, scipy_func, mpmath_func, arg_spec, name=None,
+                 dps=None, prec=None, n=None, rtol=1e-7, atol=1e-300,
+                 ignore_inf_sign=False, distinguish_nan_and_inf=True,
+                 nan_ok=True, param_filter=None):
+
+        # mpmath tests are really slow (see gh-6989).  Use a small number of
+        # points by default, increase back to 5000 (old default) if XSLOW is
+        # set
+        if n is None:
+            try:
+                is_xslow = int(os.environ.get('SCIPY_XSLOW', '0'))
+            except ValueError:
+                is_xslow = False
+
+            n = 5000 if is_xslow else 500
+
+        self.scipy_func = scipy_func
+        self.mpmath_func = mpmath_func
+        self.arg_spec = arg_spec
+        self.dps = dps
+        self.prec = prec
+        self.n = n
+        self.rtol = rtol
+        self.atol = atol
+        self.ignore_inf_sign = ignore_inf_sign
+        self.nan_ok = nan_ok
+        if isinstance(self.arg_spec, np.ndarray):
+            self.is_complex = np.issubdtype(self.arg_spec.dtype, np.complexfloating)
+        else:
+            self.is_complex = any(
+                [isinstance(arg, ComplexArg) for arg in self.arg_spec]
+            )
+        self.ignore_inf_sign = ignore_inf_sign
+        self.distinguish_nan_and_inf = distinguish_nan_and_inf
+        if not name or name == '':
+            name = getattr(scipy_func, '__name__', None)
+        if not name or name == '':
+            name = getattr(mpmath_func, '__name__', None)
+        self.name = name
+        self.param_filter = param_filter
+
+    def check(self):
+        np.random.seed(1234)
+
+        # Generate values for the arguments
+        argarr = get_args(self.arg_spec, self.n)
+
+        # Check
+        old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+        try:
+            if self.dps is not None:
+                dps_list = [self.dps]
+            else:
+                dps_list = [20]
+            if self.prec is not None:
+                mpmath.mp.prec = self.prec
+
+            # Proper casting of mpmath input and output types. Using
+            # native mpmath types as inputs gives improved precision
+            # in some cases.
+            if np.issubdtype(argarr.dtype, np.complexfloating):
+                pytype = mpc2complex
+
+                def mptype(x):
+                    return mpmath.mpc(complex(x))
+            else:
+                def mptype(x):
+                    return mpmath.mpf(float(x))
+
+                def pytype(x):
+                    if abs(x.imag) > 1e-16*(1 + abs(x.real)):
+                        return np.nan
+                    else:
+                        return mpf2float(x.real)
+
+            # Try out different dps until one (or none) works
+            for j, dps in enumerate(dps_list):
+                mpmath.mp.dps = dps
+
+                try:
+                    assert_func_equal(
+                        self.scipy_func,
+                        lambda *a: pytype(self.mpmath_func(*map(mptype, a))),
+                        argarr,
+                        vectorized=False,
+                        rtol=self.rtol,
+                        atol=self.atol,
+                        ignore_inf_sign=self.ignore_inf_sign,
+                        distinguish_nan_and_inf=self.distinguish_nan_and_inf,
+                        nan_ok=self.nan_ok,
+                        param_filter=self.param_filter
+                    )
+                    break
+                except AssertionError:
+                    if j >= len(dps_list)-1:
+                        # reraise the Exception
+                        tp, value, tb = sys.exc_info()
+                        if value.__traceback__ is not tb:
+                            raise value.with_traceback(tb)
+                        raise value
+        finally:
+            mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+    def __repr__(self):
+        if self.is_complex:
+            return f""
+        else:
+            return f""
+
+
+def assert_mpmath_equal(*a, **kw):
+    d = MpmathData(*a, **kw)
+    d.check()
+
+
+def nonfunctional_tooslow(func):
+    return pytest.mark.skip(
+        reason="    Test not yet functional (too slow), needs more work."
+    )(func)
+
+
+# ------------------------------------------------------------------------------
+# Tools for dealing with mpmath quirks
+# ------------------------------------------------------------------------------
+
+def mpf2float(x):
+    """
+    Convert an mpf to the nearest floating point number. Just using
+    float directly doesn't work because of results like this:
+
+    with mp.workdps(50):
+        float(mpf("0.99999999999999999")) = 0.9999999999999999
+
+    """
+    return float(mpmath.nstr(x, 17, min_fixed=0, max_fixed=0))
+
+
+def mpc2complex(x):
+    return complex(mpf2float(x.real), mpf2float(x.imag))
+
+
+def trace_args(func):
+    def tofloat(x):
+        if isinstance(x, mpmath.mpc):
+            return complex(x)
+        else:
+            return float(x)
+
+    def wrap(*a, **kw):
+        sys.stderr.write(f"{tuple(map(tofloat, a))!r}: ")
+        sys.stderr.flush()
+        try:
+            r = func(*a, **kw)
+            sys.stderr.write(f"-> {r!r}")
+        finally:
+            sys.stderr.write("\n")
+            sys.stderr.flush()
+        return r
+    return wrap
+
+
+try:
+    import signal
+    POSIX = ('setitimer' in dir(signal))
+except ImportError:
+    POSIX = False
+
+
+class TimeoutError(Exception):
+    pass
+
+
+def time_limited(timeout=0.5, return_val=np.nan, use_sigalrm=True):
+    """
+    Decorator for setting a timeout for pure-Python functions.
+
+    If the function does not return within `timeout` seconds, the
+    value `return_val` is returned instead.
+
+    On POSIX this uses SIGALRM by default. On non-POSIX, settrace is
+    used. Do not use this with threads: the SIGALRM implementation
+    does probably not work well. The settrace implementation only
+    traces the current thread.
+
+    The settrace implementation slows down execution speed. Slowdown
+    by a factor around 10 is probably typical.
+    """
+    if POSIX and use_sigalrm:
+        def sigalrm_handler(signum, frame):
+            raise TimeoutError()
+
+        def deco(func):
+            def wrap(*a, **kw):
+                old_handler = signal.signal(signal.SIGALRM, sigalrm_handler)
+                signal.setitimer(signal.ITIMER_REAL, timeout)
+                try:
+                    return func(*a, **kw)
+                except TimeoutError:
+                    return return_val
+                finally:
+                    signal.setitimer(signal.ITIMER_REAL, 0)
+                    signal.signal(signal.SIGALRM, old_handler)
+            return wrap
+    else:
+        def deco(func):
+            def wrap(*a, **kw):
+                start_time = time.time()
+
+                def trace(frame, event, arg):
+                    if time.time() - start_time > timeout:
+                        raise TimeoutError()
+                    return trace
+                sys.settrace(trace)
+                try:
+                    return func(*a, **kw)
+                except TimeoutError:
+                    sys.settrace(None)
+                    return return_val
+                finally:
+                    sys.settrace(None)
+            return wrap
+    return deco
+
+
+def exception_to_nan(func):
+    """Decorate function to return nan if it raises an exception"""
+    def wrap(*a, **kw):
+        try:
+            return func(*a, **kw)
+        except Exception:
+            return np.nan
+    return wrap
+
+
+def inf_to_nan(func):
+    """Decorate function to return nan if it returns inf"""
+    def wrap(*a, **kw):
+        v = func(*a, **kw)
+        if not np.isfinite(v):
+            return np.nan
+        return v
+    return wrap
+
+
+def mp_assert_allclose(res, std, atol=0, rtol=1e-17):
+    """
+    Compare lists of mpmath.mpf's or mpmath.mpc's directly so that it
+    can be done to higher precision than double.
+    """
+    failures = []
+    for k, (resval, stdval) in enumerate(zip_longest(res, std)):
+        if resval is None or stdval is None:
+            raise ValueError('Lengths of inputs res and std are not equal.')
+        if mpmath.fabs(resval - stdval) > atol + rtol*mpmath.fabs(stdval):
+            failures.append((k, resval, stdval))
+
+    nfail = len(failures)
+    if nfail > 0:
+        ndigits = int(abs(np.log10(rtol)))
+        msg = [""]
+        msg.append(f"Bad results ({nfail} out of {k + 1}) for the following points:")
+        for k, resval, stdval in failures:
+            resrep = mpmath.nstr(resval, ndigits, min_fixed=0, max_fixed=0)
+            stdrep = mpmath.nstr(stdval, ndigits, min_fixed=0, max_fixed=0)
+            if stdval == 0:
+                rdiff = "inf"
+            else:
+                rdiff = mpmath.fabs((resval - stdval)/stdval)
+                rdiff = mpmath.nstr(rdiff, 3)
+            msg.append(f"{k}: {resrep} != {stdrep} (rdiff {rdiff})")
+        assert_(False, "\n".join(msg))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bb1be9461c629a48841f1d01268e8d11eee230f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py
@@ -0,0 +1,610 @@
+import collections
+import numbers
+import numpy as np
+
+from ._input_validation import _nonneg_int_or_fail
+
+from ._special_ufuncs import (legendre_p, assoc_legendre_p,
+                              sph_legendre_p, sph_harm_y)
+from ._gufuncs import (legendre_p_all, assoc_legendre_p_all,
+                       sph_legendre_p_all, sph_harm_y_all)
+
+__all__ = [
+    "assoc_legendre_p",
+    "assoc_legendre_p_all",
+    "legendre_p",
+    "legendre_p_all",
+    "sph_harm_y",
+    "sph_harm_y_all",
+    "sph_legendre_p",
+    "sph_legendre_p_all",
+]
+
+
+class MultiUFunc:
+    def __init__(self, ufunc_or_ufuncs, doc=None, *,
+                 force_complex_output=False, **default_kwargs):
+        if not isinstance(ufunc_or_ufuncs, np.ufunc):
+            if isinstance(ufunc_or_ufuncs, collections.abc.Mapping):
+                ufuncs_iter = ufunc_or_ufuncs.values()
+            elif isinstance(ufunc_or_ufuncs, collections.abc.Iterable):
+                ufuncs_iter = ufunc_or_ufuncs
+            else:
+                raise ValueError("ufunc_or_ufuncs should be a ufunc or a"
+                                 " ufunc collection")
+
+            # Perform input validation to ensure all ufuncs in ufuncs are
+            # actually ufuncs and all take the same input types.
+            seen_input_types = set()
+            for ufunc in ufuncs_iter:
+                if not isinstance(ufunc, np.ufunc):
+                    raise ValueError("All ufuncs must have type `numpy.ufunc`."
+                                     f" Received {ufunc_or_ufuncs}")
+                seen_input_types.add(frozenset(x.split("->")[0] for x in ufunc.types))
+            if len(seen_input_types) > 1:
+                raise ValueError("All ufuncs must take the same input types.")
+
+        self._ufunc_or_ufuncs = ufunc_or_ufuncs
+        self.__doc = doc
+        self.__force_complex_output = force_complex_output
+        self._default_kwargs = default_kwargs
+        self._resolve_out_shapes = None
+        self._finalize_out = None
+        self._key = None
+        self._ufunc_default_args = lambda *args, **kwargs: ()
+        self._ufunc_default_kwargs = lambda *args, **kwargs: {}
+
+    @property
+    def __doc__(self):
+        return self.__doc
+
+    def _override_key(self, func):
+        """Set `key` method by decorating a function.
+        """
+        self._key = func
+
+    def _override_ufunc_default_args(self, func):
+        self._ufunc_default_args = func
+
+    def _override_ufunc_default_kwargs(self, func):
+        self._ufunc_default_kwargs = func
+
+    def _override_resolve_out_shapes(self, func):
+        """Set `resolve_out_shapes` method by decorating a function."""
+        if func.__doc__ is None:
+            func.__doc__ = \
+                """Resolve to output shapes based on relevant inputs."""
+        func.__name__ = "resolve_out_shapes"
+        self._resolve_out_shapes = func
+
+    def _override_finalize_out(self, func):
+        self._finalize_out = func
+
+    def _resolve_ufunc(self, **kwargs):
+        """Resolve to a ufunc based on keyword arguments."""
+
+        if isinstance(self._ufunc_or_ufuncs, np.ufunc):
+            return self._ufunc_or_ufuncs
+
+        ufunc_key = self._key(**kwargs)
+        return self._ufunc_or_ufuncs[ufunc_key]
+
+    def __call__(self, *args, **kwargs):
+        kwargs = self._default_kwargs | kwargs
+
+        args += self._ufunc_default_args(**kwargs)
+
+        ufunc = self._resolve_ufunc(**kwargs)
+
+        # array arguments to be passed to the ufunc
+        ufunc_args = [np.asarray(arg) for arg in args[-ufunc.nin:]]
+
+        ufunc_kwargs = self._ufunc_default_kwargs(**kwargs)
+
+        if (self._resolve_out_shapes is not None):
+            ufunc_arg_shapes = tuple(np.shape(ufunc_arg) for ufunc_arg in ufunc_args)
+            ufunc_out_shapes = self._resolve_out_shapes(*args[:-ufunc.nin],
+                                                        *ufunc_arg_shapes, ufunc.nout,
+                                                        **kwargs)
+
+            ufunc_arg_dtypes = tuple(ufunc_arg.dtype if hasattr(ufunc_arg, 'dtype')
+                                     else np.dtype(type(ufunc_arg))
+                                     for ufunc_arg in ufunc_args)
+
+            if hasattr(ufunc, 'resolve_dtypes'):
+                ufunc_dtypes = ufunc_arg_dtypes + ufunc.nout * (None,)
+                ufunc_dtypes = ufunc.resolve_dtypes(ufunc_dtypes)
+                ufunc_out_dtypes = ufunc_dtypes[-ufunc.nout:]
+            else:
+                ufunc_out_dtype = np.result_type(*ufunc_arg_dtypes)
+                if (not np.issubdtype(ufunc_out_dtype, np.inexact)):
+                    ufunc_out_dtype = np.float64
+
+                ufunc_out_dtypes = ufunc.nout * (ufunc_out_dtype,)
+
+            if self.__force_complex_output:
+                ufunc_out_dtypes = tuple(np.result_type(1j, ufunc_out_dtype)
+                                         for ufunc_out_dtype in ufunc_out_dtypes)
+
+            out = tuple(np.empty(ufunc_out_shape, dtype=ufunc_out_dtype)
+                        for ufunc_out_shape, ufunc_out_dtype
+                        in zip(ufunc_out_shapes, ufunc_out_dtypes))
+
+            ufunc_kwargs['out'] = out
+
+        out = ufunc(*ufunc_args, **ufunc_kwargs)
+        if (self._finalize_out is not None):
+            out = self._finalize_out(out)
+
+        return out
+
+
+sph_legendre_p = MultiUFunc(
+    sph_legendre_p,
+    r"""sph_legendre_p(n, m, theta, *, diff_n=0)
+
+    Spherical Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the spherical Legendre polynomial. Must have ``n >= 0``.
+    m : ArrayLike[int]
+        Order of the spherical Legendre polynomial.
+    theta : ArrayLike[float]
+        Input value.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Spherical Legendre polynomial with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    The spherical counterpart of an (unnormalized) associated Legendre polynomial has
+    the additional factor
+
+    .. math::
+
+        \sqrt{\frac{(2 n + 1) (n - m)!}{4 \pi (n + m)!}}
+
+    It is the same as the spherical harmonic :math:`Y_{n}^{m}(\theta, \phi)`
+    with :math:`\phi = 0`.
+    """, diff_n=0
+)
+
+
+@sph_legendre_p._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+sph_legendre_p_all = MultiUFunc(
+    sph_legendre_p_all,
+    """sph_legendre_p_all(n, m, theta, *, diff_n=0)
+
+    All spherical Legendre polynomials of the first kind up to the
+    specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    sph_legendre_p
+    """, diff_n=0
+)
+
+
+@sph_legendre_p_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_legendre_p_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [()] + [(0, 1, -1)]}
+
+
+@sph_legendre_p_all._override_resolve_out_shapes
+def _(n, m, theta_shape, nout, diff_n):
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) + theta_shape + (diff_n + 1,),)
+
+
+@sph_legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+assoc_legendre_p = MultiUFunc(
+    assoc_legendre_p,
+    r"""assoc_legendre_p(n, m, z, *, branch_cut=2, norm=False, diff_n=0)
+
+    Associated Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the associated Legendre polynomial. Must have ``n >= 0``.
+    m : ArrayLike[int]
+        order of the associated Legendre polynomial.
+    z : ArrayLike[float | complex]
+        Input value.
+    branch_cut : Optional[ArrayLike[int]]
+        Selects branch cut. Must be 2 (default) or 3.
+        2: cut on the real axis ``|z| > 1``
+        3: cut on the real axis ``-1 < z < 1``
+    norm : Optional[bool]
+        If ``True``, compute the normalized associated Legendre polynomial.
+        Default is ``False``.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Associated Legendre polynomial with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    The normalized counterpart of an (unnormalized) associated Legendre
+    polynomial has the additional factor
+
+    .. math::
+
+        \sqrt{\frac{(2 n + 1) (n - m)!}{2 (n + m)!}}
+    """, branch_cut=2, norm=False, diff_n=0
+)
+
+
+@assoc_legendre_p._override_key
+def _(branch_cut, norm, diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return norm, diff_n
+
+
+@assoc_legendre_p._override_ufunc_default_args
+def _(branch_cut, norm, diff_n):
+    return branch_cut,
+
+
+@assoc_legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+assoc_legendre_p_all = MultiUFunc(
+    assoc_legendre_p_all,
+    """assoc_legendre_p_all(n, m, z, *, branch_cut=2, norm=False, diff_n=0)
+
+    All associated Legendre polynomials of the first kind up to the
+    specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    assoc_legendre_p
+    """, branch_cut=2, norm=False, diff_n=0
+)
+
+
+@assoc_legendre_p_all._override_key
+def _(branch_cut, norm, diff_n):
+    if not ((isinstance(diff_n, numbers.Integral))
+            and diff_n >= 0):
+        raise ValueError(
+            f"diff_n must be a non-negative integer, received: {diff_n}."
+        )
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return norm, diff_n
+
+
+@assoc_legendre_p_all._override_ufunc_default_args
+def _(branch_cut, norm, diff_n):
+    return branch_cut,
+
+
+@assoc_legendre_p_all._override_ufunc_default_kwargs
+def _(branch_cut, norm, diff_n):
+    return {'axes': [(), ()] + [(0, 1, -1)]}
+
+
+@assoc_legendre_p_all._override_resolve_out_shapes
+def _(n, m, z_shape, branch_cut_shape, nout, **kwargs):
+    diff_n = kwargs['diff_n']
+
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    if not isinstance(m, numbers.Integral) or (m < 0):
+        raise ValueError("m must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) +
+        np.broadcast_shapes(z_shape, branch_cut_shape) + (diff_n + 1,),)
+
+
+@assoc_legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+legendre_p = MultiUFunc(
+    legendre_p,
+    """legendre_p(n, z, *, diff_n=0)
+
+    Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the Legendre polynomial. Must have ``n >= 0``.
+    z : ArrayLike[float]
+        Input value.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Legendre polynomial with ``diff_n`` derivatives.
+
+    See Also
+    --------
+    legendre
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    """, diff_n=0
+)
+
+
+@legendre_p._override_key
+def _(diff_n):
+    if (not isinstance(diff_n, numbers.Integral)) or (diff_n < 0):
+        raise ValueError(
+            f"diff_n must be a non-negative integer, received: {diff_n}."
+        )
+    if not 0 <= diff_n <= 2:
+        raise NotImplementedError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+legendre_p_all = MultiUFunc(
+    legendre_p_all,
+    """legendre_p_all(n, z, *, diff_n=0)
+
+    All Legendre polynomials of the first kind up to the
+    specified degree ``n``.
+
+    Output shape is ``(n + 1, ...)``. The entry at ``j``
+    corresponds to degree ``j`` for all  ``0 <= j <= n``.
+
+    See Also
+    --------
+    legendre_p
+    """, diff_n=0
+)
+
+
+@legendre_p_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@legendre_p_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [(), (0, -1)]}
+
+
+@legendre_p_all._override_resolve_out_shapes
+def _(n, z_shape, nout, diff_n):
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+
+    return nout * ((n + 1,) + z_shape + (diff_n + 1,),)
+
+
+@legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+sph_harm_y = MultiUFunc(
+    sph_harm_y,
+    r"""sph_harm_y(n, m, theta, phi, *, diff_n=0)
+
+    Spherical harmonics. They are defined as
+
+    .. math::
+
+        Y_n^m(\theta,\phi) = \sqrt{\frac{2 n + 1}{4 \pi} \frac{(n - m)!}{(n + m)!}}
+            P_n^m(\cos(\theta)) e^{i m \phi}
+
+    where :math:`P_n^m` are the (unnormalized) associated Legendre polynomials.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the harmonic. Must have ``n >= 0``. This is
+        often denoted by ``l`` (lower case L) in descriptions of
+        spherical harmonics.
+    m : ArrayLike[int]
+        Order of the harmonic.
+    theta : ArrayLike[float]
+        Polar (colatitudinal) coordinate; must be in ``[0, pi]``.
+    phi : ArrayLike[float]
+        Azimuthal (longitudinal) coordinate; must be in ``[0, 2*pi]``.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    y : ndarray[complex] or tuple[ndarray[complex]]
+       Spherical harmonics with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    There are different conventions for the meanings of the input
+    arguments ``theta`` and ``phi``. In SciPy ``theta`` is the
+    polar angle and ``phi`` is the azimuthal angle. It is common to
+    see the opposite convention, that is, ``theta`` as the azimuthal angle
+    and ``phi`` as the polar angle.
+
+    Note that SciPy's spherical harmonics include the Condon-Shortley
+    phase [2]_ because it is part of `sph_legendre_p`.
+
+    With SciPy's conventions, the first several spherical harmonics
+    are
+
+    .. math::
+
+        Y_0^0(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{1}{\pi}} \\
+        Y_1^{-1}(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{3}{2\pi}}
+                                    e^{-i\phi} \sin(\theta) \\
+        Y_1^0(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{3}{\pi}}
+                                 \cos(\theta) \\
+        Y_1^1(\theta, \phi) &= -\frac{1}{2} \sqrt{\frac{3}{2\pi}}
+                                 e^{i\phi} \sin(\theta).
+
+    References
+    ----------
+    .. [1] Digital Library of Mathematical Functions, 14.30.
+           https://dlmf.nist.gov/14.30
+    .. [2] https://en.wikipedia.org/wiki/Spherical_harmonics#Condon.E2.80.93Shortley_phase
+    """, force_complex_output=True, diff_n=0
+)
+
+
+@sph_harm_y._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_harm_y._override_finalize_out
+def _(out):
+    if (out.shape[-1] == 1):
+        return out[..., 0, 0]
+
+    if (out.shape[-1] == 2):
+        return out[..., 0, 0], out[..., [1, 0], [0, 1]]
+
+    if (out.shape[-1] == 3):
+        return (out[..., 0, 0], out[..., [1, 0], [0, 1]],
+            out[..., [[2, 1], [1, 0]], [[0, 1], [1, 2]]])
+
+
+sph_harm_y_all = MultiUFunc(
+    sph_harm_y_all,
+    """sph_harm_y_all(n, m, theta, phi, *, diff_n=0)
+
+    All spherical harmonics up to the specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    sph_harm_y
+    """, force_complex_output=True, diff_n=0
+)
+
+
+@sph_harm_y_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_harm_y_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [(), ()] + [(0, 1, -2, -1)]}
+
+
+@sph_harm_y_all._override_resolve_out_shapes
+def _(n, m, theta_shape, phi_shape, nout, **kwargs):
+    diff_n = kwargs['diff_n']
+
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) + np.broadcast_shapes(theta_shape, phi_shape) +
+        (diff_n + 1, diff_n + 1),)
+
+
+@sph_harm_y_all._override_finalize_out
+def _(out):
+    if (out.shape[-1] == 1):
+        return out[..., 0, 0]
+
+    if (out.shape[-1] == 2):
+        return out[..., 0, 0], out[..., [1, 0], [0, 1]]
+
+    if (out.shape[-1] == 3):
+        return (out[..., 0, 0], out[..., [1, 0], [0, 1]],
+            out[..., [[2, 1], [1, 0]], [[0, 1], [1, 2]]])
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..e021f5a899b2b9218d59527fd91fb6cf7a545042
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py
@@ -0,0 +1,2592 @@
+"""
+A collection of functions to find the weights and abscissas for
+Gaussian Quadrature.
+
+These calculations are done by finding the eigenvalues of a
+tridiagonal matrix whose entries are dependent on the coefficients
+in the recursion formula for the orthogonal polynomials with the
+corresponding weighting function over the interval.
+
+Many recursion relations for orthogonal polynomials are given:
+
+.. math::
+
+    a1n f_{n+1} (x) = (a2n + a3n x ) f_n (x) - a4n f_{n-1} (x)
+
+The recursion relation of interest is
+
+.. math::
+
+    P_{n+1} (x) = (x - A_n) P_n (x) - B_n P_{n-1} (x)
+
+where :math:`P` has a different normalization than :math:`f`.
+
+The coefficients can be found as:
+
+.. math::
+
+    A_n = -a2n / a3n
+    \\qquad
+    B_n = ( a4n / a3n \\sqrt{h_n-1 / h_n})^2
+
+where
+
+.. math::
+
+    h_n = \\int_a^b w(x) f_n(x)^2
+
+assume:
+
+.. math::
+
+    P_0 (x) = 1
+    \\qquad
+    P_{-1} (x) == 0
+
+For the mathematical background, see [golub.welsch-1969-mathcomp]_ and
+[abramowitz.stegun-1965]_.
+
+References
+----------
+.. [golub.welsch-1969-mathcomp]
+   Golub, Gene H, and John H Welsch. 1969. Calculation of Gauss
+   Quadrature Rules. *Mathematics of Computation* 23, 221-230+s1--s10.
+
+.. [abramowitz.stegun-1965]
+   Abramowitz, Milton, and Irene A Stegun. (1965) *Handbook of
+   Mathematical Functions: with Formulas, Graphs, and Mathematical
+   Tables*. Gaithersburg, MD: National Bureau of Standards.
+   http://www.math.sfu.ca/~cbm/aands/
+
+.. [townsend.trogdon.olver-2014]
+   Townsend, A. and Trogdon, T. and Olver, S. (2014)
+   *Fast computation of Gauss quadrature nodes and
+   weights on the whole real line*. :arXiv:`1410.5286`.
+
+.. [townsend.trogdon.olver-2015]
+   Townsend, A. and Trogdon, T. and Olver, S. (2015)
+   *Fast computation of Gauss quadrature nodes and
+   weights on the whole real line*.
+   IMA Journal of Numerical Analysis
+   :doi:`10.1093/imanum/drv002`.
+"""
+#
+# Author:  Travis Oliphant 2000
+# Updated Sep. 2003 (fixed bugs --- tested to be accurate)
+
+# SciPy imports.
+import numpy as np
+from numpy import (exp, inf, pi, sqrt, floor, sin, cos, around,
+                   hstack, arccos, arange)
+from scipy import linalg
+from scipy.special import airy
+
+# Local imports.
+# There is no .pyi file for _specfun
+from . import _specfun  # type: ignore
+from . import _ufuncs
+_gam = _ufuncs.gamma
+
+_polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys',
+             'jacobi', 'laguerre', 'genlaguerre', 'hermite',
+             'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt',
+             'sh_chebyu', 'sh_jacobi']
+
+# Correspondence between new and old names of root functions
+_rootfuns_map = {'roots_legendre': 'p_roots',
+                 'roots_chebyt': 't_roots',
+                 'roots_chebyu': 'u_roots',
+                 'roots_chebyc': 'c_roots',
+                 'roots_chebys': 's_roots',
+                 'roots_jacobi': 'j_roots',
+                 'roots_laguerre': 'l_roots',
+                 'roots_genlaguerre': 'la_roots',
+                 'roots_hermite': 'h_roots',
+                 'roots_hermitenorm': 'he_roots',
+                 'roots_gegenbauer': 'cg_roots',
+                 'roots_sh_legendre': 'ps_roots',
+                 'roots_sh_chebyt': 'ts_roots',
+                 'roots_sh_chebyu': 'us_roots',
+                 'roots_sh_jacobi': 'js_roots'}
+
+__all__ = _polyfuns + list(_rootfuns_map.keys())
+
+
+class orthopoly1d(np.poly1d):
+
+    def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None,
+                 limits=None, monic=False, eval_func=None):
+        equiv_weights = [weights[k] / wfunc(roots[k]) for
+                         k in range(len(roots))]
+        mu = sqrt(hn)
+        if monic:
+            evf = eval_func
+            if evf:
+                knn = kn
+                def eval_func(x):
+                    return evf(x) / knn
+            mu = mu / abs(kn)
+            kn = 1.0
+
+        # compute coefficients from roots, then scale
+        poly = np.poly1d(roots, r=True)
+        np.poly1d.__init__(self, poly.coeffs * float(kn))
+
+        self.weights = np.array(list(zip(roots, weights, equiv_weights)))
+        self.weight_func = wfunc
+        self.limits = limits
+        self.normcoef = mu
+
+        # Note: eval_func will be discarded on arithmetic
+        self._eval_func = eval_func
+
+    def __call__(self, v):
+        if self._eval_func and not isinstance(v, np.poly1d):
+            return self._eval_func(v)
+        else:
+            return np.poly1d.__call__(self, v)
+
+    def _scale(self, p):
+        if p == 1.0:
+            return
+        self._coeffs *= p
+
+        evf = self._eval_func
+        if evf:
+            self._eval_func = lambda x: evf(x) * p
+        self.normcoef *= p
+
+
+def _gen_roots_and_weights(n, mu0, an_func, bn_func, f, df, symmetrize, mu):
+    """[x,w] = gen_roots_and_weights(n,an_func,sqrt_bn_func,mu)
+
+    Returns the roots (x) of an nth order orthogonal polynomial,
+    and weights (w) to use in appropriate Gaussian quadrature with that
+    orthogonal polynomial.
+
+    The polynomials have the recurrence relation
+          P_n+1(x) = (x - A_n) P_n(x) - B_n P_n-1(x)
+
+    an_func(n)          should return A_n
+    sqrt_bn_func(n)     should return sqrt(B_n)
+    mu ( = h_0 )        is the integral of the weight over the orthogonal
+                        interval
+    """
+    k = np.arange(n, dtype='d')
+    c = np.zeros((2, n))
+    c[0,1:] = bn_func(k[1:])
+    c[1,:] = an_func(k)
+    x = linalg.eigvals_banded(c, overwrite_a_band=True)
+
+    # improve roots by one application of Newton's method
+    y = f(n, x)
+    dy = df(n, x)
+    x -= y/dy
+
+    # fm and dy may contain very large/small values, so we
+    # log-normalize them to maintain precision in the product fm*dy
+    fm = f(n-1, x)
+    log_fm = np.log(np.abs(fm))
+    log_dy = np.log(np.abs(dy))
+    fm /= np.exp((log_fm.max() + log_fm.min()) / 2.)
+    dy /= np.exp((log_dy.max() + log_dy.min()) / 2.)
+    w = 1.0 / (fm * dy)
+
+    if symmetrize:
+        w = (w + w[::-1]) / 2
+        x = (x - x[::-1]) / 2
+
+    w *= mu0 / w.sum()
+
+    if mu:
+        return x, w, mu0
+    else:
+        return x, w
+
+# Jacobi Polynomials 1               P^(alpha,beta)_n(x)
+
+
+def roots_jacobi(n, alpha, beta, mu=False):
+    r"""Gauss-Jacobi quadrature.
+
+    Compute the sample points and weights for Gauss-Jacobi
+    quadrature. The sample points are the roots of the nth degree
+    Jacobi polynomial, :math:`P^{\alpha, \beta}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[-1, 1]` with
+    weight function :math:`w(x) = (1 - x)^{\alpha} (1 +
+    x)^{\beta}`. See 22.2.1 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -1
+    beta : float
+        beta must be > -1
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha <= -1 or beta <= -1:
+        raise ValueError("alpha and beta must be greater than -1.")
+
+    if alpha == 0.0 and beta == 0.0:
+        return roots_legendre(m, mu)
+    if alpha == beta:
+        return roots_gegenbauer(m, alpha+0.5, mu)
+
+    if (alpha + beta) <= 1000:
+        mu0 = 2.0**(alpha+beta+1) * _ufuncs.beta(alpha+1, beta+1)
+    else:
+        # Avoid overflows in pow and beta for very large parameters
+        mu0 = np.exp((alpha + beta + 1) * np.log(2.0)
+                     + _ufuncs.betaln(alpha+1, beta+1))
+    a = alpha
+    b = beta
+    if a + b == 0.0:
+        def an_func(k):
+            return np.where(k == 0, (b - a) / (2 + a + b), 0.0)
+    else:
+        def an_func(k):
+            return np.where(
+                k == 0,
+                (b - a) / (2 + a + b),
+                (b * b - a * a) / ((2.0 * k + a + b) * (2.0 * k + a + b + 2))
+            )
+
+    def bn_func(k):
+        return (
+            2.0 / (2.0 * k + a + b)
+            * np.sqrt((k + a) * (k + b) / (2 * k + a + b + 1))
+            * np.where(k == 1, 1.0, np.sqrt(k * (k + a + b) / (2.0 * k + a + b - 1)))
+        )
+
+    def f(n, x):
+        return _ufuncs.eval_jacobi(n, a, b, x)
+    def df(n, x):
+        return 0.5 * (n + a + b + 1) * _ufuncs.eval_jacobi(n - 1, a + 1, b + 1, x)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu)
+
+
+def jacobi(n, alpha, beta, monic=False):
+    r"""Jacobi polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}P_n^{(\alpha, \beta)}
+          + (\beta - \alpha - (\alpha + \beta + 2)x)
+            \frac{d}{dx}P_n^{(\alpha, \beta)}
+          + n(n + \alpha + \beta + 1)P_n^{(\alpha, \beta)} = 0
+
+    for :math:`\alpha, \beta > -1`; :math:`P_n^{(\alpha, \beta)}` is a
+    polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -1.
+    beta : float
+        Parameter, must be greater than -1.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Jacobi polynomial.
+
+    Notes
+    -----
+    For fixed :math:`\alpha, \beta`, the polynomials
+    :math:`P_n^{(\alpha, \beta)}` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x)^\alpha(1 + x)^\beta`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The Jacobi polynomials satisfy the recurrence relation:
+
+    .. math::
+        P_n^{(\alpha, \beta-1)}(x) - P_n^{(\alpha-1, \beta)}(x)
+          = P_{n-1}^{(\alpha, \beta)}(x)
+
+    This can be verified, for example, for :math:`\alpha = \beta = 2`
+    and :math:`n = 1` over the interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import jacobi
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(jacobi(0, 2, 2)(x),
+    ...             jacobi(1, 2, 1)(x) - jacobi(1, 1, 2)(x))
+    True
+
+    Plot of the Jacobi polynomial :math:`P_5^{(\alpha, -0.5)}` for
+    different values of :math:`\alpha`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Jacobi polynomials $P_5^{(\alpha, -0.5)}$')
+    >>> for alpha in np.arange(0, 4, 1):
+    ...     ax.plot(x, jacobi(5, alpha, -0.5)(x), label=rf'$\alpha={alpha}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return (1 - x) ** alpha * (1 + x) ** beta
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic,
+                           eval_func=np.ones_like)
+    x, w, mu = roots_jacobi(n, alpha, beta, mu=True)
+    ab1 = alpha + beta + 1.0
+    hn = 2**ab1 / (2 * n + ab1) * _gam(n + alpha + 1)
+    hn *= _gam(n + beta + 1.0) / _gam(n + 1) / _gam(n + ab1)
+    kn = _gam(2 * n + ab1) / 2.0**n / _gam(n + 1) / _gam(n + ab1)
+    # here kn = coefficient on x^n term
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
+                    lambda x: _ufuncs.eval_jacobi(n, alpha, beta, x))
+    return p
+
+# Jacobi Polynomials shifted         G_n(p,q,x)
+
+
+def roots_sh_jacobi(n, p1, q1, mu=False):
+    """Gauss-Jacobi (shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Jacobi (shifted)
+    quadrature. The sample points are the roots of the nth degree
+    shifted Jacobi polynomial, :math:`G^{p,q}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[0, 1]` with
+    weight function :math:`w(x) = (1 - x)^{p-q} x^{q-1}`. See 22.2.2
+    in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    p1 : float
+        (p1 - q1) must be > -1
+    q1 : float
+        q1 must be > 0
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    if (p1-q1) <= -1 or q1 <= 0:
+        message = "(p - q) must be greater than -1, and q must be greater than 0."
+        raise ValueError(message)
+    x, w, m = roots_jacobi(n, p1-q1, q1-1, True)
+    x = (x + 1) / 2
+    scale = 2.0**p1
+    w /= scale
+    m /= scale
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def sh_jacobi(n, p, q, monic=False):
+    r"""Shifted Jacobi polynomial.
+
+    Defined by
+
+    .. math::
+
+        G_n^{(p, q)}(x)
+          = \binom{2n + p - 1}{n}^{-1}P_n^{(p - q, q - 1)}(2x - 1),
+
+    where :math:`P_n^{(\cdot, \cdot)}` is the nth Jacobi polynomial.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    p : float
+        Parameter, must have :math:`p > q - 1`.
+    q : float
+        Parameter, must be greater than 0.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    G : orthopoly1d
+        Shifted Jacobi polynomial.
+
+    Notes
+    -----
+    For fixed :math:`p, q`, the polynomials :math:`G_n^{(p, q)}` are
+    orthogonal over :math:`[0, 1]` with weight function :math:`(1 -
+    x)^{p - q}x^{q - 1}`.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return (1.0 - x) ** (p - q) * x ** (q - 1.0)
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic,
+                           eval_func=np.ones_like)
+    n1 = n
+    x, w = roots_sh_jacobi(n1, p, q)
+    hn = _gam(n + 1) * _gam(n + q) * _gam(n + p) * _gam(n + p - q + 1)
+    hn /= (2 * n + p) * (_gam(2 * n + p)**2)
+    # kn = 1.0 in standard form so monic is redundant. Kept for compatibility.
+    kn = 1.0
+    pp = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(0, 1), monic=monic,
+                     eval_func=lambda x: _ufuncs.eval_sh_jacobi(n, p, q, x))
+    return pp
+
+# Generalized Laguerre               L^(alpha)_n(x)
+
+
+def roots_genlaguerre(n, alpha, mu=False):
+    r"""Gauss-generalized Laguerre quadrature.
+
+    Compute the sample points and weights for Gauss-generalized
+    Laguerre quadrature. The sample points are the roots of the nth
+    degree generalized Laguerre polynomial, :math:`L^{\alpha}_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0,
+    \infty]` with weight function :math:`w(x) = x^{\alpha}
+    e^{-x}`. See 22.3.9 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -1
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha < -1:
+        raise ValueError("alpha must be greater than -1.")
+
+    mu0 = _ufuncs.gamma(alpha + 1)
+
+    if m == 1:
+        x = np.array([alpha+1.0], 'd')
+        w = np.array([mu0], 'd')
+        if mu:
+            return x, w, mu0
+        else:
+            return x, w
+
+    def an_func(k):
+        return 2 * k + alpha + 1
+    def bn_func(k):
+        return -np.sqrt(k * (k + alpha))
+    def f(n, x):
+        return _ufuncs.eval_genlaguerre(n, alpha, x)
+    def df(n, x):
+        return (n * _ufuncs.eval_genlaguerre(n, alpha, x)
+                - (n + alpha) * _ufuncs.eval_genlaguerre(n - 1, alpha, x)) / x
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu)
+
+
+def genlaguerre(n, alpha, monic=False):
+    r"""Generalized (associated) Laguerre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        x\frac{d^2}{dx^2}L_n^{(\alpha)}
+          + (\alpha + 1 - x)\frac{d}{dx}L_n^{(\alpha)}
+          + nL_n^{(\alpha)} = 0,
+
+    where :math:`\alpha > -1`; :math:`L_n^{(\alpha)}` is a polynomial
+    of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -1.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    L : orthopoly1d
+        Generalized Laguerre polynomial.
+
+    See Also
+    --------
+    laguerre : Laguerre polynomial.
+    hyp1f1 : confluent hypergeometric function
+
+    Notes
+    -----
+    For fixed :math:`\alpha`, the polynomials :math:`L_n^{(\alpha)}`
+    are orthogonal over :math:`[0, \infty)` with weight function
+    :math:`e^{-x}x^\alpha`.
+
+    The Laguerre polynomials are the special case where :math:`\alpha
+    = 0`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The generalized Laguerre polynomials are closely related to the confluent
+    hypergeometric function :math:`{}_1F_1`:
+
+        .. math::
+            L_n^{(\alpha)} = \binom{n + \alpha}{n} {}_1F_1(-n, \alpha +1, x)
+
+    This can be verified, for example,  for :math:`n = \alpha = 3` over the
+    interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import binom
+    >>> from scipy.special import genlaguerre
+    >>> from scipy.special import hyp1f1
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(genlaguerre(3, 3)(x), binom(6, 3) * hyp1f1(-3, 4, x))
+    True
+
+    This is the plot of the generalized Laguerre polynomials
+    :math:`L_3^{(\alpha)}` for some values of :math:`\alpha`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-4.0, 12.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-5.0, 10.0)
+    >>> ax.set_title(r'Generalized Laguerre polynomials $L_3^{\alpha}$')
+    >>> for alpha in np.arange(0, 5):
+    ...     ax.plot(x, genlaguerre(3, alpha)(x), label=rf'$L_3^{(alpha)}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if alpha <= -1:
+        raise ValueError("alpha must be > -1")
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_genlaguerre(n1, alpha)
+    def wfunc(x):
+        return exp(-x) * x ** alpha
+    if n == 0:
+        x, w = [], []
+    hn = _gam(n + alpha + 1) / _gam(n + 1)
+    kn = (-1)**n / _gam(n + 1)
+    p = orthopoly1d(x, w, hn, kn, wfunc, (0, inf), monic,
+                    lambda x: _ufuncs.eval_genlaguerre(n, alpha, x))
+    return p
+
+# Laguerre                      L_n(x)
+
+
+def roots_laguerre(n, mu=False):
+    r"""Gauss-Laguerre quadrature.
+
+    Compute the sample points and weights for Gauss-Laguerre
+    quadrature. The sample points are the roots of the nth degree
+    Laguerre polynomial, :math:`L_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[0, \infty]` with weight function
+    :math:`w(x) = e^{-x}`. See 22.2.13 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.laguerre.laggauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    return roots_genlaguerre(n, 0.0, mu=mu)
+
+
+def laguerre(n, monic=False):
+    r"""Laguerre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        x\frac{d^2}{dx^2}L_n + (1 - x)\frac{d}{dx}L_n + nL_n = 0;
+
+    :math:`L_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    L : orthopoly1d
+        Laguerre Polynomial.
+
+    See Also
+    --------
+    genlaguerre : Generalized (associated) Laguerre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`L_n` are orthogonal over :math:`[0,
+    \infty)` with weight function :math:`e^{-x}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The Laguerre polynomials :math:`L_n` are the special case
+    :math:`\alpha = 0` of the generalized Laguerre polynomials
+    :math:`L_n^{(\alpha)}`.
+    Let's verify it on the interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import genlaguerre
+    >>> from scipy.special import laguerre
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(genlaguerre(3, 0)(x), laguerre(3)(x))
+    True
+
+    The polynomials :math:`L_n` also satisfy the recurrence relation:
+
+    .. math::
+        (n + 1)L_{n+1}(x) = (2n +1 -x)L_n(x) - nL_{n-1}(x)
+
+    This can be easily checked on :math:`[0, 1]` for :math:`n = 3`:
+
+    >>> x = np.arange(0.0, 1.0, 0.01)
+    >>> np.allclose(4 * laguerre(4)(x),
+    ...             (7 - x) * laguerre(3)(x) - 3 * laguerre(2)(x))
+    True
+
+    This is the plot of the first few Laguerre polynomials :math:`L_n`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-1.0, 5.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-5.0, 5.0)
+    >>> ax.set_title(r'Laguerre polynomials $L_n$')
+    >>> for n in np.arange(0, 5):
+    ...     ax.plot(x, laguerre(n)(x), label=rf'$L_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_laguerre(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 1.0
+    kn = (-1)**n / _gam(n + 1)
+    p = orthopoly1d(x, w, hn, kn, lambda x: exp(-x), (0, inf), monic,
+                    lambda x: _ufuncs.eval_laguerre(n, x))
+    return p
+
+# Hermite  1                         H_n(x)
+
+
+def roots_hermite(n, mu=False):
+    r"""Gauss-Hermite (physicist's) quadrature.
+
+    Compute the sample points and weights for Gauss-Hermite
+    quadrature. The sample points are the roots of the nth degree
+    Hermite polynomial, :math:`H_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-\infty, \infty]` with weight
+    function :math:`w(x) = e^{-x^2}`. See 22.2.14 in [AS]_ for
+    details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.hermite.hermgauss
+    roots_hermitenorm
+
+    Notes
+    -----
+    For small n up to 150 a modified version of the Golub-Welsch
+    algorithm is used. Nodes are computed from the eigenvalue
+    problem and improved by one step of a Newton iteration.
+    The weights are computed from the well-known analytical formula.
+
+    For n larger than 150 an optimal asymptotic algorithm is applied
+    which computes nodes and weights in a numerically stable manner.
+    The algorithm has linear runtime making computation for very
+    large n (several thousand or more) feasible.
+
+    References
+    ----------
+    .. [townsend.trogdon.olver-2014]
+        Townsend, A. and Trogdon, T. and Olver, S. (2014)
+        *Fast computation of Gauss quadrature nodes and
+        weights on the whole real line*. :arXiv:`1410.5286`.
+    .. [townsend.trogdon.olver-2015]
+        Townsend, A. and Trogdon, T. and Olver, S. (2015)
+        *Fast computation of Gauss quadrature nodes and
+        weights on the whole real line*.
+        IMA Journal of Numerical Analysis
+        :doi:`10.1093/imanum/drv002`.
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = np.sqrt(np.pi)
+    if n <= 150:
+        def an_func(k):
+            return 0.0 * k
+        def bn_func(k):
+            return np.sqrt(k / 2.0)
+        f = _ufuncs.eval_hermite
+        def df(n, x):
+            return 2.0 * n * _ufuncs.eval_hermite(n - 1, x)
+        return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+    else:
+        nodes, weights = _roots_hermite_asy(m)
+        if mu:
+            return nodes, weights, mu0
+        else:
+            return nodes, weights
+
+
+def _compute_tauk(n, k, maxit=5):
+    """Helper function for Tricomi initial guesses
+
+    For details, see formula 3.1 in lemma 3.1 in the
+    original paper.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots :math:`\tau_k` to compute
+    maxit : int
+        Number of Newton maxit performed, the default
+        value of 5 is sufficient.
+
+    Returns
+    -------
+    tauk : ndarray
+        Roots of equation 3.1
+
+    See Also
+    --------
+    initial_nodes_a
+    roots_hermite_asy
+    """
+    a = n % 2 - 0.5
+    c = (4.0*floor(n/2.0) - 4.0*k + 3.0)*pi / (4.0*floor(n/2.0) + 2.0*a + 2.0)
+    def f(x):
+        return x - sin(x) - c
+    def df(x):
+        return 1.0 - cos(x)
+    xi = 0.5*pi
+    for i in range(maxit):
+        xi = xi - f(xi)/df(xi)
+    return xi
+
+
+def _initial_nodes_a(n, k):
+    r"""Tricomi initial guesses
+
+    Computes an initial approximation to the square of the `k`-th
+    (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The formula is the one from lemma 3.1 in the
+    original paper. The guesses are accurate except in the region
+    near :math:`\sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots to compute
+
+    Returns
+    -------
+    xksq : ndarray
+        Square of the approximate roots
+
+    See Also
+    --------
+    initial_nodes
+    roots_hermite_asy
+    """
+    tauk = _compute_tauk(n, k)
+    sigk = cos(0.5*tauk)**2
+    a = n % 2 - 0.5
+    nu = 4.0*floor(n/2.0) + 2.0*a + 2.0
+    # Initial approximation of Hermite roots (square)
+    xksq = nu*sigk - 1.0/(3.0*nu) * (5.0/(4.0*(1.0-sigk)**2) - 1.0/(1.0-sigk) - 0.25)
+    return xksq
+
+
+def _initial_nodes_b(n, k):
+    r"""Gatteschi initial guesses
+
+    Computes an initial approximation to the square of the kth
+    (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The formula is the one from lemma 3.2 in the
+    original paper. The guesses are accurate in the region just
+    below :math:`\sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots to compute
+
+    Returns
+    -------
+    xksq : ndarray
+        Square of the approximate root
+
+    See Also
+    --------
+    initial_nodes
+    roots_hermite_asy
+    """
+    a = n % 2 - 0.5
+    nu = 4.0*floor(n/2.0) + 2.0*a + 2.0
+    # Airy roots by approximation
+    ak = _specfun.airyzo(k.max(), 1)[0][::-1]
+    # Initial approximation of Hermite roots (square)
+    xksq = (nu
+            + 2.0**(2.0/3.0) * ak * nu**(1.0/3.0)
+            + 1.0/5.0 * 2.0**(4.0/3.0) * ak**2 * nu**(-1.0/3.0)
+            + (9.0/140.0 - 12.0/175.0 * ak**3) * nu**(-1.0)
+            + (16.0/1575.0 * ak + 92.0/7875.0 * ak**4) * 2.0**(2.0/3.0) * nu**(-5.0/3.0)
+            - (15152.0/3031875.0 * ak**5 + 1088.0/121275.0 * ak**2)
+              * 2.0**(1.0/3.0) * nu**(-7.0/3.0))
+    return xksq
+
+
+def _initial_nodes(n):
+    """Initial guesses for the Hermite roots
+
+    Computes an initial approximation to the non-negative
+    roots :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The Tricomi and Gatteschi initial
+    guesses are used in the region where they are accurate.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+
+    Returns
+    -------
+    xk : ndarray
+        Approximate roots
+
+    See Also
+    --------
+    roots_hermite_asy
+    """
+    # Turnover point
+    # linear polynomial fit to error of 10, 25, 40, ..., 1000 point rules
+    fit = 0.49082003*n - 4.37859653
+    turnover = around(fit).astype(int)
+    # Compute all approximations
+    ia = arange(1, int(floor(n*0.5)+1))
+    ib = ia[::-1]
+    xasq = _initial_nodes_a(n, ia[:turnover+1])
+    xbsq = _initial_nodes_b(n, ib[turnover+1:])
+    # Combine
+    iv = sqrt(hstack([xasq, xbsq]))
+    # Central node is always zero
+    if n % 2 == 1:
+        iv = hstack([0.0, iv])
+    return iv
+
+
+def _pbcf(n, theta):
+    r"""Asymptotic series expansion of parabolic cylinder function
+
+    The implementation is based on sections 3.2 and 3.3 from the
+    original paper. Compared to the published version this code
+    adds one more term to the asymptotic series. The detailed
+    formulas can be found at [parabolic-asymptotics]_. The evaluation
+    is done in a transformed variable :math:`\theta := \arccos(t)`
+    where :math:`t := x / \mu` and :math:`\mu := \sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    theta : ndarray
+        Transformed position variable
+
+    Returns
+    -------
+    U : ndarray
+        Value of the parabolic cylinder function :math:`U(a, \theta)`.
+    Ud : ndarray
+        Value of the derivative :math:`U^{\prime}(a, \theta)` of
+        the parabolic cylinder function.
+
+    See Also
+    --------
+    roots_hermite_asy
+
+    References
+    ----------
+    .. [parabolic-asymptotics]
+       https://dlmf.nist.gov/12.10#vii
+    """
+    st = sin(theta)
+    ct = cos(theta)
+    # https://dlmf.nist.gov/12.10#vii
+    mu = 2.0*n + 1.0
+    # https://dlmf.nist.gov/12.10#E23
+    eta = 0.5*theta - 0.5*st*ct
+    # https://dlmf.nist.gov/12.10#E39
+    zeta = -(3.0*eta/2.0) ** (2.0/3.0)
+    # https://dlmf.nist.gov/12.10#E40
+    phi = (-zeta / st**2) ** (0.25)
+    # Coefficients
+    # https://dlmf.nist.gov/12.10#E43
+    a0 = 1.0
+    a1 = 0.10416666666666666667
+    a2 = 0.08355034722222222222
+    a3 = 0.12822657455632716049
+    a4 = 0.29184902646414046425
+    a5 = 0.88162726744375765242
+    b0 = 1.0
+    b1 = -0.14583333333333333333
+    b2 = -0.09874131944444444444
+    b3 = -0.14331205391589506173
+    b4 = -0.31722720267841354810
+    b5 = -0.94242914795712024914
+    # Polynomials
+    # https://dlmf.nist.gov/12.10#E9
+    # https://dlmf.nist.gov/12.10#E10
+    ctp = ct ** arange(16).reshape((-1,1))
+    u0 = 1.0
+    u1 = (1.0*ctp[3,:] - 6.0*ct) / 24.0
+    u2 = (-9.0*ctp[4,:] + 249.0*ctp[2,:] + 145.0) / 1152.0
+    u3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 28287.0*ctp[5,:]
+          - 151995.0*ctp[3,:] - 259290.0*ct) / 414720.0
+    u4 = (72756.0*ctp[10,:] - 321339.0*ctp[8,:] - 154982.0*ctp[6,:]
+          + 50938215.0*ctp[4,:] + 122602962.0*ctp[2,:] + 12773113.0) / 39813120.0
+    u5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 1994971575.0*ctp[11,:]
+          - 3630137104.0*ctp[9,:] + 4433574213.0*ctp[7,:] - 37370295816.0*ctp[5,:]
+          - 119582875013.0*ctp[3,:] - 34009066266.0*ct) / 6688604160.0
+    v0 = 1.0
+    v1 = (1.0*ctp[3,:] + 6.0*ct) / 24.0
+    v2 = (15.0*ctp[4,:] - 327.0*ctp[2,:] - 143.0) / 1152.0
+    v3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 36387.0*ctp[5,:] 
+          + 238425.0*ctp[3,:] + 259290.0*ct) / 414720.0
+    v4 = (-121260.0*ctp[10,:] + 551733.0*ctp[8,:] - 151958.0*ctp[6,:]
+          - 57484425.0*ctp[4,:] - 132752238.0*ctp[2,:] - 12118727) / 39813120.0
+    v5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 2025529095.0*ctp[11,:]
+          - 3750839308.0*ctp[9,:] + 3832454253.0*ctp[7,:] + 35213253348.0*ctp[5,:]
+          + 130919230435.0*ctp[3,:] + 34009066266*ct) / 6688604160.0
+    # Airy Evaluation (Bi and Bip unused)
+    Ai, Aip, Bi, Bip = airy(mu**(4.0/6.0) * zeta)
+    # Prefactor for U
+    P = 2.0*sqrt(pi) * mu**(1.0/6.0) * phi
+    # Terms for U
+    # https://dlmf.nist.gov/12.10#E42
+    phip = phi ** arange(6, 31, 6).reshape((-1,1))
+    A0 = b0*u0
+    A1 = (b2*u0 + phip[0,:]*b1*u1 + phip[1,:]*b0*u2) / zeta**3
+    A2 = (b4*u0 + phip[0,:]*b3*u1 + phip[1,:]*b2*u2 + phip[2,:]*b1*u3
+          + phip[3,:]*b0*u4) / zeta**6
+    B0 = -(a1*u0 + phip[0,:]*a0*u1) / zeta**2
+    B1 = -(a3*u0 + phip[0,:]*a2*u1 + phip[1,:]*a1*u2 + phip[2,:]*a0*u3) / zeta**5
+    B2 = -(a5*u0 + phip[0,:]*a4*u1 + phip[1,:]*a3*u2 + phip[2,:]*a2*u3
+           + phip[3,:]*a1*u4 + phip[4,:]*a0*u5) / zeta**8
+    # U
+    # https://dlmf.nist.gov/12.10#E35
+    U = P * (Ai * (A0 + A1/mu**2.0 + A2/mu**4.0) +
+             Aip * (B0 + B1/mu**2.0 + B2/mu**4.0) / mu**(8.0/6.0))
+    # Prefactor for derivative of U
+    Pd = sqrt(2.0*pi) * mu**(2.0/6.0) / phi
+    # Terms for derivative of U
+    # https://dlmf.nist.gov/12.10#E46
+    C0 = -(b1*v0 + phip[0,:]*b0*v1) / zeta
+    C1 = -(b3*v0 + phip[0,:]*b2*v1 + phip[1,:]*b1*v2 + phip[2,:]*b0*v3) / zeta**4
+    C2 = -(b5*v0 + phip[0,:]*b4*v1 + phip[1,:]*b3*v2 + phip[2,:]*b2*v3
+           + phip[3,:]*b1*v4 + phip[4,:]*b0*v5) / zeta**7
+    D0 = a0*v0
+    D1 = (a2*v0 + phip[0,:]*a1*v1 + phip[1,:]*a0*v2) / zeta**3
+    D2 = (a4*v0 + phip[0,:]*a3*v1 + phip[1,:]*a2*v2 + phip[2,:]*a1*v3
+          + phip[3,:]*a0*v4) / zeta**6
+    # Derivative of U
+    # https://dlmf.nist.gov/12.10#E36
+    Ud = Pd * (Ai * (C0 + C1/mu**2.0 + C2/mu**4.0) / mu**(4.0/6.0) +
+               Aip * (D0 + D1/mu**2.0 + D2/mu**4.0))
+    return U, Ud
+
+
+def _newton(n, x_initial, maxit=5):
+    """Newton iteration for polishing the asymptotic approximation
+    to the zeros of the Hermite polynomials.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    x_initial : ndarray
+        Initial guesses for the roots
+    maxit : int
+        Maximal number of Newton iterations.
+        The default 5 is sufficient, usually
+        only one or two steps are needed.
+
+    Returns
+    -------
+    nodes : ndarray
+        Quadrature nodes
+    weights : ndarray
+        Quadrature weights
+
+    See Also
+    --------
+    roots_hermite_asy
+    """
+    # Variable transformation
+    mu = sqrt(2.0*n + 1.0)
+    t = x_initial / mu
+    theta = arccos(t)
+    # Newton iteration
+    for i in range(maxit):
+        u, ud = _pbcf(n, theta)
+        dtheta = u / (sqrt(2.0) * mu * sin(theta) * ud)
+        theta = theta + dtheta
+        if max(abs(dtheta)) < 1e-14:
+            break
+    # Undo variable transformation
+    x = mu * cos(theta)
+    # Central node is always zero
+    if n % 2 == 1:
+        x[0] = 0.0
+    # Compute weights
+    w = exp(-x**2) / (2.0*ud**2)
+    return x, w
+
+
+def _roots_hermite_asy(n):
+    r"""Gauss-Hermite (physicist's) quadrature for large n.
+
+    Computes the sample points and weights for Gauss-Hermite quadrature.
+    The sample points are the roots of the nth degree Hermite polynomial,
+    :math:`H_n(x)`. These sample points and weights correctly integrate
+    polynomials of degree :math:`2n - 1` or less over the interval
+    :math:`[-\infty, \infty]` with weight function :math:`f(x) = e^{-x^2}`.
+
+    This method relies on asymptotic expansions which work best for n > 150.
+    The algorithm has linear runtime making computation for very large n
+    feasible.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+
+    Returns
+    -------
+    nodes : ndarray
+        Quadrature nodes
+    weights : ndarray
+        Quadrature weights
+
+    See Also
+    --------
+    roots_hermite
+
+    References
+    ----------
+    .. [townsend.trogdon.olver-2014]
+       Townsend, A. and Trogdon, T. and Olver, S. (2014)
+       *Fast computation of Gauss quadrature nodes and
+       weights on the whole real line*. :arXiv:`1410.5286`.
+
+    .. [townsend.trogdon.olver-2015]
+       Townsend, A. and Trogdon, T. and Olver, S. (2015)
+       *Fast computation of Gauss quadrature nodes and
+       weights on the whole real line*.
+       IMA Journal of Numerical Analysis
+       :doi:`10.1093/imanum/drv002`.
+    """
+    iv = _initial_nodes(n)
+    nodes, weights = _newton(n, iv)
+    # Combine with negative parts
+    if n % 2 == 0:
+        nodes = hstack([-nodes[::-1], nodes])
+        weights = hstack([weights[::-1], weights])
+    else:
+        nodes = hstack([-nodes[-1:0:-1], nodes])
+        weights = hstack([weights[-1:0:-1], weights])
+    # Scale weights
+    weights *= sqrt(pi) / sum(weights)
+    return nodes, weights
+
+
+def hermite(n, monic=False):
+    r"""Physicist's Hermite polynomial.
+
+    Defined by
+
+    .. math::
+
+        H_n(x) = (-1)^ne^{x^2}\frac{d^n}{dx^n}e^{-x^2};
+
+    :math:`H_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    H : orthopoly1d
+        Hermite polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`H_n` are orthogonal over :math:`(-\infty,
+    \infty)` with weight function :math:`e^{-x^2}`.
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+
+    >>> p_monic = special.hermite(3, monic=True)
+    >>> p_monic
+    poly1d([ 1. ,  0. , -1.5,  0. ])
+    >>> p_monic(1)
+    -0.49999999999999983
+    >>> x = np.linspace(-3, 3, 400)
+    >>> y = p_monic(x)
+    >>> plt.plot(x, y)
+    >>> plt.title("Monic Hermite polynomial of degree 3")
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("H_3(x)")
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_hermite(n1)
+    def wfunc(x):
+        return exp(-x * x)
+    if n == 0:
+        x, w = [], []
+    hn = 2**n * _gam(n + 1) * sqrt(pi)
+    kn = 2**n
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-inf, inf), monic,
+                    lambda x: _ufuncs.eval_hermite(n, x))
+    return p
+
+# Hermite  2                         He_n(x)
+
+
+def roots_hermitenorm(n, mu=False):
+    r"""Gauss-Hermite (statistician's) quadrature.
+
+    Compute the sample points and weights for Gauss-Hermite
+    quadrature. The sample points are the roots of the nth degree
+    Hermite polynomial, :math:`He_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-\infty, \infty]` with weight
+    function :math:`w(x) = e^{-x^2/2}`. See 22.2.15 in [AS]_ for more
+    details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.hermite_e.hermegauss
+
+    Notes
+    -----
+    For small n up to 150 a modified version of the Golub-Welsch
+    algorithm is used. Nodes are computed from the eigenvalue
+    problem and improved by one step of a Newton iteration.
+    The weights are computed from the well-known analytical formula.
+
+    For n larger than 150 an optimal asymptotic algorithm is used
+    which computes nodes and weights in a numerical stable manner.
+    The algorithm has linear runtime making computation for very
+    large n (several thousand or more) feasible.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = np.sqrt(2.0*np.pi)
+    if n <= 150:
+        def an_func(k):
+            return 0.0 * k
+        def bn_func(k):
+            return np.sqrt(k)
+        f = _ufuncs.eval_hermitenorm
+        def df(n, x):
+            return n * _ufuncs.eval_hermitenorm(n - 1, x)
+        return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+    else:
+        nodes, weights = _roots_hermite_asy(m)
+        # Transform
+        nodes *= sqrt(2)
+        weights *= sqrt(2)
+        if mu:
+            return nodes, weights, mu0
+        else:
+            return nodes, weights
+
+
+def hermitenorm(n, monic=False):
+    r"""Normalized (probabilist's) Hermite polynomial.
+
+    Defined by
+
+    .. math::
+
+        He_n(x) = (-1)^ne^{x^2/2}\frac{d^n}{dx^n}e^{-x^2/2};
+
+    :math:`He_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    He : orthopoly1d
+        Hermite polynomial.
+
+    Notes
+    -----
+
+    The polynomials :math:`He_n` are orthogonal over :math:`(-\infty,
+    \infty)` with weight function :math:`e^{-x^2/2}`.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_hermitenorm(n1)
+    def wfunc(x):
+        return exp(-x * x / 2.0)
+    if n == 0:
+        x, w = [], []
+    hn = sqrt(2 * pi) * _gam(n + 1)
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(-inf, inf), monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_hermitenorm(n, x))
+    return p
+
+# The remainder of the polynomials can be derived from the ones above.
+
+# Ultraspherical (Gegenbauer)        C^(alpha)_n(x)
+
+
+def roots_gegenbauer(n, alpha, mu=False):
+    r"""Gauss-Gegenbauer quadrature.
+
+    Compute the sample points and weights for Gauss-Gegenbauer
+    quadrature. The sample points are the roots of the nth degree
+    Gegenbauer polynomial, :math:`C^{\alpha}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[-1, 1]` with
+    weight function :math:`w(x) = (1 - x^2)^{\alpha - 1/2}`. See
+    22.2.3 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -0.5
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha < -0.5:
+        raise ValueError("alpha must be greater than -0.5.")
+    elif alpha == 0.0:
+        # C(n,0,x) == 0 uniformly, however, as alpha->0, C(n,alpha,x)->T(n,x)
+        # strictly, we should just error out here, since the roots are not
+        # really defined, but we used to return something useful, so let's
+        # keep doing so.
+        return roots_chebyt(n, mu)
+
+    if alpha <= 170:
+        mu0 = (np.sqrt(np.pi) * _ufuncs.gamma(alpha + 0.5)) \
+              / _ufuncs.gamma(alpha + 1)
+    else:
+        # For large alpha we use a Taylor series expansion around inf,
+        # expressed as a 6th order polynomial of a^-1 and using Horner's
+        # method to minimize computation and maximize precision
+        inv_alpha = 1. / alpha
+        coeffs = np.array([0.000207186, -0.00152206, -0.000640869,
+                           0.00488281, 0.0078125, -0.125, 1.])
+        mu0 = coeffs[0]
+        for term in range(1, len(coeffs)):
+            mu0 = mu0 * inv_alpha + coeffs[term]
+        mu0 = mu0 * np.sqrt(np.pi / alpha)
+    def an_func(k):
+        return 0.0 * k
+    def bn_func(k):
+        return np.sqrt(k * (k + 2 * alpha - 1) / (4 * (k + alpha) * (k + alpha - 1)))
+    def f(n, x):
+        return _ufuncs.eval_gegenbauer(n, alpha, x)
+    def df(n, x):
+        return (
+            -n * x * _ufuncs.eval_gegenbauer(n, alpha, x)
+            + (n + 2 * alpha - 1) * _ufuncs.eval_gegenbauer(n - 1, alpha, x)
+        ) / (1 - x ** 2)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+
+
+def gegenbauer(n, alpha, monic=False):
+    r"""Gegenbauer (ultraspherical) polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}C_n^{(\alpha)}
+          - (2\alpha + 1)x\frac{d}{dx}C_n^{(\alpha)}
+          + n(n + 2\alpha)C_n^{(\alpha)} = 0
+
+    for :math:`\alpha > -1/2`; :math:`C_n^{(\alpha)}` is a polynomial
+    of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -0.5.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    C : orthopoly1d
+        Gegenbauer polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`C_n^{(\alpha)}` are orthogonal over
+    :math:`[-1,1]` with weight function :math:`(1 - x^2)^{(\alpha -
+    1/2)}`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    We can initialize a variable ``p`` as a Gegenbauer polynomial using the
+    `gegenbauer` function and evaluate at a point ``x = 1``.
+
+    >>> p = special.gegenbauer(3, 0.5, monic=False)
+    >>> p
+    poly1d([ 2.5,  0. , -1.5,  0. ])
+    >>> p(1)
+    1.0
+
+    To evaluate ``p`` at various points ``x`` in the interval ``(-3, 3)``,
+    simply pass an array ``x`` to ``p`` as follows:
+
+    >>> x = np.linspace(-3, 3, 400)
+    >>> y = p(x)
+
+    We can then visualize ``x, y`` using `matplotlib.pyplot`.
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y)
+    >>> ax.set_title("Gegenbauer (ultraspherical) polynomial of degree 3")
+    >>> ax.set_xlabel("x")
+    >>> ax.set_ylabel("G_3(x)")
+    >>> plt.show()
+
+    """
+    if not np.isfinite(alpha) or alpha <= -0.5 :
+        raise ValueError("`alpha` must be a finite number greater than -1/2")
+    base = jacobi(n, alpha - 0.5, alpha - 0.5, monic=monic)
+    if monic or n == 0:
+        return base
+    #  Abrahmowitz and Stegan 22.5.20
+    factor = (_gam(2*alpha + n) * _gam(alpha + 0.5) /
+              _gam(2*alpha) / _gam(alpha + 0.5 + n))
+    base._scale(factor)
+    base.__dict__['_eval_func'] = lambda x: _ufuncs.eval_gegenbauer(float(n),
+                                                                    alpha, x)
+    return base
+
+# Chebyshev of the first kind: T_n(x) =
+#     n! sqrt(pi) / _gam(n+1./2)* P^(-1/2,-1/2)_n(x)
+# Computed anew.
+
+
+def roots_chebyt(n, mu=False):
+    r"""Gauss-Chebyshev (first kind) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the first kind, :math:`T_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-1, 1]`
+    with weight function :math:`w(x) = 1/\sqrt{1 - x^2}`. See 22.2.4
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.chebyshev.chebgauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError('n must be a positive integer.')
+    x = _ufuncs._sinpi(np.arange(-m + 1, m, 2) / (2*m))
+    w = np.full_like(x, pi/m)
+    if mu:
+        return x, w, pi
+    else:
+        return x, w
+
+
+def chebyt(n, monic=False):
+    r"""Chebyshev polynomial of the first kind.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}T_n - x\frac{d}{dx}T_n + n^2T_n = 0;
+
+    :math:`T_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    T : orthopoly1d
+        Chebyshev polynomial of the first kind.
+
+    See Also
+    --------
+    chebyu : Chebyshev polynomial of the second kind.
+
+    Notes
+    -----
+    The polynomials :math:`T_n` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x^2)^{-1/2}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Chebyshev polynomials of the first kind of order :math:`n` can
+    be obtained as the determinant of specific :math:`n \times n`
+    matrices. As an example we can check how the points obtained from
+    the determinant of the following :math:`3 \times 3` matrix
+    lay exactly on :math:`T_3`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.linalg import det
+    >>> from scipy.special import chebyt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Chebyshev polynomial $T_3$')
+    >>> ax.plot(x, chebyt(3)(x), label=rf'$T_3$')
+    >>> for p in np.arange(-1.0, 1.0, 0.1):
+    ...     ax.plot(p,
+    ...             det(np.array([[p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])),
+    ...             'rx')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    They are also related to the Jacobi Polynomials
+    :math:`P_n^{(-0.5, -0.5)}` through the relation:
+
+    .. math::
+        P_n^{(-0.5, -0.5)}(x) = \frac{1}{4^n} \binom{2n}{n} T_n(x)
+
+    Let's verify it for :math:`n = 3`:
+
+    >>> from scipy.special import binom
+    >>> from scipy.special import jacobi
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(jacobi(3, -0.5, -0.5)(x),
+    ...             1/64 * binom(6, 3) * chebyt(3)(x))
+    True
+
+    We can plot the Chebyshev polynomials :math:`T_n` for some values
+    of :math:`n`:
+
+    >>> x = np.arange(-1.5, 1.5, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-4.0, 4.0)
+    >>> ax.set_title(r'Chebyshev polynomials $T_n$')
+    >>> for n in np.arange(2,5):
+    ...     ax.plot(x, chebyt(n)(x), label=rf'$T_n={n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return 1.0 / sqrt(1 - x * x)
+    if n == 0:
+        return orthopoly1d([], [], pi, 1.0, wfunc, (-1, 1), monic,
+                           lambda x: _ufuncs.eval_chebyt(n, x))
+    n1 = n
+    x, w, mu = roots_chebyt(n1, mu=True)
+    hn = pi / 2
+    kn = 2**(n - 1)
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
+                    lambda x: _ufuncs.eval_chebyt(n, x))
+    return p
+
+# Chebyshev of the second kind
+#    U_n(x) = (n+1)! sqrt(pi) / (2*_gam(n+3./2)) * P^(1/2,1/2)_n(x)
+
+
+def roots_chebyu(n, mu=False):
+    r"""Gauss-Chebyshev (second kind) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the second kind, :math:`U_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-1, 1]`
+    with weight function :math:`w(x) = \sqrt{1 - x^2}`. See 22.2.5 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError('n must be a positive integer.')
+    t = np.arange(m, 0, -1) * pi / (m + 1)
+    x = np.cos(t)
+    w = pi * np.sin(t)**2 / (m + 1)
+    if mu:
+        return x, w, pi / 2
+    else:
+        return x, w
+
+
+def chebyu(n, monic=False):
+    r"""Chebyshev polynomial of the second kind.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}U_n - 3x\frac{d}{dx}U_n
+          + n(n + 2)U_n = 0;
+
+    :math:`U_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    U : orthopoly1d
+        Chebyshev polynomial of the second kind.
+
+    See Also
+    --------
+    chebyt : Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`U_n` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x^2)^{1/2}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Chebyshev polynomials of the second kind of order :math:`n` can
+    be obtained as the determinant of specific :math:`n \times n`
+    matrices. As an example we can check how the points obtained from
+    the determinant of the following :math:`3 \times 3` matrix
+    lay exactly on :math:`U_3`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.linalg import det
+    >>> from scipy.special import chebyu
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Chebyshev polynomial $U_3$')
+    >>> ax.plot(x, chebyu(3)(x), label=rf'$U_3$')
+    >>> for p in np.arange(-1.0, 1.0, 0.1):
+    ...     ax.plot(p,
+    ...             det(np.array([[2*p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])),
+    ...             'rx')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    They satisfy the recurrence relation:
+
+    .. math::
+        U_{2n-1}(x) = 2 T_n(x)U_{n-1}(x)
+
+    where the :math:`T_n` are the Chebyshev polynomial of the first kind.
+    Let's verify it for :math:`n = 2`:
+
+    >>> from scipy.special import chebyt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(chebyu(3)(x), 2 * chebyt(2)(x) * chebyu(1)(x))
+    True
+
+    We can plot the Chebyshev polynomials :math:`U_n` for some values
+    of :math:`n`:
+
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-1.5, 1.5)
+    >>> ax.set_title(r'Chebyshev polynomials $U_n$')
+    >>> for n in np.arange(1,5):
+    ...     ax.plot(x, chebyu(n)(x), label=rf'$U_n={n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    base = jacobi(n, 0.5, 0.5, monic=monic)
+    if monic:
+        return base
+    factor = sqrt(pi) / 2.0 * _gam(n + 2) / _gam(n + 1.5)
+    base._scale(factor)
+    return base
+
+# Chebyshev of the first kind        C_n(x)
+
+
+def roots_chebyc(n, mu=False):
+    r"""Gauss-Chebyshev (first kind) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the first kind, :math:`C_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-2, 2]`
+    with weight function :math:`w(x) = 1 / \sqrt{1 - (x/2)^2}`. See
+    22.2.6 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyt(n, True)
+    x *= 2
+    w *= 2
+    m *= 2
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def chebyc(n, monic=False):
+    r"""Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+
+    Defined as :math:`C_n(x) = 2T_n(x/2)`, where :math:`T_n` is the
+    nth Chebychev polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    C : orthopoly1d
+        Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+
+    See Also
+    --------
+    chebyt : Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`C_n(x)` are orthogonal over :math:`[-2, 2]`
+    with weight function :math:`1/\sqrt{1 - (x/2)^2}`.
+
+    References
+    ----------
+    .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions"
+           Section 22. National Bureau of Standards, 1972.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_chebyc(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 4 * pi * ((n == 0) + 1)
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn,
+                    wfunc=lambda x: 1.0 / sqrt(1 - x * x / 4.0),
+                    limits=(-2, 2), monic=monic)
+    if not monic:
+        p._scale(2.0 / p(2))
+        p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebyc(n, x)
+    return p
+
+# Chebyshev of the second kind       S_n(x)
+
+
+def roots_chebys(n, mu=False):
+    r"""Gauss-Chebyshev (second kind) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the second kind, :math:`S_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-2, 2]`
+    with weight function :math:`w(x) = \sqrt{1 - (x/2)^2}`. See 22.2.7
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyu(n, True)
+    x *= 2
+    w *= 2
+    m *= 2
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def chebys(n, monic=False):
+    r"""Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+
+    Defined as :math:`S_n(x) = U_n(x/2)` where :math:`U_n` is the
+    nth Chebychev polynomial of the second kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    S : orthopoly1d
+        Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+
+    See Also
+    --------
+    chebyu : Chebyshev polynomial of the second kind
+
+    Notes
+    -----
+    The polynomials :math:`S_n(x)` are orthogonal over :math:`[-2, 2]`
+    with weight function :math:`\sqrt{1 - (x/2)}^2`.
+
+    References
+    ----------
+    .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions"
+           Section 22. National Bureau of Standards, 1972.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_chebys(n1)
+    if n == 0:
+        x, w = [], []
+    hn = pi
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn,
+                    wfunc=lambda x: sqrt(1 - x * x / 4.0),
+                    limits=(-2, 2), monic=monic)
+    if not monic:
+        factor = (n + 1.0) / p(2)
+        p._scale(factor)
+        p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebys(n, x)
+    return p
+
+# Shifted Chebyshev of the first kind     T^*_n(x)
+
+
+def roots_sh_chebyt(n, mu=False):
+    r"""Gauss-Chebyshev (first kind, shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    shifted Chebyshev polynomial of the first kind, :math:`T_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0, 1]`
+    with weight function :math:`w(x) = 1/\sqrt{x - x^2}`. See 22.2.8
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    xw = roots_chebyt(n, mu)
+    return ((xw[0] + 1) / 2,) + xw[1:]
+
+
+def sh_chebyt(n, monic=False):
+    r"""Shifted Chebyshev polynomial of the first kind.
+
+    Defined as :math:`T^*_n(x) = T_n(2x - 1)` for :math:`T_n` the nth
+    Chebyshev polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    T : orthopoly1d
+        Shifted Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`T^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function :math:`(x - x^2)^{-1/2}`.
+
+    """
+    base = sh_jacobi(n, 0.0, 0.5, monic=monic)
+    if monic:
+        return base
+    if n > 0:
+        factor = 4**n / 2.0
+    else:
+        factor = 1.0
+    base._scale(factor)
+    return base
+
+
+# Shifted Chebyshev of the second kind    U^*_n(x)
+def roots_sh_chebyu(n, mu=False):
+    r"""Gauss-Chebyshev (second kind, shifted) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    shifted Chebyshev polynomial of the second kind, :math:`U_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0, 1]`
+    with weight function :math:`w(x) = \sqrt{x - x^2}`. See 22.2.9 in
+    [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyu(n, True)
+    x = (x + 1) / 2
+    m_us = _ufuncs.beta(1.5, 1.5)
+    w *= m_us / m
+    if mu:
+        return x, w, m_us
+    else:
+        return x, w
+
+
+def sh_chebyu(n, monic=False):
+    r"""Shifted Chebyshev polynomial of the second kind.
+
+    Defined as :math:`U^*_n(x) = U_n(2x - 1)` for :math:`U_n` the nth
+    Chebyshev polynomial of the second kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    U : orthopoly1d
+        Shifted Chebyshev polynomial of the second kind.
+
+    Notes
+    -----
+    The polynomials :math:`U^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function :math:`(x - x^2)^{1/2}`.
+
+    """
+    base = sh_jacobi(n, 2.0, 1.5, monic=monic)
+    if monic:
+        return base
+    factor = 4**n
+    base._scale(factor)
+    return base
+
+# Legendre
+
+
+def roots_legendre(n, mu=False):
+    r"""Gauss-Legendre quadrature.
+
+    Compute the sample points and weights for Gauss-Legendre
+    quadrature [GL]_. The sample points are the roots of the nth degree
+    Legendre polynomial :math:`P_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-1, 1]` with weight function
+    :math:`w(x) = 1`. See 2.2.10 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.legendre.leggauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [GL] Gauss-Legendre quadrature, Wikipedia,
+        https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_quadrature
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import roots_legendre, eval_legendre
+    >>> roots, weights = roots_legendre(9)
+
+    ``roots`` holds the roots, and ``weights`` holds the weights for
+    Gauss-Legendre quadrature.
+
+    >>> roots
+    array([-0.96816024, -0.83603111, -0.61337143, -0.32425342,  0.        ,
+            0.32425342,  0.61337143,  0.83603111,  0.96816024])
+    >>> weights
+    array([0.08127439, 0.18064816, 0.2606107 , 0.31234708, 0.33023936,
+           0.31234708, 0.2606107 , 0.18064816, 0.08127439])
+
+    Verify that we have the roots by evaluating the degree 9 Legendre
+    polynomial at ``roots``.  All the values are approximately zero:
+
+    >>> eval_legendre(9, roots)
+    array([-8.88178420e-16, -2.22044605e-16,  1.11022302e-16,  1.11022302e-16,
+            0.00000000e+00, -5.55111512e-17, -1.94289029e-16,  1.38777878e-16,
+           -8.32667268e-17])
+
+    Here we'll show how the above values can be used to estimate the
+    integral from 1 to 2 of f(t) = t + 1/t with Gauss-Legendre
+    quadrature [GL]_.  First define the function and the integration
+    limits.
+
+    >>> def f(t):
+    ...    return t + 1/t
+    ...
+    >>> a = 1
+    >>> b = 2
+
+    We'll use ``integral(f(t), t=a, t=b)`` to denote the definite integral
+    of f from t=a to t=b.  The sample points in ``roots`` are from the
+    interval [-1, 1], so we'll rewrite the integral with the simple change
+    of variable::
+
+        x = 2/(b - a) * t - (a + b)/(b - a)
+
+    with inverse::
+
+        t = (b - a)/2 * x + (a + b)/2
+
+    Then::
+
+        integral(f(t), a, b) =
+            (b - a)/2 * integral(f((b-a)/2*x + (a+b)/2), x=-1, x=1)
+
+    We can approximate the latter integral with the values returned
+    by `roots_legendre`.
+
+    Map the roots computed above from [-1, 1] to [a, b].
+
+    >>> t = (b - a)/2 * roots + (a + b)/2
+
+    Approximate the integral as the weighted sum of the function values.
+
+    >>> (b - a)/2 * f(t).dot(weights)
+    2.1931471805599276
+
+    Compare that to the exact result, which is 3/2 + log(2):
+
+    >>> 1.5 + np.log(2)
+    2.1931471805599454
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = 2.0
+    def an_func(k):
+        return 0.0 * k
+    def bn_func(k):
+        return k * np.sqrt(1.0 / (4 * k * k - 1))
+    f = _ufuncs.eval_legendre
+    def df(n, x):
+        return (-n * x * _ufuncs.eval_legendre(n, x)
+                + n * _ufuncs.eval_legendre(n - 1, x)) / (1 - x ** 2)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+
+
+def legendre(n, monic=False):
+    r"""Legendre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        \frac{d}{dx}\left[(1 - x^2)\frac{d}{dx}P_n(x)\right]
+          + n(n + 1)P_n(x) = 0;
+
+    :math:`P_n(x)` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Legendre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`P_n` are orthogonal over :math:`[-1, 1]`
+    with weight function 1.
+
+    Examples
+    --------
+    Generate the 3rd-order Legendre polynomial 1/2*(5x^3 + 0x^2 - 3x + 0):
+
+    >>> from scipy.special import legendre
+    >>> legendre(3)
+    poly1d([ 2.5,  0. , -1.5,  0. ])
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_legendre(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 2.0 / (2 * n + 1)
+    kn = _gam(2 * n + 1) / _gam(n + 1)**2 / 2.0**n
+    p = orthopoly1d(x, w, hn, kn, wfunc=lambda x: 1.0, limits=(-1, 1),
+                    monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_legendre(n, x))
+    return p
+
+# Shifted Legendre              P^*_n(x)
+
+
+def roots_sh_legendre(n, mu=False):
+    r"""Gauss-Legendre (shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Legendre
+    quadrature. The sample points are the roots of the nth degree
+    shifted Legendre polynomial :math:`P^*_n(x)`. These sample points
+    and weights correctly integrate polynomials of degree :math:`2n -
+    1` or less over the interval :math:`[0, 1]` with weight function
+    :math:`w(x) = 1.0`. See 2.2.11 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w = roots_legendre(n)
+    x = (x + 1) / 2
+    w /= 2
+    if mu:
+        return x, w, 1.0
+    else:
+        return x, w
+
+
+def sh_legendre(n, monic=False):
+    r"""Shifted Legendre polynomial.
+
+    Defined as :math:`P^*_n(x) = P_n(2x - 1)` for :math:`P_n` the nth
+    Legendre polynomial.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Shifted Legendre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`P^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function 1.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return 0.0 * x + 1.0
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (0, 1), monic,
+                           lambda x: _ufuncs.eval_sh_legendre(n, x))
+    x, w = roots_sh_legendre(n)
+    hn = 1.0 / (2 * n + 1.0)
+    kn = _gam(2 * n + 1) / _gam(n + 1)**2
+    p = orthopoly1d(x, w, hn, kn, wfunc, limits=(0, 1), monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_sh_legendre(n, x))
+    return p
+
+
+# Make the old root function names an alias for the new ones
+_modattrs = globals()
+for newfun, oldfun in _rootfuns_map.items():
+    _modattrs[oldfun] = _modattrs[newfun]
+    __all__.append(oldfun)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e0ae3ce3be90187cd957fe16cc6d145a7093da5a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi
@@ -0,0 +1,330 @@
+from typing import (
+    Any,
+    Callable,
+    Literal,
+    Optional,
+    overload,
+)
+
+import numpy as np
+
+_IntegerType = int | np.integer
+_FloatingType = float | np.floating
+_PointsAndWeights = tuple[np.ndarray, np.ndarray]
+_PointsAndWeightsAndMu = tuple[np.ndarray, np.ndarray, float]
+
+_ArrayLike0D = bool | int | float | complex | str | bytes | np.generic
+
+__all__ = [
+    'legendre',
+    'chebyt',
+    'chebyu',
+    'chebyc',
+    'chebys',
+    'jacobi',
+    'laguerre',
+    'genlaguerre',
+    'hermite',
+    'hermitenorm',
+    'gegenbauer',
+    'sh_legendre',
+    'sh_chebyt',
+    'sh_chebyu',
+    'sh_jacobi',
+    'roots_legendre',
+    'roots_chebyt',
+    'roots_chebyu',
+    'roots_chebyc',
+    'roots_chebys',
+    'roots_jacobi',
+    'roots_laguerre',
+    'roots_genlaguerre',
+    'roots_hermite',
+    'roots_hermitenorm',
+    'roots_gegenbauer',
+    'roots_sh_legendre',
+    'roots_sh_chebyt',
+    'roots_sh_chebyu',
+    'roots_sh_jacobi',
+]
+
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_laguerre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_laguerre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_laguerre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_hermite(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_hermite(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_hermite(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_hermitenorm(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_hermitenorm(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_hermitenorm(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyt(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyt(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyt(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyu(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyu(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyu(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyc(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyc(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyc(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebys(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebys(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebys(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_chebyt(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyt(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyt(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_chebyu(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyu(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyu(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_legendre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_legendre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_legendre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_legendre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_legendre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_legendre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+class orthopoly1d(np.poly1d):
+    def __init__(
+            self,
+            roots: np.typing.ArrayLike,
+            weights: np.typing.ArrayLike | None,
+            hn: float = ...,
+            kn: float = ...,
+            wfunc = Optional[Callable[[float], float]],  # noqa: UP007
+            limits = tuple[float, float] | None,
+            monic: bool = ...,
+            eval_func: np.ufunc = ...,
+    ) -> None: ...
+    @property
+    def limits(self) -> tuple[float, float]: ...
+    def weight_func(self, x: float) -> float: ...
+    @overload
+    def __call__(self, x: _ArrayLike0D) -> Any: ...
+    @overload
+    def __call__(self, x: np.poly1d) -> np.poly1d: ...  # type: ignore[overload-overlap]
+    @overload
+    def __call__(self, x: np.typing.ArrayLike) -> np.ndarray: ...
+
+def legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyc(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebys(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def laguerre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def hermite(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def hermitenorm(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def sh_legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_jacobi(
+        n: _IntegerType,
+        p: _FloatingType,
+        q: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+
+# These functions are not public, but still need stubs because they
+# get checked in the tests.
+def _roots_hermite_asy(n: _IntegerType) -> _PointsAndWeights: ...
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..662c12bc74b31478c87471fbd1cce8bea285e765
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py
@@ -0,0 +1,17 @@
+import mpmath
+
+
+def f(x):
+    return (mpmath.pi + x + mpmath.sin(x)) / (2*mpmath.pi)
+
+
+# Note: 40 digits might be overkill; a few more digits than the default
+# might be sufficient.
+mpmath.mp.dps = 40
+ts = mpmath.taylor(f, -mpmath.pi, 20)
+p, q = mpmath.pade(ts, 9, 10)
+
+p = [float(c) for c in p]
+q = [float(c) for c in q]
+print('p =', p)
+print('q =', q)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py
new file mode 100644
index 0000000000000000000000000000000000000000..3491b8acd588a2cacfc48f0a3a60c6ae88c3e8c5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py
@@ -0,0 +1,54 @@
+"""Precompute the polynomials for the asymptotic expansion of the
+generalized exponential integral.
+
+Sources
+-------
+[1] NIST, Digital Library of Mathematical Functions,
+    https://dlmf.nist.gov/8.20#ii
+
+"""
+import os
+
+try:
+    import sympy
+    from sympy import Poly
+    x = sympy.symbols('x')
+except ImportError:
+    pass
+
+
+def generate_A(K):
+    A = [Poly(1, x)]
+    for k in range(K):
+        A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff())
+    return A
+
+
+WARNING = """\
+/* This file was automatically generated by _precompute/expn_asy.py.
+ * Do not edit it manually!
+ */
+"""
+
+
+def main():
+    print(__doc__)
+    fn = os.path.join('..', 'cephes', 'expn.h')
+
+    K = 12
+    A = generate_A(K)
+    with open(fn + '.new', 'w') as f:
+        f.write(WARNING)
+        f.write(f"#define nA {len(A)}\n")
+        for k, Ak in enumerate(A):
+            ', '.join([str(x.evalf(18)) for x in Ak.coeffs()])
+            f.write(f"static const double A{k}[] = {{tmp}};\n")
+        ", ".join([f"A{k}" for k in range(K + 1)])
+        f.write("static const double *A[] = {{tmp}};\n")
+        ", ".join([str(Ak.degree()) for Ak in A])
+        f.write("static const int Adegs[] = {{tmp}};\n")
+    os.rename(fn + '.new', fn)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py
new file mode 100644
index 0000000000000000000000000000000000000000..98035457c78706ae01c02273ae1ab458b4ca140d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py
@@ -0,0 +1,116 @@
+"""
+Precompute coefficients of Temme's asymptotic expansion for gammainc.
+
+This takes about 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram.
+
+Sources:
+[1] NIST, "Digital Library of Mathematical Functions",
+    https://dlmf.nist.gov/
+
+"""
+import os
+from scipy.special._precompute.utils import lagrange_inversion
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+
+def compute_a(n):
+    """a_k from DLMF 5.11.6"""
+    a = [mp.sqrt(2)/2]
+    for k in range(1, n):
+        ak = a[-1]/k
+        for j in range(1, len(a)):
+            ak -= a[j]*a[-j]/(j + 1)
+        ak /= a[0]*(1 + mp.mpf(1)/(k + 1))
+        a.append(ak)
+    return a
+
+
+def compute_g(n):
+    """g_k from DLMF 5.11.3/5.11.5"""
+    a = compute_a(2*n)
+    g = [mp.sqrt(2)*mp.rf(0.5, k)*a[2*k] for k in range(n)]
+    return g
+
+
+def eta(lam):
+    """Function from DLMF 8.12.1 shifted to be centered at 0."""
+    if lam > 0:
+        return mp.sqrt(2*(lam - mp.log(lam + 1)))
+    elif lam < 0:
+        return -mp.sqrt(2*(lam - mp.log(lam + 1)))
+    else:
+        return 0
+
+
+def compute_alpha(n):
+    """alpha_n from DLMF 8.12.13"""
+    coeffs = mp.taylor(eta, 0, n - 1)
+    return lagrange_inversion(coeffs)
+
+
+def compute_d(K, N):
+    """d_{k, n} from DLMF 8.12.12"""
+    M = N + 2*K
+    d0 = [-mp.mpf(1)/3]
+    alpha = compute_alpha(M + 2)
+    for n in range(1, M):
+        d0.append((n + 2)*alpha[n+2])
+    d = [d0]
+    g = compute_g(K)
+    for k in range(1, K):
+        dk = []
+        for n in range(M - 2*k):
+            dk.append((-1)**k*g[k]*d[0][n] + (n + 2)*d[k-1][n+2])
+        d.append(dk)
+    for k in range(K):
+        d[k] = d[k][:N]
+    return d
+
+
+header = \
+r"""/* This file was automatically generated by _precomp/gammainc.py.
+ * Do not edit it manually!
+ */
+
+#ifndef IGAM_H
+#define IGAM_H
+
+#define K {}
+#define N {}
+
+static const double d[K][N] =
+{{"""
+
+footer = \
+r"""
+#endif
+"""
+
+
+def main():
+    print(__doc__)
+    K = 25
+    N = 25
+    with mp.workdps(50):
+        d = compute_d(K, N)
+    fn = os.path.join(os.path.dirname(__file__), '..', 'cephes', 'igam.h')
+    with open(fn + '.new', 'w') as f:
+        f.write(header.format(K, N))
+        for k, row in enumerate(d):
+            row = [mp.nstr(x, 17, min_fixed=0, max_fixed=0) for x in row]
+            f.write('{')
+            f.write(", ".join(row))
+            if k < K - 1:
+                f.write('},\n')
+            else:
+                f.write('}};\n')
+        f.write(footer)
+    os.rename(fn + '.new', fn)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebbe39f6159fb80c424dbb38eedeba46bd8cccf2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py
@@ -0,0 +1,124 @@
+"""Compute gammainc and gammaincc for large arguments and parameters
+and save the values to data files for use in tests. We can't just
+compare to mpmath's gammainc in test_mpmath.TestSystematic because it
+would take too long.
+
+Note that mpmath's gammainc is computed using hypercomb, but since it
+doesn't allow the user to increase the maximum number of terms used in
+the series it doesn't converge for many arguments. To get around this
+we copy the mpmath implementation but use more terms.
+
+This takes about 17 minutes to run on a 2.3 GHz Macbook Pro with 4GB
+ram.
+
+Sources:
+[1] Fredrik Johansson and others. mpmath: a Python library for
+    arbitrary-precision floating-point arithmetic (version 0.19),
+    December 2013. http://mpmath.org/.
+
+"""
+import os
+from time import time
+import numpy as np
+from numpy import pi
+
+from scipy.special._mptestutils import mpf2float
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+
+def gammainc(a, x, dps=50, maxterms=10**8):
+    """Compute gammainc exactly like mpmath does but allow for more
+    summands in hypercomb. See
+
+    mpmath/functions/expintegrals.py#L134
+
+    in the mpmath GitHub repository.
+
+    """
+    with mp.workdps(dps):
+        z, a, b = mp.mpf(a), mp.mpf(x), mp.mpf(x)
+        G = [z]
+        negb = mp.fneg(b, exact=True)
+
+        def h(z):
+            T1 = [mp.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b
+            return (T1,)
+
+        res = mp.hypercomb(h, [z], maxterms=maxterms)
+        return mpf2float(res)
+
+
+def gammaincc(a, x, dps=50, maxterms=10**8):
+    """Compute gammaincc exactly like mpmath does but allow for more
+    terms in hypercomb. See
+
+    mpmath/functions/expintegrals.py#L187
+
+    in the mpmath GitHub repository.
+
+    """
+    with mp.workdps(dps):
+        z, a = a, x
+
+        if mp.isint(z):
+            try:
+                # mpmath has a fast integer path
+                return mpf2float(mp.gammainc(z, a=a, regularized=True))
+            except mp.libmp.NoConvergence:
+                pass
+        nega = mp.fneg(a, exact=True)
+        G = [z]
+        # Use 2F0 series when possible; fall back to lower gamma representation
+        try:
+            def h(z):
+                r = z-1
+                return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)]
+            return mpf2float(mp.hypercomb(h, [z], force_series=True))
+        except mp.libmp.NoConvergence:
+            def h(z):
+                T1 = [], [1, z-1], [z], G, [], [], 0
+                T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a
+                return T1, T2
+            return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms))
+
+
+def main():
+    t0 = time()
+    # It would be nice to have data for larger values, but either this
+    # requires prohibitively large precision (dps > 800) or mpmath has
+    # a bug. For example, gammainc(1e20, 1e20, dps=800) returns a
+    # value around 0.03, while the true value should be close to 0.5
+    # (DLMF 8.12.15).
+    print(__doc__)
+    pwd = os.path.dirname(__file__)
+    r = np.logspace(4, 14, 30)
+    ltheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(0.6)), 30)
+    utheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(1.4)), 30)
+
+    regimes = [(gammainc, ltheta), (gammaincc, utheta)]
+    for func, theta in regimes:
+        rg, thetag = np.meshgrid(r, theta)
+        a, x = rg*np.cos(thetag), rg*np.sin(thetag)
+        a, x = a.flatten(), x.flatten()
+        dataset = []
+        for i, (a0, x0) in enumerate(zip(a, x)):
+            if func == gammaincc:
+                # Exploit the fast integer path in gammaincc whenever
+                # possible so that the computation doesn't take too
+                # long
+                a0, x0 = np.floor(a0), np.floor(x0)
+            dataset.append((a0, x0, func(a0, x0)))
+        dataset = np.array(dataset)
+        filename = os.path.join(pwd, '..', 'tests', 'data', 'local',
+                                f'{func.__name__}.txt')
+        np.savetxt(filename, dataset)
+
+    print(f"{(time() - t0)/60} minutes elapsed")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4adf14f49184bf75048a28a823909d24e778e04
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py
@@ -0,0 +1,484 @@
+"""This script evaluates scipy's implementation of hyp2f1 against mpmath's.
+
+Author: Albert Steppi
+
+This script is long running and generates a large output file. With default
+arguments, the generated file is roughly 700MB in size and it takes around
+40 minutes using an Intel(R) Core(TM) i5-8250U CPU with n_jobs set to 8
+(full utilization). There are optional arguments which can be used to restrict
+(or enlarge) the computations performed. These are described below.
+The output of this script can be analyzed to identify suitable test cases and
+to find parameter and argument regions where hyp2f1 needs to be improved.
+
+The script has one mandatory positional argument for specifying the path to
+the location where the output file is to be placed, and 4 optional arguments
+--n_jobs, --grid_size, --regions, and --parameter_groups. --n_jobs specifies
+the number of processes to use if running in parallel. The default value is 1.
+The other optional arguments are explained below.
+
+Produces a tab separated values file with 11 columns. The first four columns
+contain the parameters a, b, c and the argument z. The next two contain |z| and
+a region code for which region of the complex plane belongs to. The regions are
+
+    0) z == 1
+    1) |z| < 0.9 and real(z) >= 0
+    2) |z| <= 1 and real(z) < 0
+    3) 0.9 <= |z| <= 1 and |1 - z| < 0.9:
+    4) 0.9 <= |z| <= 1 and |1 - z| >= 0.9 and real(z) >= 0:
+    5) 1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0
+    6) |z| > 1 and not in 5)
+
+The --regions optional argument allows the user to specify a list of regions
+to which computation will be restricted.
+
+Parameters a, b, c are taken from a 10 * 10 * 10 grid with values at
+
+    -16, -8, -4, -2, -1, 1, 2, 4, 8, 16
+
+with random perturbations applied.
+
+There are 9 parameter groups handling the following cases.
+
+    1) A, B, C, B - A, C - A, C - B, C - A - B all non-integral.
+    2) B - A integral
+    3) C - A integral
+    4) C - B integral
+    5) C - A - B integral
+    6) A integral
+    7) B integral
+    8) C integral
+    9) Wider range with c - a - b > 0.
+
+The seventh column of the output file is an integer between 1 and 8 specifying
+the parameter group as above.
+
+The --parameter_groups optional argument allows the user to specify a list of
+parameter groups to which computation will be restricted.
+
+The argument z is taken from a grid in the box
+    -box_size <= real(z) <= box_size, -box_size <= imag(z) <= box_size.
+with grid size specified using the optional command line argument --grid_size,
+and box_size specified with the command line argument --box_size.
+The default value of grid_size is 20 and the default value of box_size is 2.0,
+yielding a 20 * 20 grid in the box with corners -2-2j, -2+2j, 2-2j, 2+2j.
+
+The final four columns have the expected value of hyp2f1 for the given
+parameters and argument as calculated with mpmath, the observed value
+calculated with scipy's hyp2f1, the relative error, and the absolute error.
+
+As special cases of hyp2f1 are moved from the original Fortran implementation
+into Cython, this script can be used to ensure that no regressions occur and
+to point out where improvements are needed.
+"""
+
+
+import os
+import csv
+import argparse
+import numpy as np
+from itertools import product
+from multiprocessing import Pool
+
+
+from scipy.special import hyp2f1
+from scipy.special.tests.test_hyp2f1 import mp_hyp2f1
+
+
+def get_region(z):
+    """Assign numbers for regions where hyp2f1 must be handled differently."""
+    if z == 1 + 0j:
+        return 0
+    elif abs(z) < 0.9 and z.real >= 0:
+        return 1
+    elif abs(z) <= 1 and z.real < 0:
+        return 2
+    elif 0.9 <= abs(z) <= 1 and abs(1 - z) < 0.9:
+        return 3
+    elif 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9:
+        return 4
+    elif 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0:
+        return 5
+    else:
+        return 6
+
+
+def get_result(a, b, c, z, group):
+    """Get results for given parameter and value combination."""
+    expected, observed = mp_hyp2f1(a, b, c, z), hyp2f1(a, b, c, z)
+    if (
+            np.isnan(observed) and np.isnan(expected) or
+            expected == observed
+    ):
+        relative_error = 0.0
+        absolute_error = 0.0
+    elif np.isnan(observed):
+        # Set error to infinity if result is nan when not expected to be.
+        # Makes results easier to interpret.
+        relative_error = float("inf")
+        absolute_error = float("inf")
+    else:
+        absolute_error = abs(expected - observed)
+        relative_error = absolute_error / abs(expected)
+
+    return (
+        a,
+        b,
+        c,
+        z,
+        abs(z),
+        get_region(z),
+        group,
+        expected,
+        observed,
+        relative_error,
+        absolute_error,
+    )
+
+
+def get_result_no_mp(a, b, c, z, group):
+    """Get results for given parameter and value combination."""
+    expected, observed = complex('nan'), hyp2f1(a, b, c, z)
+    relative_error, absolute_error = float('nan'), float('nan')
+    return (
+        a,
+        b,
+        c,
+        z,
+        abs(z),
+        get_region(z),
+        group,
+        expected,
+        observed,
+        relative_error,
+        absolute_error,
+    )
+
+
+def get_results(params, Z, n_jobs=1, compute_mp=True):
+    """Batch compute results for multiple parameter and argument values.
+
+    Parameters
+    ----------
+    params : iterable
+        iterable of tuples of floats (a, b, c) specifying parameter values
+        a, b, c for hyp2f1
+    Z : iterable of complex
+        Arguments at which to evaluate hyp2f1
+    n_jobs : Optional[int]
+        Number of jobs for parallel execution.
+
+    Returns
+    -------
+    list
+        List of tuples of results values. See return value in source code
+        of `get_result`.
+    """
+    input_ = (
+        (a, b, c, z, group) for (a, b, c, group), z in product(params, Z)
+    )
+
+    with Pool(n_jobs) as pool:
+        rows = pool.starmap(
+            get_result if compute_mp else get_result_no_mp,
+            input_
+        )
+    return rows
+
+
+def _make_hyp2f1_test_case(a, b, c, z, rtol):
+    """Generate string for single test case as used in test_hyp2f1.py."""
+    expected = mp_hyp2f1(a, b, c, z)
+    return (
+        "    pytest.param(\n"
+        "        Hyp2f1TestCase(\n"
+        f"            a={a},\n"
+        f"            b={b},\n"
+        f"            c={c},\n"
+        f"            z={z},\n"
+        f"            expected={expected},\n"
+        f"            rtol={rtol},\n"
+        "        ),\n"
+        "    ),"
+    )
+
+
+def make_hyp2f1_test_cases(rows):
+    """Generate string for a list of test cases for test_hyp2f1.py.
+
+    Parameters
+    ----------
+    rows : list
+        List of lists of the form [a, b, c, z, rtol] where a, b, c, z are
+        parameters and the argument for hyp2f1 and rtol is an expected
+        relative error for the associated test case.
+
+    Returns
+    -------
+    str
+        String for a list of test cases. The output string can be printed
+        or saved to a file and then copied into an argument for
+        `pytest.mark.parameterize` within `scipy.special.tests.test_hyp2f1.py`.
+    """
+    result = "[\n"
+    result += '\n'.join(
+        _make_hyp2f1_test_case(a, b, c, z, rtol)
+        for a, b, c, z, rtol in rows
+    )
+    result += "\n]"
+    return result
+
+
+def main(
+        outpath,
+        n_jobs=1,
+        box_size=2.0,
+        grid_size=20,
+        regions=None,
+        parameter_groups=None,
+        compute_mp=True,
+):
+    outpath = os.path.realpath(os.path.expanduser(outpath))
+
+    random_state = np.random.RandomState(1234)
+    # Parameters a, b, c selected near these values.
+    root_params = np.array(
+        [-16, -8, -4, -2, -1, 1, 2, 4, 8, 16]
+    )
+    # Perturbations to apply to root values.
+    perturbations = 0.1 * random_state.random_sample(
+        size=(3, len(root_params))
+    )
+
+    params = []
+    # Parameter group 1
+    # -----------------
+    # No integer differences. This has been confirmed for the above seed.
+    A = root_params + perturbations[0, :]
+    B = root_params + perturbations[1, :]
+    C = root_params + perturbations[2, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 1) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 2
+    # -----------------
+    # B - A an integer
+    A = root_params + 0.5
+    B = root_params + 0.5
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 2) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 3
+    # -----------------
+    # C - A an integer
+    A = root_params + 0.5
+    B = root_params + perturbations[1, :]
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 3) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 4
+    # -----------------
+    # C - B an integer
+    A = root_params + perturbations[0, :]
+    B = root_params + 0.5
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 4) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 5
+    # -----------------
+    # C - A - B an integer
+    A = root_params + 0.25
+    B = root_params + 0.25
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 5) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 6
+    # -----------------
+    # A an integer
+    A = root_params
+    B = root_params + perturbations[0, :]
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 6) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 7
+    # -----------------
+    # B an integer
+    A = root_params + perturbations[0, :]
+    B = root_params
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 7) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 8
+    # -----------------
+    # C an integer
+    A = root_params + perturbations[0, :]
+    B = root_params + perturbations[1, :]
+    C = root_params
+    params.extend(
+        sorted(
+            ((a, b, c, 8) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 9
+    # -----------------
+    # Wide range of magnitudes, c - a - b > 0.
+    phi = (1 + np.sqrt(5))/2
+    P = phi**np.arange(16)
+    P = np.hstack([-P, P])
+    group_9_params = sorted(
+        (
+            (a, b, c, 9) for a, b, c in product(P, P, P) if c - a - b > 0
+        ),
+        key=lambda x: max(abs(x[0]), abs(x[1])),
+    )
+
+    if parameter_groups is not None:
+        # Group 9 params only used if specified in arguments.
+        params.extend(group_9_params)
+        params = [
+            (a, b, c, group) for a, b, c, group in params
+            if group in parameter_groups
+        ]
+
+    # grid_size * grid_size grid in box with corners
+    # -2 - 2j, -2 + 2j, 2 - 2j, 2 + 2j
+    X, Y = np.meshgrid(
+        np.linspace(-box_size, box_size, grid_size),
+        np.linspace(-box_size, box_size, grid_size)
+    )
+    Z = X + Y * 1j
+    Z = Z.flatten().tolist()
+    # Add z = 1 + 0j (region 0).
+    Z.append(1 + 0j)
+    if regions is not None:
+        Z = [z for z in Z if get_region(z) in regions]
+
+    # Evaluate scipy and mpmath's hyp2f1 for all parameter combinations
+    # above against all arguments in the grid Z
+    rows = get_results(params, Z, n_jobs=n_jobs, compute_mp=compute_mp)
+
+    with open(outpath, "w", newline="") as f:
+        writer = csv.writer(f, delimiter="\t")
+        writer.writerow(
+            [
+                "a",
+                "b",
+                "c",
+                "z",
+                "|z|",
+                "region",
+                "parameter_group",
+                "expected",  # mpmath's hyp2f1
+                "observed",  # scipy's hyp2f1
+                "relative_error",
+                "absolute_error",
+            ]
+        )
+        for row in rows:
+            writer.writerow(row)
+
+
+if __name__ == "__main__":
+    parser = argparse.ArgumentParser(
+        description="Test scipy's hyp2f1 against mpmath's on a grid in the"
+        " complex plane over a grid of parameter values. Saves output to file"
+        " specified in positional argument \"outpath\"."
+        " Caution: With default arguments, the generated output file is"
+        " roughly 700MB in size. Script may take several hours to finish if"
+        " \"--n_jobs\" is set to 1."
+    )
+    parser.add_argument(
+        "outpath", type=str, help="Path to output tsv file."
+    )
+    parser.add_argument(
+        "--n_jobs",
+        type=int,
+        default=1,
+        help="Number of jobs for multiprocessing.",
+    )
+    parser.add_argument(
+        "--box_size",
+        type=float,
+        default=2.0,
+        help="hyp2f1 is evaluated in box of side_length 2*box_size centered"
+        " at the origin."
+    )
+    parser.add_argument(
+        "--grid_size",
+        type=int,
+        default=20,
+        help="hyp2f1 is evaluated on grid_size * grid_size grid in box of side"
+        " length 2*box_size centered at the origin."
+    )
+    parser.add_argument(
+        "--parameter_groups",
+        type=int,
+        nargs='+',
+        default=None,
+        help="Restrict to supplied parameter groups. See the Docstring for"
+        " this module for more info on parameter groups. Calculate for all"
+        " parameter groups by default."
+    )
+    parser.add_argument(
+        "--regions",
+        type=int,
+        nargs='+',
+        default=None,
+        help="Restrict to argument z only within the supplied regions. See"
+        " the Docstring for this module for more info on regions. Calculate"
+        " for all regions by default."
+    )
+    parser.add_argument(
+        "--no_mp",
+        action='store_true',
+        help="If this flag is set, do not compute results with mpmath. Saves"
+        " time if results have already been computed elsewhere. Fills in"
+        " \"expected\" column with None values."
+    )
+    args = parser.parse_args()
+    compute_mp = not args.no_mp
+    print(args.parameter_groups)
+    main(
+        args.outpath,
+        n_jobs=args.n_jobs,
+        box_size=args.box_size,
+        grid_size=args.grid_size,
+        parameter_groups=args.parameter_groups,
+        regions=args.regions,
+        compute_mp=compute_mp,
+    )
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fdbf35b2cf85f1f7a6e73579546ed5cfe508fa6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py
@@ -0,0 +1,68 @@
+"""Compute a Pade approximation for the principal branch of the
+Lambert W function around 0 and compare it to various other
+approximations.
+
+"""
+import numpy as np
+
+try:
+    import mpmath
+    import matplotlib.pyplot as plt
+except ImportError:
+    pass
+
+
+def lambertw_pade():
+    derivs = [mpmath.diff(mpmath.lambertw, 0, n=n) for n in range(6)]
+    p, q = mpmath.pade(derivs, 3, 2)
+    return p, q
+
+
+def main():
+    print(__doc__)
+    with mpmath.workdps(50):
+        p, q = lambertw_pade()
+        p, q = p[::-1], q[::-1]
+        print(f"p = {p}")
+        print(f"q = {q}")
+
+    x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75)
+    x, y = np.meshgrid(x, y)
+    z = x + 1j*y
+    lambertw_std = []
+    for z0 in z.flatten():
+        lambertw_std.append(complex(mpmath.lambertw(z0)))
+    lambertw_std = np.array(lambertw_std).reshape(x.shape)
+
+    fig, axes = plt.subplots(nrows=3, ncols=1)
+    # Compare Pade approximation to true result
+    p = np.array([float(p0) for p0 in p])
+    q = np.array([float(q0) for q0 in q])
+    pade_approx = np.polyval(p, z)/np.polyval(q, z)
+    pade_err = abs(pade_approx - lambertw_std)
+    axes[0].pcolormesh(x, y, pade_err)
+    # Compare two terms of asymptotic series to true result
+    asy_approx = np.log(z) - np.log(np.log(z))
+    asy_err = abs(asy_approx - lambertw_std)
+    axes[1].pcolormesh(x, y, asy_err)
+    # Compare two terms of the series around the branch point to the
+    # true result
+    p = np.sqrt(2*(np.exp(1)*z + 1))
+    series_approx = -1 + p - p**2/3
+    series_err = abs(series_approx - lambertw_std)
+    im = axes[2].pcolormesh(x, y, series_err)
+
+    fig.colorbar(im, ax=axes.ravel().tolist())
+    plt.show()
+
+    fig, ax = plt.subplots(nrows=1, ncols=1)
+    pade_better = pade_err < asy_err
+    im = ax.pcolormesh(x, y, pade_better)
+    t = np.linspace(-0.3, 0.3)
+    ax.plot(-2.5*abs(t) - 0.2, t, 'r')
+    fig.colorbar(im, ax=ax)
+    plt.show()
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..74051ac7b46c70dc01919a362d05a8bbbe11333a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py
@@ -0,0 +1,43 @@
+"""Precompute series coefficients for log-Gamma."""
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def stirling_series(N):
+    with mpmath.workdps(100):
+        coeffs = [mpmath.bernoulli(2*n)/(2*n*(2*n - 1))
+                  for n in range(1, N + 1)]
+    return coeffs
+
+
+def taylor_series_at_1(N):
+    coeffs = []
+    with mpmath.workdps(100):
+        coeffs.append(-mpmath.euler)
+        for n in range(2, N + 1):
+            coeffs.append((-1)**n*mpmath.zeta(n)/n)
+    return coeffs
+
+
+def main():
+    print(__doc__)
+    print()
+    stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+                       for x in stirling_series(8)[::-1]]
+    taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+                     for x in taylor_series_at_1(23)[::-1]]
+    print("Stirling series coefficients")
+    print("----------------------------")
+    print("\n".join(stirling_coeffs))
+    print()
+    print("Taylor series coefficients")
+    print("--------------------------")
+    print("\n".join(taylor_coeffs))
+    print()
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbf6009368540dbf603b61f5b72510f0acd1a65b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py
@@ -0,0 +1,131 @@
+"""
+Convergence regions of the expansions used in ``struve.c``
+
+Note that for v >> z both functions tend rapidly to 0,
+and for v << -z, they tend to infinity.
+
+The floating-point functions over/underflow in the lower left and right
+corners of the figure.
+
+
+Figure legend
+=============
+
+Red region
+    Power series is close (1e-12) to the mpmath result
+
+Blue region
+    Asymptotic series is close to the mpmath result
+
+Green region
+    Bessel series is close to the mpmath result
+
+Dotted colored lines
+    Boundaries of the regions
+
+Solid colored lines
+    Boundaries estimated by the routine itself. These will be used
+    for determining which of the results to use.
+
+Black dashed line
+    The line z = 0.7*|v| + 12
+
+"""
+import numpy as np
+import matplotlib.pyplot as plt
+
+import mpmath
+
+
+def err_metric(a, b, atol=1e-290):
+    m = abs(a - b) / (atol + abs(b))
+    m[np.isinf(b) & (a == b)] = 0
+    return m
+
+
+def do_plot(is_h=True):
+    from scipy.special._ufuncs import (_struve_power_series,
+                                       _struve_asymp_large_z,
+                                       _struve_bessel_series)
+
+    vs = np.linspace(-1000, 1000, 91)
+    zs = np.sort(np.r_[1e-5, 1.0, np.linspace(0, 700, 91)[1:]])
+
+    rp = _struve_power_series(vs[:,None], zs[None,:], is_h)
+    ra = _struve_asymp_large_z(vs[:,None], zs[None,:], is_h)
+    rb = _struve_bessel_series(vs[:,None], zs[None,:], is_h)
+
+    mpmath.mp.dps = 50
+    if is_h:
+        def sh(v, z):
+            return float(mpmath.struveh(mpmath.mpf(v), mpmath.mpf(z)))
+    else:
+        def sh(v, z):
+            return float(mpmath.struvel(mpmath.mpf(v), mpmath.mpf(z)))
+    ex = np.vectorize(sh, otypes='d')(vs[:,None], zs[None,:])
+
+    err_a = err_metric(ra[0], ex) + 1e-300
+    err_p = err_metric(rp[0], ex) + 1e-300
+    err_b = err_metric(rb[0], ex) + 1e-300
+
+    err_est_a = abs(ra[1]/ra[0])
+    err_est_p = abs(rp[1]/rp[0])
+    err_est_b = abs(rb[1]/rb[0])
+
+    z_cutoff = 0.7*abs(vs) + 12
+
+    levels = [-1000, -12]
+
+    plt.cla()
+
+    plt.hold(1)
+    plt.contourf(vs, zs, np.log10(err_p).T,
+                 levels=levels, colors=['r', 'r'], alpha=0.1)
+    plt.contourf(vs, zs, np.log10(err_a).T,
+                 levels=levels, colors=['b', 'b'], alpha=0.1)
+    plt.contourf(vs, zs, np.log10(err_b).T,
+                 levels=levels, colors=['g', 'g'], alpha=0.1)
+
+    plt.contour(vs, zs, np.log10(err_p).T,
+                levels=levels, colors=['r', 'r'], linestyles=[':', ':'])
+    plt.contour(vs, zs, np.log10(err_a).T,
+                levels=levels, colors=['b', 'b'], linestyles=[':', ':'])
+    plt.contour(vs, zs, np.log10(err_b).T,
+                levels=levels, colors=['g', 'g'], linestyles=[':', ':'])
+
+    lp = plt.contour(vs, zs, np.log10(err_est_p).T,
+                     levels=levels, colors=['r', 'r'], linestyles=['-', '-'])
+    la = plt.contour(vs, zs, np.log10(err_est_a).T,
+                     levels=levels, colors=['b', 'b'], linestyles=['-', '-'])
+    lb = plt.contour(vs, zs, np.log10(err_est_b).T,
+                     levels=levels, colors=['g', 'g'], linestyles=['-', '-'])
+
+    plt.clabel(lp, fmt={-1000: 'P', -12: 'P'})
+    plt.clabel(la, fmt={-1000: 'A', -12: 'A'})
+    plt.clabel(lb, fmt={-1000: 'B', -12: 'B'})
+
+    plt.plot(vs, z_cutoff, 'k--')
+
+    plt.xlim(vs.min(), vs.max())
+    plt.ylim(zs.min(), zs.max())
+
+    plt.xlabel('v')
+    plt.ylabel('z')
+
+
+def main():
+    plt.clf()
+    plt.subplot(121)
+    do_plot(True)
+    plt.title('Struve H')
+
+    plt.subplot(122)
+    do_plot(False)
+    plt.title('Struve L')
+
+    plt.savefig('struve_convergence.png')
+    plt.show()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..55cf4083ed5e5a6628fd3316c02ce1a5ce21a92c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py
@@ -0,0 +1,38 @@
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+try:
+    from sympy.abc import x
+except ImportError:
+    pass
+
+
+def lagrange_inversion(a):
+    """Given a series
+
+    f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
+
+    use the Lagrange inversion formula to compute a series
+
+    g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
+
+    so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
+    necessarily b[0] = 0 too.
+
+    The algorithm is naive and could be improved, but speed isn't an
+    issue here and it's easy to read.
+
+    """
+    n = len(a)
+    f = sum(a[i]*x**i for i in range(n))
+    h = (x/f).series(x, 0, n).removeO()
+    hpower = [h**0]
+    for k in range(n):
+        hpower.append((hpower[-1]*h).expand())
+    b = [mp.mpf(0)]
+    for k in range(1, n):
+        b.append(hpower[k].coeff(x, k - 1)/k)
+    b = [mp.mpf(x) for x in b]
+    return b
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..51d56b1cd5c47c7ef005d21aad9827a1e85ec0d9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py
@@ -0,0 +1,342 @@
+"""Precompute coefficients of several series expansions
+of Wright's generalized Bessel function Phi(a, b, x).
+
+See https://dlmf.nist.gov/10.46.E1 with rho=a, beta=b, z=x.
+"""
+from argparse import ArgumentParser, RawTextHelpFormatter
+import numpy as np
+from scipy.integrate import quad
+from scipy.optimize import minimize_scalar, curve_fit
+from time import time
+
+try:
+    import sympy
+    from sympy import EulerGamma, Rational, S, Sum, \
+        factorial, gamma, gammasimp, pi, polygamma, symbols, zeta
+    from sympy.polys.polyfuncs import horner
+except ImportError:
+    pass
+
+
+def series_small_a():
+    """Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.
+    """
+    order = 5
+    a, b, x, k = symbols("a b x k")
+    A = []  # terms with a
+    X = []  # terms with x
+    B = []  # terms with b (polygammas)
+    # Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i])
+    expression = Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity))
+    expression = gamma(b)/sympy.exp(x) * expression
+
+    # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0)
+    for n in range(0, order+1):
+        term = expression.diff(a, n).subs(a, 0).simplify().doit()
+        # set the whole bracket involving polygammas to 1
+        x_part = (term.subs(polygamma(0, b), 1)
+                  .replace(polygamma, lambda *args: 0))
+        # sign convention: x part always positive
+        x_part *= (-1)**n
+
+        A.append(a**n/factorial(n))
+        X.append(horner(x_part))
+        B.append(horner((term/x_part).simplify()))
+
+    s = "Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.\n"
+    s += "Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)\n"
+    for name, c in zip(['A', 'X', 'B'], [A, X, B]):
+        for i in range(len(c)):
+            s += f"\n{name}[{i}] = " + str(c[i])
+    return s
+
+
+# expansion of digamma
+def dg_series(z, n):
+    """Symbolic expansion of digamma(z) in z=0 to order n.
+
+    See https://dlmf.nist.gov/5.7.E4 and with https://dlmf.nist.gov/5.5.E2
+    """
+    k = symbols("k")
+    return -1/z - EulerGamma + \
+        sympy.summation((-1)**k * zeta(k) * z**(k-1), (k, 2, n+1))
+
+
+def pg_series(k, z, n):
+    """Symbolic expansion of polygamma(k, z) in z=0 to order n."""
+    return sympy.diff(dg_series(z, n+k), z, k)
+
+
+def series_small_a_small_b():
+    """Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5.
+
+    Be aware of cancellation of poles in b=0 of digamma(b)/Gamma(b) and
+    polygamma functions.
+
+    digamma(b)/Gamma(b) = -1 - 2*M_EG*b + O(b^2)
+    digamma(b)^2/Gamma(b) = 1/b + 3*M_EG + b*(-5/12*PI^2+7/2*M_EG^2) + O(b^2)
+    polygamma(1, b)/Gamma(b) = 1/b + M_EG + b*(1/12*PI^2 + 1/2*M_EG^2) + O(b^2)
+    and so on.
+    """
+    order = 5
+    a, b, x, k = symbols("a b x k")
+    M_PI, M_EG, M_Z3 = symbols("M_PI M_EG M_Z3")
+    c_subs = {pi: M_PI, EulerGamma: M_EG, zeta(3): M_Z3}
+    A = []  # terms with a
+    X = []  # terms with x
+    B = []  # terms with b (polygammas expanded)
+    C = []  # terms that generate B
+    # Phi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i])
+    # B[0] = 1
+    # B[k] = sum(C[k] * b**k/k!, k=0..)
+    # Note: C[k] can be obtained from a series expansion of 1/gamma(b).
+    expression = gamma(b)/sympy.exp(x) * \
+        Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity))
+
+    # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0)
+    for n in range(0, order+1):
+        term = expression.diff(a, n).subs(a, 0).simplify().doit()
+        # set the whole bracket involving polygammas to 1
+        x_part = (term.subs(polygamma(0, b), 1)
+                  .replace(polygamma, lambda *args: 0))
+        # sign convention: x part always positive
+        x_part *= (-1)**n
+        # expansion of polygamma part with 1/gamma(b)
+        pg_part = term/x_part/gamma(b)
+        if n >= 1:
+            # Note: highest term is digamma^n
+            pg_part = pg_part.replace(polygamma,
+                                      lambda k, x: pg_series(k, x, order+1+n))
+            pg_part = (pg_part.series(b, 0, n=order+1-n)
+                       .removeO()
+                       .subs(polygamma(2, 1), -2*zeta(3))
+                       .simplify()
+                       )
+
+        A.append(a**n/factorial(n))
+        X.append(horner(x_part))
+        B.append(pg_part)
+
+    # Calculate C and put in the k!
+    C = sympy.Poly(B[1].subs(c_subs), b).coeffs()
+    C.reverse()
+    for i in range(len(C)):
+        C[i] = (C[i] * factorial(i)).simplify()
+
+    s = "Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5."
+    s += "\nPhi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i], i=0..5)\n"
+    s += "B[0] = 1\n"
+    s += "B[i] = sum(C[k+i-1] * b**k/k!, k=0..)\n"
+    s += "\nM_PI = pi"
+    s += "\nM_EG = EulerGamma"
+    s += "\nM_Z3 = zeta(3)"
+    for name, c in zip(['A', 'X'], [A, X]):
+        for i in range(len(c)):
+            s += f"\n{name}[{i}] = "
+            s += str(c[i])
+    # For C, do also compute the values numerically
+    for i in range(len(C)):
+        s += f"\n# C[{i}] = "
+        s += str(C[i])
+        s += f"\nC[{i}] = "
+        s += str(C[i].subs({M_EG: EulerGamma, M_PI: pi, M_Z3: zeta(3)})
+                 .evalf(17))
+
+    # Does B have the assumed structure?
+    s += "\n\nTest if B[i] does have the assumed structure."
+    s += "\nC[i] are derived from B[1] alone."
+    s += "\nTest B[2] == C[1] + b*C[2] + b^2/2*C[3] + b^3/6*C[4] + .."
+    test = sum([b**k/factorial(k) * C[k+1] for k in range(order-1)])
+    test = (test - B[2].subs(c_subs)).simplify()
+    s += f"\ntest successful = {test==S(0)}"
+    s += "\nTest B[3] == C[2] + b*C[3] + b^2/2*C[4] + .."
+    test = sum([b**k/factorial(k) * C[k+2] for k in range(order-2)])
+    test = (test - B[3].subs(c_subs)).simplify()
+    s += f"\ntest successful = {test==S(0)}"
+    return s
+
+
+def asymptotic_series():
+    """Asymptotic expansion for large x.
+
+    Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k
+    Z = (a*x)^(1/(1+a))
+
+    Wright (1935) lists the coefficients C_0 and C_1 (he calls them a_0 and
+    a_1). With slightly different notation, Paris (2017) lists coefficients
+    c_k up to order k=3.
+    Paris (2017) uses ZP = (1+a)/a * Z  (ZP = Z of Paris) and
+    C_k = C_0 * (-a/(1+a))^k * c_k
+    """
+    order = 8
+
+    class g(sympy.Function):
+        """Helper function g according to Wright (1935)
+
+        g(n, rho, v) = (1 + (rho+2)/3 * v + (rho+2)*(rho+3)/(2*3) * v^2 + ...)
+
+        Note: Wright (1935) uses square root of above definition.
+        """
+        nargs = 3
+
+        @classmethod
+        def eval(cls, n, rho, v):
+            if not n >= 0:
+                raise ValueError("must have n >= 0")
+            elif n == 0:
+                return 1
+            else:
+                return g(n-1, rho, v) \
+                    + gammasimp(gamma(rho+2+n)/gamma(rho+2)) \
+                    / gammasimp(gamma(3+n)/gamma(3))*v**n
+
+    class coef_C(sympy.Function):
+        """Calculate coefficients C_m for integer m.
+
+        C_m is the coefficient of v^(2*m) in the Taylor expansion in v=0 of
+        Gamma(m+1/2)/(2*pi) * (2/(rho+1))^(m+1/2) * (1-v)^(-b)
+            * g(rho, v)^(-m-1/2)
+        """
+        nargs = 3
+
+        @classmethod
+        def eval(cls, m, rho, beta):
+            if not m >= 0:
+                raise ValueError("must have m >= 0")
+
+            v = symbols("v")
+            expression = (1-v)**(-beta) * g(2*m, rho, v)**(-m-Rational(1, 2))
+            res = expression.diff(v, 2*m).subs(v, 0) / factorial(2*m)
+            res = res * (gamma(m + Rational(1, 2)) / (2*pi)
+                         * (2/(rho+1))**(m + Rational(1, 2)))
+            return res
+
+    # in order to have nice ordering/sorting of expressions, we set a = xa.
+    xa, b, xap1 = symbols("xa b xap1")
+    C0 = coef_C(0, xa, b)
+    # a1 = a(1, rho, beta)
+    s = "Asymptotic expansion for large x\n"
+    s += "Phi(a, b, x) = Z**(1/2-b) * exp((1+a)/a * Z) \n"
+    s += "               * sum((-1)**k * C[k]/Z**k, k=0..6)\n\n"
+    s += "Z      = pow(a * x, 1/(1+a))\n"
+    s += "A[k]   = pow(a, k)\n"
+    s += "B[k]   = pow(b, k)\n"
+    s += "Ap1[k] = pow(1+a, k)\n\n"
+    s += "C[0] = 1./sqrt(2. * M_PI * Ap1[1])\n"
+    for i in range(1, order+1):
+        expr = (coef_C(i, xa, b) / (C0/(1+xa)**i)).simplify()
+        factor = [x.denominator() for x in sympy.Poly(expr).coeffs()]
+        factor = sympy.lcm(factor)
+        expr = (expr * factor).simplify().collect(b, sympy.factor)
+        expr = expr.xreplace({xa+1: xap1})
+        s += f"C[{i}] = C[0] / ({factor} * Ap1[{i}])\n"
+        s += f"C[{i}] *= {str(expr)}\n\n"
+    import re
+    re_a = re.compile(r'xa\*\*(\d+)')
+    s = re_a.sub(r'A[\1]', s)
+    re_b = re.compile(r'b\*\*(\d+)')
+    s = re_b.sub(r'B[\1]', s)
+    s = s.replace('xap1', 'Ap1[1]')
+    s = s.replace('xa', 'a')
+    # max integer = 2^31-1 = 2,147,483,647. Solution: Put a point after 10
+    # or more digits.
+    re_digits = re.compile(r'(\d{10,})')
+    s = re_digits.sub(r'\1.', s)
+    return s
+
+
+def optimal_epsilon_integral():
+    """Fit optimal choice of epsilon for integral representation.
+
+    The integrand of
+        int_0^pi P(eps, a, b, x, phi) * dphi
+    can exhibit oscillatory behaviour. It stems from the cosine of P and can be
+    minimized by minimizing the arc length of the argument
+        f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a * phi) + (1 - b) * phi
+    of cos(f(phi)).
+    We minimize the arc length in eps for a grid of values (a, b, x) and fit a
+    parametric function to it.
+    """
+    def fp(eps, a, b, x, phi):
+        """Derivative of f w.r.t. phi."""
+        eps_a = np.power(1. * eps, -a)
+        return eps * np.cos(phi) - a * x * eps_a * np.cos(a * phi) + 1 - b
+
+    def arclength(eps, a, b, x, epsrel=1e-2, limit=100):
+        """Compute Arc length of f.
+
+        Note that the arc length of a function f from t0 to t1 is given by
+            int_t0^t1 sqrt(1 + f'(t)^2) dt
+        """
+        return quad(lambda phi: np.sqrt(1 + fp(eps, a, b, x, phi)**2),
+                    0, np.pi,
+                    epsrel=epsrel, limit=100)[0]
+
+    # grid of minimal arc length values
+    data_a = [1e-3, 0.1, 0.5, 0.9, 1, 2, 4, 5, 6, 8]
+    data_b = [0, 1, 4, 7, 10]
+    data_x = [1, 1.5, 2, 4, 10, 20, 50, 100, 200, 500, 1e3, 5e3, 1e4]
+    data_a, data_b, data_x = np.meshgrid(data_a, data_b, data_x)
+    data_a, data_b, data_x = (data_a.flatten(), data_b.flatten(),
+                              data_x.flatten())
+    best_eps = []
+    for i in range(data_x.size):
+        best_eps.append(
+            minimize_scalar(lambda eps: arclength(eps, data_a[i], data_b[i],
+                                                  data_x[i]),
+                            bounds=(1e-3, 1000),
+                            method='Bounded', options={'xatol': 1e-3}).x
+        )
+    best_eps = np.array(best_eps)
+    # pandas would be nice, but here a dictionary is enough
+    df = {'a': data_a,
+          'b': data_b,
+          'x': data_x,
+          'eps': best_eps,
+          }
+
+    def func(data, A0, A1, A2, A3, A4, A5):
+        """Compute parametric function to fit."""
+        a = data['a']
+        b = data['b']
+        x = data['x']
+        return (A0 * b * np.exp(-0.5 * a)
+                + np.exp(A1 + 1 / (1 + a) * np.log(x) - A2 * np.exp(-A3 * a)
+                         + A4 / (1 + np.exp(A5 * a))))
+
+    func_params = list(curve_fit(func, df, df['eps'], method='trf')[0])
+
+    s = "Fit optimal eps for integrand P via minimal arc length\n"
+    s += "with parametric function:\n"
+    s += "optimal_eps = (A0 * b * exp(-a/2) + exp(A1 + 1 / (1 + a) * log(x)\n"
+    s += "              - A2 * exp(-A3 * a) + A4 / (1 + exp(A5 * a)))\n\n"
+    s += "Fitted parameters A0 to A5 are:\n"
+    s += ', '.join([f'{x:.5g}' for x in func_params])
+    return s
+
+
+def main():
+    t0 = time()
+    parser = ArgumentParser(description=__doc__,
+                            formatter_class=RawTextHelpFormatter)
+    parser.add_argument('action', type=int, choices=[1, 2, 3, 4],
+                        help='chose what expansion to precompute\n'
+                             '1 : Series for small a\n'
+                             '2 : Series for small a and small b\n'
+                             '3 : Asymptotic series for large x\n'
+                             '    This may take some time (>4h).\n'
+                             '4 : Fit optimal eps for integral representation.'
+                        )
+    args = parser.parse_args()
+
+    switch = {1: lambda: print(series_small_a()),
+              2: lambda: print(series_small_a_small_b()),
+              3: lambda: print(asymptotic_series()),
+              4: lambda: print(optimal_epsilon_integral())
+              }
+    switch.get(args.action, lambda: print("Invalid input."))()
+    print(f"\n{(time() - t0)/60:.1f} minutes elapsed.\n")
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..1de9b4fe552ca9178c452194ab84af6ca5daac71
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py
@@ -0,0 +1,152 @@
+"""Compute a grid of values for Wright's generalized Bessel function
+and save the values to data files for use in tests. Using mpmath directly in
+tests would take too long.
+
+This takes about 10 minutes to run on a 2.7 GHz i7 Macbook Pro.
+"""
+from functools import lru_cache
+import os
+from time import time
+
+import numpy as np
+from scipy.special._mptestutils import mpf2float
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+# exp_inf: smallest value x for which exp(x) == inf
+exp_inf = 709.78271289338403
+
+
+# 64 Byte per value
+@lru_cache(maxsize=100_000)
+def rgamma_cached(x, dps):
+    with mp.workdps(dps):
+        return mp.rgamma(x)
+
+
+def mp_wright_bessel(a, b, x, dps=50, maxterms=2000):
+    """Compute Wright's generalized Bessel function as Series with mpmath.
+    """
+    with mp.workdps(dps):
+        a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x)
+        res = mp.nsum(lambda k: x**k / mp.fac(k)
+                      * rgamma_cached(a * k + b, dps=dps),
+                      [0, mp.inf],
+                      tol=dps, method='s', steps=[maxterms]
+                      )
+        return mpf2float(res)
+
+
+def main():
+    t0 = time()
+    print(__doc__)
+    pwd = os.path.dirname(__file__)
+    eps = np.finfo(float).eps * 100
+
+    a_range = np.array([eps,
+                        1e-4 * (1 - eps), 1e-4, 1e-4 * (1 + eps),
+                        1e-3 * (1 - eps), 1e-3, 1e-3 * (1 + eps),
+                        0.1, 0.5,
+                        1 * (1 - eps), 1, 1 * (1 + eps),
+                        1.5, 2, 4.999, 5, 10])
+    b_range = np.array([0, eps, 1e-10, 1e-5, 0.1, 1, 2, 10, 20, 100])
+    x_range = np.array([0, eps, 1 - eps, 1, 1 + eps,
+                        1.5,
+                        2 - eps, 2, 2 + eps,
+                        9 - eps, 9, 9 + eps,
+                        10 * (1 - eps), 10, 10 * (1 + eps),
+                        100 * (1 - eps), 100, 100 * (1 + eps),
+                        500, exp_inf, 1e3, 1e5, 1e10, 1e20])
+
+    a_range, b_range, x_range = np.meshgrid(a_range, b_range, x_range,
+                                            indexing='ij')
+    a_range = a_range.flatten()
+    b_range = b_range.flatten()
+    x_range = x_range.flatten()
+
+    # filter out some values, especially too large x
+    bool_filter = ~((a_range < 5e-3) & (x_range >= exp_inf))
+    bool_filter = bool_filter & ~((a_range < 0.2) & (x_range > exp_inf))
+    bool_filter = bool_filter & ~((a_range < 0.5) & (x_range > 1e3))
+    bool_filter = bool_filter & ~((a_range < 0.56) & (x_range > 5e3))
+    bool_filter = bool_filter & ~((a_range < 1) & (x_range > 1e4))
+    bool_filter = bool_filter & ~((a_range < 1.4) & (x_range > 1e5))
+    bool_filter = bool_filter & ~((a_range < 1.8) & (x_range > 1e6))
+    bool_filter = bool_filter & ~((a_range < 2.2) & (x_range > 1e7))
+    bool_filter = bool_filter & ~((a_range < 2.5) & (x_range > 1e8))
+    bool_filter = bool_filter & ~((a_range < 2.9) & (x_range > 1e9))
+    bool_filter = bool_filter & ~((a_range < 3.3) & (x_range > 1e10))
+    bool_filter = bool_filter & ~((a_range < 3.7) & (x_range > 1e11))
+    bool_filter = bool_filter & ~((a_range < 4) & (x_range > 1e12))
+    bool_filter = bool_filter & ~((a_range < 4.4) & (x_range > 1e13))
+    bool_filter = bool_filter & ~((a_range < 4.7) & (x_range > 1e14))
+    bool_filter = bool_filter & ~((a_range < 5.1) & (x_range > 1e15))
+    bool_filter = bool_filter & ~((a_range < 5.4) & (x_range > 1e16))
+    bool_filter = bool_filter & ~((a_range < 5.8) & (x_range > 1e17))
+    bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18))
+    bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18))
+    bool_filter = bool_filter & ~((a_range < 6.5) & (x_range > 1e19))
+    bool_filter = bool_filter & ~((a_range < 6.9) & (x_range > 1e20))
+
+    # filter out known values that do not meet the required numerical accuracy
+    # see test test_wright_data_grid_failures
+    failing = np.array([
+        [0.1, 100, 709.7827128933841],
+        [0.5, 10, 709.7827128933841],
+        [0.5, 10, 1000],
+        [0.5, 100, 1000],
+        [1, 20, 100000],
+        [1, 100, 100000],
+        [1.0000000000000222, 20, 100000],
+        [1.0000000000000222, 100, 100000],
+        [1.5, 0, 500],
+        [1.5, 2.220446049250313e-14, 500],
+        [1.5, 1.e-10, 500],
+        [1.5, 1.e-05, 500],
+        [1.5, 0.1, 500],
+        [1.5, 20, 100000],
+        [1.5, 100, 100000],
+        ]).tolist()
+
+    does_fail = np.full_like(a_range, False, dtype=bool)
+    for i in range(x_range.size):
+        if [a_range[i], b_range[i], x_range[i]] in failing:
+            does_fail[i] = True
+
+    # filter and flatten
+    a_range = a_range[bool_filter]
+    b_range = b_range[bool_filter]
+    x_range = x_range[bool_filter]
+    does_fail = does_fail[bool_filter]
+
+    dataset = []
+    print(f"Computing {x_range.size} single points.")
+    print("Tests will fail for the following data points:")
+    for i in range(x_range.size):
+        a = a_range[i]
+        b = b_range[i]
+        x = x_range[i]
+        # take care of difficult corner cases
+        maxterms = 1000
+        if a < 1e-6 and x >= exp_inf/10:
+            maxterms = 2000
+        f = mp_wright_bessel(a, b, x, maxterms=maxterms)
+        if does_fail[i]:
+            print("failing data point a, b, x, value = "
+                  f"[{a}, {b}, {x}, {f}]")
+        else:
+            dataset.append((a, b, x, f))
+    dataset = np.array(dataset)
+
+    filename = os.path.join(pwd, '..', 'tests', 'data', 'local',
+                            'wright_bessel.txt')
+    np.savetxt(filename, dataset)
+
+    print(f"{(time() - t0)/60:.1f} minutes elapsed")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bcd0345a9c1b90c45b0e9e3340ab4da4ec5c6d7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py
@@ -0,0 +1,41 @@
+import numpy as np
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def mpmath_wrightomega(x):
+    return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
+
+
+def wrightomega_series_error(x):
+    series = x
+    desired = mpmath_wrightomega(x)
+    return abs(series - desired) / desired
+
+
+def wrightomega_exp_error(x):
+    exponential_approx = mpmath.exp(x)
+    desired = mpmath_wrightomega(x)
+    return abs(exponential_approx - desired) / desired
+
+
+def main():
+    desired_error = 2 * np.finfo(float).eps
+    print('Series Error')
+    for x in [1e5, 1e10, 1e15, 1e20]:
+        with mpmath.workdps(100):
+            error = wrightomega_series_error(x)
+        print(x, error, error < desired_error)
+
+    print('Exp error')
+    for x in [-10, -25, -50, -100, -200, -400, -700, -740]:
+        with mpmath.workdps(100):
+            error = wrightomega_exp_error(x)
+        print(x, error, error < desired_error)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py
new file mode 100644
index 0000000000000000000000000000000000000000..d408b1a2fffb6872287452923fcc9394adc13a7c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py
@@ -0,0 +1,27 @@
+"""Compute the Taylor series for zeta(x) - 1 around x = 0."""
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def zetac_series(N):
+    coeffs = []
+    with mpmath.workdps(100):
+        coeffs.append(-1.5)
+        for n in range(1, N):
+            coeff = mpmath.diff(mpmath.zeta, 0, n)/mpmath.factorial(n)
+            coeffs.append(coeff)
+    return coeffs
+
+
+def main():
+    print(__doc__)
+    coeffs = zetac_series(10)
+    coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+              for x in coeffs]
+    print("\n".join(coeffs[::-1]))
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1edc9800759dfda9e49bde1becc775a64bce958
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py
@@ -0,0 +1,15 @@
+"""Warnings and Exceptions that can be raised by special functions."""
+import warnings
+
+
+class SpecialFunctionWarning(Warning):
+    """Warning that can be emitted by special functions."""
+    pass
+
+
+warnings.simplefilter("always", category=SpecialFunctionWarning)
+
+
+class SpecialFunctionError(Exception):
+    """Exception that can be raised by special functions."""
+    pass
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..2525eceb47ec2b20b45ca693e19e741f4a666597
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py
@@ -0,0 +1,106 @@
+# Last Change: Sat Mar 21 02:00 PM 2009 J
+
+# Copyright (c) 2001, 2002 Enthought, Inc.
+#
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#   a. Redistributions of source code must retain the above copyright notice,
+#      this list of conditions and the following disclaimer.
+#   b. Redistributions in binary form must reproduce the above copyright
+#      notice, this list of conditions and the following disclaimer in the
+#      documentation and/or other materials provided with the distribution.
+#   c. Neither the name of the Enthought 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 REGENTS 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.
+
+"""Some more special functions which may be useful for multivariate statistical
+analysis."""
+
+import numpy as np
+from scipy.special import gammaln as loggam
+
+
+__all__ = ['multigammaln']
+
+
+def multigammaln(a, d):
+    r"""Returns the log of multivariate gamma, also sometimes called the
+    generalized gamma.
+
+    Parameters
+    ----------
+    a : ndarray
+        The multivariate gamma is computed for each item of `a`.
+    d : int
+        The dimension of the space of integration.
+
+    Returns
+    -------
+    res : ndarray
+        The values of the log multivariate gamma at the given points `a`.
+
+    Notes
+    -----
+    The formal definition of the multivariate gamma of dimension d for a real
+    `a` is
+
+    .. math::
+
+        \Gamma_d(a) = \int_{A>0} e^{-tr(A)} |A|^{a - (d+1)/2} dA
+
+    with the condition :math:`a > (d-1)/2`, and :math:`A > 0` being the set of
+    all the positive definite matrices of dimension `d`.  Note that `a` is a
+    scalar: the integrand only is multivariate, the argument is not (the
+    function is defined over a subset of the real set).
+
+    This can be proven to be equal to the much friendlier equation
+
+    .. math::
+
+        \Gamma_d(a) = \pi^{d(d-1)/4} \prod_{i=1}^{d} \Gamma(a - (i-1)/2).
+
+    References
+    ----------
+    R. J. Muirhead, Aspects of multivariate statistical theory (Wiley Series in
+    probability and mathematical statistics).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import multigammaln, gammaln
+    >>> a = 23.5
+    >>> d = 10
+    >>> multigammaln(a, d)
+    454.1488605074416
+
+    Verify that the result agrees with the logarithm of the equation
+    shown above:
+
+    >>> d*(d-1)/4*np.log(np.pi) + gammaln(a - 0.5*np.arange(0, d)).sum()
+    454.1488605074416
+    """
+    a = np.asarray(a)
+    if not np.isscalar(d) or (np.floor(d) != d):
+        raise ValueError("d should be a positive integer (dimension)")
+    if np.any(a <= 0.5 * (d - 1)):
+        raise ValueError(f"condition a ({a:f}) > 0.5 * (d-1) ({0.5 * (d-1):f}) not met")
+
+    res = (d * (d-1) * 0.25) * np.log(np.pi)
+    res += np.sum(loggam([(a - (j - 1.)/2) for j in range(1, d+1)]), axis=0)
+    return res
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3d871fcd07ef092962a4594cf780445daae4458
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py
@@ -0,0 +1,397 @@
+from functools import wraps
+from scipy._lib._util import _lazywhere
+import numpy as np
+from ._ufuncs import (_spherical_jn, _spherical_yn, _spherical_in,
+                      _spherical_kn, _spherical_jn_d, _spherical_yn_d,
+                      _spherical_in_d, _spherical_kn_d)
+
+
+def use_reflection(sign_n_even=None, reflection_fun=None):
+    # - If reflection_fun is not specified, reflects negative `z` and multiplies
+    #   output by appropriate sign (indicated by `sign_n_even`).
+    # - If reflection_fun is specified, calls `reflection_fun` instead of `fun`.
+    # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+    def decorator(fun):
+        def standard_reflection(n, z, derivative):
+            # sign_n_even indicates the sign when the order `n` is even
+            sign = np.where(n % 2 == 0, sign_n_even, -sign_n_even)
+            # By the chain rule, differentiation at `-z` adds a minus sign
+            sign = -sign if derivative else sign
+            # Evaluate at positive z (minus negative z) and adjust the sign
+            return fun(n, -z, derivative) * sign
+
+        @wraps(fun)
+        def wrapper(n, z, derivative=False):
+            z = np.asarray(z)
+
+            if np.issubdtype(z.dtype, np.complexfloating):
+                return fun(n, z, derivative)  # complex dtype just works
+
+            f2 = standard_reflection if reflection_fun is None else reflection_fun
+            return _lazywhere(z.real >= 0, (n, z),
+                              f=lambda n, z: fun(n, z, derivative),
+                              f2=lambda n, z: f2(n, z, derivative))[()]
+        return wrapper
+    return decorator
+
+
+@use_reflection(+1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_jn(n, z, derivative=False):
+    r"""Spherical Bessel function of the first kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: j_n(z) = \sqrt{\frac{\pi}{2z}} J_{n + 1/2}(z),
+
+    where :math:`J_n` is the Bessel function of the first kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    jn : ndarray
+
+    Notes
+    -----
+    For real arguments greater than the order, the function is computed
+    using the ascending recurrence [2]_. For small real or complex
+    arguments, the definitional relation to the cylindrical Bessel function
+    of the first kind is used.
+
+    The derivative is computed using the relations [3]_,
+
+    .. math::
+        j_n'(z) = j_{n-1}(z) - \frac{n + 1}{z} j_n(z).
+
+        j_0'(z) = -j_1(z)
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E3
+    .. [2] https://dlmf.nist.gov/10.51.E1
+    .. [3] https://dlmf.nist.gov/10.51.E2
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The spherical Bessel functions of the first kind :math:`j_n` accept
+    both real and complex second argument. They can return a complex type:
+
+    >>> from scipy.special import spherical_jn
+    >>> spherical_jn(0, 3+5j)
+    (-9.878987731663194-8.021894345786002j)
+    >>> type(spherical_jn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_jn(3, x, True),
+    ...             spherical_jn(2, x) - 4/x * spherical_jn(3, x))
+    True
+
+    The first few :math:`j_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 10.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-0.5, 1.5)
+    >>> ax.set_title(r'Spherical Bessel functions $j_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_jn(n, x), label=rf'$j_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_jn_d(n, z)
+    else:
+        return _spherical_jn(n, z)
+
+
+@use_reflection(-1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_yn(n, z, derivative=False):
+    r"""Spherical Bessel function of the second kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: y_n(z) = \sqrt{\frac{\pi}{2z}} Y_{n + 1/2}(z),
+
+    where :math:`Y_n` is the Bessel function of the second kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    yn : ndarray
+
+    Notes
+    -----
+    For real arguments, the function is computed using the ascending
+    recurrence [2]_.  For complex arguments, the definitional relation to
+    the cylindrical Bessel function of the second kind is used.
+
+    The derivative is computed using the relations [3]_,
+
+    .. math::
+        y_n' = y_{n-1} - \frac{n + 1}{z} y_n.
+
+        y_0' = -y_1
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E4
+    .. [2] https://dlmf.nist.gov/10.51.E1
+    .. [3] https://dlmf.nist.gov/10.51.E2
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The spherical Bessel functions of the second kind :math:`y_n` accept
+    both real and complex second argument. They can return a complex type:
+
+    >>> from scipy.special import spherical_yn
+    >>> spherical_yn(0, 3+5j)
+    (8.022343088587197-9.880052589376795j)
+    >>> type(spherical_yn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_yn(3, x, True),
+    ...             spherical_yn(2, x) - 4/x * spherical_yn(3, x))
+    True
+
+    The first few :math:`y_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 10.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 1.0)
+    >>> ax.set_title(r'Spherical Bessel functions $y_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_yn(n, x), label=rf'$y_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_yn_d(n, z)
+    else:
+        return _spherical_yn(n, z)
+
+
+@use_reflection(+1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_in(n, z, derivative=False):
+    r"""Modified spherical Bessel function of the first kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: i_n(z) = \sqrt{\frac{\pi}{2z}} I_{n + 1/2}(z),
+
+    where :math:`I_n` is the modified Bessel function of the first kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    in : ndarray
+
+    Notes
+    -----
+    The function is computed using its definitional relation to the
+    modified cylindrical Bessel function of the first kind.
+
+    The derivative is computed using the relations [2]_,
+
+    .. math::
+        i_n' = i_{n-1} - \frac{n + 1}{z} i_n.
+
+        i_1' = i_0
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E7
+    .. [2] https://dlmf.nist.gov/10.51.E5
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The modified spherical Bessel functions of the first kind :math:`i_n`
+    accept both real and complex second argument.
+    They can return a complex type:
+
+    >>> from scipy.special import spherical_in
+    >>> spherical_in(0, 3+5j)
+    (-1.1689867793369182-1.2697305267234222j)
+    >>> type(spherical_in(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_in(3, x, True),
+    ...             spherical_in(2, x) - 4/x * spherical_in(3, x))
+    True
+
+    The first few :math:`i_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 6.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-0.5, 5.0)
+    >>> ax.set_title(r'Modified spherical Bessel functions $i_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_in(n, x), label=rf'$i_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_in_d(n, z)
+    else:
+        return _spherical_in(n, z)
+
+
+def spherical_kn_reflection(n, z, derivative=False):
+    # More complex than the other cases, and this will likely be re-implemented
+    # in C++ anyway. Would require multiple function evaluations. Probably about
+    # as fast to just resort to complex math, and much simpler.
+    return spherical_kn(n, z + 0j, derivative=derivative).real
+
+
+@use_reflection(reflection_fun=spherical_kn_reflection)
+def spherical_kn(n, z, derivative=False):
+    r"""Modified spherical Bessel function of the second kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: k_n(z) = \sqrt{\frac{\pi}{2z}} K_{n + 1/2}(z),
+
+    where :math:`K_n` is the modified Bessel function of the second kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    kn : ndarray
+
+    Notes
+    -----
+    The function is computed using its definitional relation to the
+    modified cylindrical Bessel function of the second kind.
+
+    The derivative is computed using the relations [2]_,
+
+    .. math::
+        k_n' = -k_{n-1} - \frac{n + 1}{z} k_n.
+
+        k_0' = -k_1
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E9
+    .. [2] https://dlmf.nist.gov/10.51.E5
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The modified spherical Bessel functions of the second kind :math:`k_n`
+    accept both real and complex second argument.
+    They can return a complex type:
+
+    >>> from scipy.special import spherical_kn
+    >>> spherical_kn(0, 3+5j)
+    (0.012985785614001561+0.003354691603137546j)
+    >>> type(spherical_kn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_kn(3, x, True),
+    ...             - 4/x * spherical_kn(3, x) - spherical_kn(2, x))
+    True
+
+    The first few :math:`k_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 4.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(0.0, 5.0)
+    >>> ax.set_title(r'Modified spherical Bessel functions $k_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_kn(n, x), label=rf'$k_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_kn_d(n, z)
+    else:
+        return _spherical_kn(n, z)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f5101198cebcbb5138e88a2050a5c4d7a115d60
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py
@@ -0,0 +1,202 @@
+import os
+import sys
+import functools
+
+import numpy as np
+from scipy._lib._array_api import (
+    array_namespace, scipy_namespace_for, is_numpy
+)
+from . import _ufuncs
+# These don't really need to be imported, but otherwise IDEs might not realize
+# that these are defined in this file / report an error in __init__.py
+from ._ufuncs import (
+    log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, gammaln,  # noqa: F401
+    gammainc, gammaincc, logit, expit, entr, rel_entr, xlogy,  # noqa: F401
+    chdtr, chdtrc, betainc, betaincc, stdtr  # noqa: F401
+)
+
+_SCIPY_ARRAY_API = os.environ.get("SCIPY_ARRAY_API", False)
+array_api_compat_prefix = "scipy._lib.array_api_compat"
+
+
+def get_array_special_func(f_name, xp, n_array_args):
+    spx = scipy_namespace_for(xp)
+    f = None
+    if is_numpy(xp):
+        f = getattr(_ufuncs, f_name, None)
+    elif spx is not None:
+        f = getattr(spx.special, f_name, None)
+
+    if f is not None:
+        return f
+
+    # if generic array-API implementation is available, use that;
+    # otherwise, fall back to NumPy/SciPy
+    if f_name in _generic_implementations:
+        _f = _generic_implementations[f_name](xp=xp, spx=spx)
+        if _f is not None:
+            return _f
+
+    _f = getattr(_ufuncs, f_name, None)
+    def __f(*args, _f=_f, _xp=xp, **kwargs):
+        array_args = args[:n_array_args]
+        other_args = args[n_array_args:]
+        array_args = [np.asarray(arg) for arg in array_args]
+        out = _f(*array_args, *other_args, **kwargs)
+        return _xp.asarray(out)
+
+    return __f
+
+
+def _get_shape_dtype(*args, xp):
+    args = xp.broadcast_arrays(*args)
+    shape = args[0].shape
+    dtype = xp.result_type(*args)
+    if xp.isdtype(dtype, 'integral'):
+        dtype = xp.float64
+        args = [xp.asarray(arg, dtype=dtype) for arg in args]
+    return args, shape, dtype
+
+
+def _rel_entr(xp, spx):
+    def __rel_entr(x, y, *, xp=xp):
+        args, shape, dtype = _get_shape_dtype(x, y, xp=xp)
+        x, y = args
+        res = xp.full(x.shape, xp.inf, dtype=dtype)
+        res[(x == 0) & (y >= 0)] = xp.asarray(0, dtype=dtype)
+        i = (x > 0) & (y > 0)
+        res[i] = x[i] * (xp.log(x[i]) - xp.log(y[i]))
+        return res
+    return __rel_entr
+
+
+def _xlogy(xp, spx):
+    def __xlogy(x, y, *, xp=xp):
+        with np.errstate(divide='ignore', invalid='ignore'):
+            temp = x * xp.log(y)
+        return xp.where(x == 0., xp.asarray(0., dtype=temp.dtype), temp)
+    return __xlogy
+
+
+def _chdtr(xp, spx):
+    # The difference between this and just using `gammainc`
+    # defined by `get_array_special_func` is that if `gammainc`
+    # isn't found, we don't want to use the SciPy version; we'll
+    # return None here and use the SciPy version of `chdtr`.
+    gammainc = getattr(spx.special, 'gammainc', None) if spx else None  # noqa: F811
+    if gammainc is None and hasattr(xp, 'special'):
+        gammainc = getattr(xp.special, 'gammainc', None)
+    if gammainc is None:
+        return None
+
+    def __chdtr(v, x):
+        res = gammainc(v / 2, x / 2)  # this is almost all we need
+        # The rest can be removed when google/jax#20507 is resolved
+        mask = (v == 0) & (x > 0)  # JAX returns NaN
+        res = xp.where(mask, 1., res)
+        mask = xp.isinf(v) & xp.isinf(x)  # JAX returns 1.0
+        return xp.where(mask, xp.nan, res)
+    return __chdtr
+
+
+def _chdtrc(xp, spx):
+    # The difference between this and just using `gammaincc`
+    # defined by `get_array_special_func` is that if `gammaincc`
+    # isn't found, we don't want to use the SciPy version; we'll
+    # return None here and use the SciPy version of `chdtrc`.
+    gammaincc = getattr(spx.special, 'gammaincc', None) if spx else None  # noqa: F811
+    if gammaincc is None and hasattr(xp, 'special'):
+        gammaincc = getattr(xp.special, 'gammaincc', None)
+    if gammaincc is None:
+        return None
+
+    def __chdtrc(v, x):
+        res = xp.where(x >= 0, gammaincc(v/2, x/2), 1)
+        i_nan = ((x == 0) & (v == 0)) | xp.isnan(x) | xp.isnan(v) | (v <= 0)
+        res = xp.where(i_nan, xp.nan, res)
+        return res
+    return __chdtrc
+
+
+def _betaincc(xp, spx):
+    betainc = getattr(spx.special, 'betainc', None) if spx else None  # noqa: F811
+    if betainc is None and hasattr(xp, 'special'):
+        betainc = getattr(xp.special, 'betainc', None)
+    if betainc is None:
+        return None
+
+    def __betaincc(a, b, x):
+        # not perfect; might want to just rely on SciPy
+        return betainc(b, a, 1-x)
+    return __betaincc
+
+
+def _stdtr(xp, spx):
+    betainc = getattr(spx.special, 'betainc', None) if spx else None  # noqa: F811
+    if betainc is None and hasattr(xp, 'special'):
+        betainc = getattr(xp.special, 'betainc', None)
+    if betainc is None:
+        return None
+
+    def __stdtr(df, t):
+        x = df / (t ** 2 + df)
+        tail = betainc(df / 2, 0.5, x) / 2
+        return xp.where(t < 0, tail, 1 - tail)
+
+    return __stdtr
+
+
+_generic_implementations = {'rel_entr': _rel_entr,
+                            'xlogy': _xlogy,
+                            'chdtr': _chdtr,
+                            'chdtrc': _chdtrc,
+                            'betaincc': _betaincc,
+                            'stdtr': _stdtr,
+                            }
+
+
+# functools.wraps doesn't work because:
+# 'numpy.ufunc' object has no attribute '__module__'
+def support_alternative_backends(f_name, n_array_args):
+    func = getattr(_ufuncs, f_name)
+
+    @functools.wraps(func)
+    def wrapped(*args, **kwargs):
+        xp = array_namespace(*args[:n_array_args])
+        f = get_array_special_func(f_name, xp, n_array_args)
+        return f(*args, **kwargs)
+
+    return wrapped
+
+
+array_special_func_map = {
+    'log_ndtr': 1,
+    'ndtr': 1,
+    'ndtri': 1,
+    'erf': 1,
+    'erfc': 1,
+    'i0': 1,
+    'i0e': 1,
+    'i1': 1,
+    'i1e': 1,
+    'gammaln': 1,
+    'gammainc': 2,
+    'gammaincc': 2,
+    'logit': 1,
+    'expit': 1,
+    'entr': 1,
+    'rel_entr': 2,
+    'xlogy': 2,
+    'chdtr': 2,
+    'chdtrc': 2,
+    'betainc': 3,
+    'betaincc': 3,
+    'stdtr': 2,
+}
+
+for f_name, n_array_args in array_special_func_map.items():
+    f = (support_alternative_backends(f_name, n_array_args) if _SCIPY_ARRAY_API
+         else getattr(_ufuncs, f_name))
+    sys.modules[__name__].__dict__[f_name] = f
+
+__all__ = list(array_special_func_map)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..1e6c272f16fa2bd3ae75af412bc6ae3270158ce4
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi
@@ -0,0 +1,9 @@
+import numpy as np
+
+def have_fenv() -> bool: ...
+def random_double(size: int, rng: np.random.RandomState) -> np.float64: ...
+def test_add_round(size: int, mode: str, rng: np.random.RandomState): ...
+
+def _dd_exp(xhi: float, xlo: float) -> tuple[float, float]: ...
+def _dd_log(xhi: float, xlo: float) -> tuple[float, float]: ...
+def _dd_expm1(xhi: float, xlo: float) -> tuple[float, float]: ...
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0c2bd3053d076aacfa8be1d53cd851443fd8821
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py
@@ -0,0 +1,321 @@
+import os
+import functools
+import operator
+from scipy._lib import _pep440
+
+import numpy as np
+from numpy.testing import assert_
+import pytest
+
+import scipy.special as sc
+
+__all__ = ['with_special_errors', 'assert_func_equal', 'FuncData']
+
+
+#------------------------------------------------------------------------------
+# Check if a module is present to be used in tests
+#------------------------------------------------------------------------------
+
+class MissingModule:
+    def __init__(self, name):
+        self.name = name
+
+
+def check_version(module, min_ver):
+    if type(module) is MissingModule:
+        return pytest.mark.skip(reason=f"{module.name} is not installed")
+    return pytest.mark.skipif(
+        _pep440.parse(module.__version__) < _pep440.Version(min_ver),
+        reason=f"{module.__name__} version >= {min_ver} required"
+    )
+
+
+#------------------------------------------------------------------------------
+# Enable convergence and loss of precision warnings -- turn off one by one
+#------------------------------------------------------------------------------
+
+def with_special_errors(func):
+    """
+    Enable special function errors (such as underflow, overflow,
+    loss of precision, etc.)
+    """
+    @functools.wraps(func)
+    def wrapper(*a, **kw):
+        with sc.errstate(all='raise'):
+            res = func(*a, **kw)
+        return res
+    return wrapper
+
+
+#------------------------------------------------------------------------------
+# Comparing function values at many data points at once, with helpful
+# error reports
+#------------------------------------------------------------------------------
+
+def assert_func_equal(func, results, points, rtol=None, atol=None,
+                      param_filter=None, knownfailure=None,
+                      vectorized=True, dtype=None, nan_ok=False,
+                      ignore_inf_sign=False, distinguish_nan_and_inf=True):
+    if hasattr(points, 'next'):
+        # it's a generator
+        points = list(points)
+
+    points = np.asarray(points)
+    if points.ndim == 1:
+        points = points[:,None]
+    nparams = points.shape[1]
+
+    if hasattr(results, '__name__'):
+        # function
+        data = points
+        result_columns = None
+        result_func = results
+    else:
+        # dataset
+        data = np.c_[points, results]
+        result_columns = list(range(nparams, data.shape[1]))
+        result_func = None
+
+    fdata = FuncData(func, data, list(range(nparams)),
+                     result_columns=result_columns, result_func=result_func,
+                     rtol=rtol, atol=atol, param_filter=param_filter,
+                     knownfailure=knownfailure, nan_ok=nan_ok, vectorized=vectorized,
+                     ignore_inf_sign=ignore_inf_sign,
+                     distinguish_nan_and_inf=distinguish_nan_and_inf)
+    fdata.check()
+
+
+class FuncData:
+    """
+    Data set for checking a special function.
+
+    Parameters
+    ----------
+    func : function
+        Function to test
+    data : numpy array
+        columnar data to use for testing
+    param_columns : int or tuple of ints
+        Columns indices in which the parameters to `func` lie.
+        Can be imaginary integers to indicate that the parameter
+        should be cast to complex.
+    result_columns : int or tuple of ints, optional
+        Column indices for expected results from `func`.
+    result_func : callable, optional
+        Function to call to obtain results.
+    rtol : float, optional
+        Required relative tolerance. Default is 5*eps.
+    atol : float, optional
+        Required absolute tolerance. Default is 5*tiny.
+    param_filter : function, or tuple of functions/Nones, optional
+        Filter functions to exclude some parameter ranges.
+        If omitted, no filtering is done.
+    knownfailure : str, optional
+        Known failure error message to raise when the test is run.
+        If omitted, no exception is raised.
+    nan_ok : bool, optional
+        If nan is always an accepted result.
+    vectorized : bool, optional
+        Whether all functions passed in are vectorized.
+    ignore_inf_sign : bool, optional
+        Whether to ignore signs of infinities.
+        (Doesn't matter for complex-valued functions.)
+    distinguish_nan_and_inf : bool, optional
+        If True, treat numbers which contain nans or infs as
+        equal. Sets ignore_inf_sign to be True.
+
+    """
+
+    def __init__(self, func, data, param_columns, result_columns=None,
+                 result_func=None, rtol=None, atol=None, param_filter=None,
+                 knownfailure=None, dataname=None, nan_ok=False, vectorized=True,
+                 ignore_inf_sign=False, distinguish_nan_and_inf=True):
+        self.func = func
+        self.data = data
+        self.dataname = dataname
+        if not hasattr(param_columns, '__len__'):
+            param_columns = (param_columns,)
+        self.param_columns = tuple(param_columns)
+        if result_columns is not None:
+            if not hasattr(result_columns, '__len__'):
+                result_columns = (result_columns,)
+            self.result_columns = tuple(result_columns)
+            if result_func is not None:
+                message = "Only result_func or result_columns should be provided"
+                raise ValueError(message)
+        elif result_func is not None:
+            self.result_columns = None
+        else:
+            raise ValueError("Either result_func or result_columns should be provided")
+        self.result_func = result_func
+        self.rtol = rtol
+        self.atol = atol
+        if not hasattr(param_filter, '__len__'):
+            param_filter = (param_filter,)
+        self.param_filter = param_filter
+        self.knownfailure = knownfailure
+        self.nan_ok = nan_ok
+        self.vectorized = vectorized
+        self.ignore_inf_sign = ignore_inf_sign
+        self.distinguish_nan_and_inf = distinguish_nan_and_inf
+        if not self.distinguish_nan_and_inf:
+            self.ignore_inf_sign = True
+
+    def get_tolerances(self, dtype):
+        if not np.issubdtype(dtype, np.inexact):
+            dtype = np.dtype(float)
+        info = np.finfo(dtype)
+        rtol, atol = self.rtol, self.atol
+        if rtol is None:
+            rtol = 5*info.eps
+        if atol is None:
+            atol = 5*info.tiny
+        return rtol, atol
+
+    def check(self, data=None, dtype=None, dtypes=None):
+        """Check the special function against the data."""
+        __tracebackhide__ = operator.methodcaller(
+            'errisinstance', AssertionError
+        )
+
+        if self.knownfailure:
+            pytest.xfail(reason=self.knownfailure)
+
+        if data is None:
+            data = self.data
+
+        if dtype is None:
+            dtype = data.dtype
+        else:
+            data = data.astype(dtype)
+
+        rtol, atol = self.get_tolerances(dtype)
+
+        # Apply given filter functions
+        if self.param_filter:
+            param_mask = np.ones((data.shape[0],), np.bool_)
+            for j, filter in zip(self.param_columns, self.param_filter):
+                if filter:
+                    param_mask &= list(filter(data[:,j]))
+            data = data[param_mask]
+
+        # Pick parameters from the correct columns
+        params = []
+        for idx, j in enumerate(self.param_columns):
+            if np.iscomplexobj(j):
+                j = int(j.imag)
+                params.append(data[:,j].astype(complex))
+            elif dtypes and idx < len(dtypes):
+                params.append(data[:, j].astype(dtypes[idx]))
+            else:
+                params.append(data[:,j])
+
+        # Helper for evaluating results
+        def eval_func_at_params(func, skip_mask=None):
+            if self.vectorized:
+                got = func(*params)
+            else:
+                got = []
+                for j in range(len(params[0])):
+                    if skip_mask is not None and skip_mask[j]:
+                        got.append(np.nan)
+                        continue
+                    got.append(func(*tuple([params[i][j] for i in range(len(params))])))
+                got = np.asarray(got)
+            if not isinstance(got, tuple):
+                got = (got,)
+            return got
+
+        # Evaluate function to be tested
+        got = eval_func_at_params(self.func)
+
+        # Grab the correct results
+        if self.result_columns is not None:
+            # Correct results passed in with the data
+            wanted = tuple([data[:,icol] for icol in self.result_columns])
+        else:
+            # Function producing correct results passed in
+            skip_mask = None
+            if self.nan_ok and len(got) == 1:
+                # Don't spend time evaluating what doesn't need to be evaluated
+                skip_mask = np.isnan(got[0])
+            wanted = eval_func_at_params(self.result_func, skip_mask=skip_mask)
+
+        # Check the validity of each output returned
+        assert_(len(got) == len(wanted))
+
+        for output_num, (x, y) in enumerate(zip(got, wanted)):
+            if np.issubdtype(x.dtype, np.complexfloating) or self.ignore_inf_sign:
+                pinf_x = np.isinf(x)
+                pinf_y = np.isinf(y)
+                minf_x = np.isinf(x)
+                minf_y = np.isinf(y)
+            else:
+                pinf_x = np.isposinf(x)
+                pinf_y = np.isposinf(y)
+                minf_x = np.isneginf(x)
+                minf_y = np.isneginf(y)
+            nan_x = np.isnan(x)
+            nan_y = np.isnan(y)
+
+            with np.errstate(all='ignore'):
+                abs_y = np.absolute(y)
+                abs_y[~np.isfinite(abs_y)] = 0
+                diff = np.absolute(x - y)
+                diff[~np.isfinite(diff)] = 0
+
+                rdiff = diff / np.absolute(y)
+                rdiff[~np.isfinite(rdiff)] = 0
+
+            tol_mask = (diff <= atol + rtol*abs_y)
+            pinf_mask = (pinf_x == pinf_y)
+            minf_mask = (minf_x == minf_y)
+
+            nan_mask = (nan_x == nan_y)
+
+            bad_j = ~(tol_mask & pinf_mask & minf_mask & nan_mask)
+
+            point_count = bad_j.size
+            if self.nan_ok:
+                bad_j &= ~nan_x
+                bad_j &= ~nan_y
+                point_count -= (nan_x | nan_y).sum()
+
+            if not self.distinguish_nan_and_inf and not self.nan_ok:
+                # If nan's are okay we've already covered all these cases
+                inf_x = np.isinf(x)
+                inf_y = np.isinf(y)
+                both_nonfinite = (inf_x & nan_y) | (nan_x & inf_y)
+                bad_j &= ~both_nonfinite
+                point_count -= both_nonfinite.sum()
+
+            if np.any(bad_j):
+                # Some bad results: inform what, where, and how bad
+                msg = [""]
+                msg.append(f"Max |adiff|: {diff[bad_j].max():g}")
+                msg.append(f"Max |rdiff|: {rdiff[bad_j].max():g}")
+                msg.append("Bad results (%d out of %d) for the following points "
+                           "(in output %d):"
+                           % (np.sum(bad_j), point_count, output_num,))
+                for j in np.nonzero(bad_j)[0]:
+                    j = int(j)
+                    def fmt(x):
+                        return '%30s' % np.array2string(x[j], precision=18)
+                    a = "  ".join(map(fmt, params))
+                    b = "  ".join(map(fmt, got))
+                    c = "  ".join(map(fmt, wanted))
+                    d = fmt(rdiff)
+                    msg.append(f"{a} => {b} != {c}  (rdiff {d})")
+                assert_(False, "\n".join(msg))
+
+    def __repr__(self):
+        """Pretty-printing"""
+        if np.any(list(map(np.iscomplexobj, self.param_columns))):
+            is_complex = " (complex)"
+        else:
+            is_complex = ""
+        if self.dataname:
+            return (f"")
+        else:
+            return f""
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0ccf14137096c862a0644cdb229cb98b4556e5d7
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi
@@ -0,0 +1,521 @@
+from typing import Any
+
+import numpy as np
+
+__all__ = [
+    'geterr',
+    'seterr',
+    'errstate',
+    'agm',
+    'airy',
+    'airye',
+    'bdtr',
+    'bdtrc',
+    'bdtri',
+    'bdtrik',
+    'bdtrin',
+    'bei',
+    'beip',
+    'ber',
+    'berp',
+    'besselpoly',
+    'beta',
+    'betainc',
+    'betaincc',
+    'betainccinv',
+    'betaincinv',
+    'betaln',
+    'binom',
+    'boxcox',
+    'boxcox1p',
+    'btdtria',
+    'btdtrib',
+    'cbrt',
+    'chdtr',
+    'chdtrc',
+    'chdtri',
+    'chdtriv',
+    'chndtr',
+    'chndtridf',
+    'chndtrinc',
+    'chndtrix',
+    'cosdg',
+    'cosm1',
+    'cotdg',
+    'dawsn',
+    'ellipe',
+    'ellipeinc',
+    'ellipj',
+    'ellipk',
+    'ellipkinc',
+    'ellipkm1',
+    'elliprc',
+    'elliprd',
+    'elliprf',
+    'elliprg',
+    'elliprj',
+    'entr',
+    'erf',
+    'erfc',
+    'erfcinv',
+    'erfcx',
+    'erfi',
+    'erfinv',
+    'eval_chebyc',
+    'eval_chebys',
+    'eval_chebyt',
+    'eval_chebyu',
+    'eval_gegenbauer',
+    'eval_genlaguerre',
+    'eval_hermite',
+    'eval_hermitenorm',
+    'eval_jacobi',
+    'eval_laguerre',
+    'eval_legendre',
+    'eval_sh_chebyt',
+    'eval_sh_chebyu',
+    'eval_sh_jacobi',
+    'eval_sh_legendre',
+    'exp1',
+    'exp10',
+    'exp2',
+    'expi',
+    'expit',
+    'expm1',
+    'expn',
+    'exprel',
+    'fdtr',
+    'fdtrc',
+    'fdtri',
+    'fdtridfd',
+    'fresnel',
+    'gamma',
+    'gammainc',
+    'gammaincc',
+    'gammainccinv',
+    'gammaincinv',
+    'gammaln',
+    'gammasgn',
+    'gdtr',
+    'gdtrc',
+    'gdtria',
+    'gdtrib',
+    'gdtrix',
+    'hankel1',
+    'hankel1e',
+    'hankel2',
+    'hankel2e',
+    'huber',
+    'hyp0f1',
+    'hyp1f1',
+    'hyp2f1',
+    'hyperu',
+    'i0',
+    'i0e',
+    'i1',
+    'i1e',
+    'inv_boxcox',
+    'inv_boxcox1p',
+    'it2i0k0',
+    'it2j0y0',
+    'it2struve0',
+    'itairy',
+    'iti0k0',
+    'itj0y0',
+    'itmodstruve0',
+    'itstruve0',
+    'iv',
+    'ive',
+    'j0',
+    'j1',
+    'jn',
+    'jv',
+    'jve',
+    'k0',
+    'k0e',
+    'k1',
+    'k1e',
+    'kei',
+    'keip',
+    'kelvin',
+    'ker',
+    'kerp',
+    'kl_div',
+    'kn',
+    'kolmogi',
+    'kolmogorov',
+    'kv',
+    'kve',
+    'log1p',
+    'log_expit',
+    'log_ndtr',
+    'log_wright_bessel',
+    'loggamma',
+    'logit',
+    'lpmv',
+    'mathieu_a',
+    'mathieu_b',
+    'mathieu_cem',
+    'mathieu_modcem1',
+    'mathieu_modcem2',
+    'mathieu_modsem1',
+    'mathieu_modsem2',
+    'mathieu_sem',
+    'modfresnelm',
+    'modfresnelp',
+    'modstruve',
+    'nbdtr',
+    'nbdtrc',
+    'nbdtri',
+    'nbdtrik',
+    'nbdtrin',
+    'ncfdtr',
+    'ncfdtri',
+    'ncfdtridfd',
+    'ncfdtridfn',
+    'ncfdtrinc',
+    'nctdtr',
+    'nctdtridf',
+    'nctdtrinc',
+    'nctdtrit',
+    'ndtr',
+    'ndtri',
+    'ndtri_exp',
+    'nrdtrimn',
+    'nrdtrisd',
+    'obl_ang1',
+    'obl_ang1_cv',
+    'obl_cv',
+    'obl_rad1',
+    'obl_rad1_cv',
+    'obl_rad2',
+    'obl_rad2_cv',
+    'owens_t',
+    'pbdv',
+    'pbvv',
+    'pbwa',
+    'pdtr',
+    'pdtrc',
+    'pdtri',
+    'pdtrik',
+    'poch',
+    'powm1',
+    'pro_ang1',
+    'pro_ang1_cv',
+    'pro_cv',
+    'pro_rad1',
+    'pro_rad1_cv',
+    'pro_rad2',
+    'pro_rad2_cv',
+    'pseudo_huber',
+    'psi',
+    'radian',
+    'rel_entr',
+    'rgamma',
+    'round',
+    'shichi',
+    'sici',
+    'sindg',
+    'smirnov',
+    'smirnovi',
+    'spence',
+    'sph_harm',
+    'stdtr',
+    'stdtridf',
+    'stdtrit',
+    'struve',
+    'tandg',
+    'tklmbda',
+    'voigt_profile',
+    'wofz',
+    'wright_bessel',
+    'wrightomega',
+    'xlog1py',
+    'xlogy',
+    'y0',
+    'y1',
+    'yn',
+    'yv',
+    'yve',
+    'zetac'
+]
+
+def geterr() -> dict[str, str]: ...
+def seterr(**kwargs: str) -> dict[str, str]: ...
+
+class errstate:
+    def __init__(self, **kargs: str) -> None: ...
+    def __enter__(self) -> None: ...
+    def __exit__(
+        self,
+        exc_type: Any,  # Unused
+        exc_value: Any,  # Unused
+        traceback: Any,  # Unused
+    ) -> None: ...
+
+_cosine_cdf: np.ufunc
+_cosine_invcdf: np.ufunc
+_cospi: np.ufunc
+_ellip_harm: np.ufunc
+_factorial: np.ufunc
+_igam_fac: np.ufunc
+_kolmogc: np.ufunc
+_kolmogci: np.ufunc
+_kolmogp: np.ufunc
+_lambertw: np.ufunc
+_lanczos_sum_expg_scaled: np.ufunc
+_lgam1p: np.ufunc
+_log1pmx: np.ufunc
+_riemann_zeta: np.ufunc
+_scaled_exp1: np.ufunc
+_sf_error_test_function: np.ufunc
+_sinpi: np.ufunc
+_smirnovc: np.ufunc
+_smirnovci: np.ufunc
+_smirnovp: np.ufunc
+_spherical_in: np.ufunc
+_spherical_in_d: np.ufunc
+_spherical_jn: np.ufunc
+_spherical_jn_d: np.ufunc
+_spherical_kn: np.ufunc
+_spherical_kn_d: np.ufunc
+_spherical_yn: np.ufunc
+_spherical_yn_d: np.ufunc
+_stirling2_inexact: np.ufunc
+_struve_asymp_large_z: np.ufunc
+_struve_bessel_series: np.ufunc
+_struve_power_series: np.ufunc
+_zeta: np.ufunc
+agm: np.ufunc
+airy: np.ufunc
+airye: np.ufunc
+bdtr: np.ufunc
+bdtrc: np.ufunc
+bdtri: np.ufunc
+bdtrik: np.ufunc
+bdtrin: np.ufunc
+bei: np.ufunc
+beip: np.ufunc
+ber: np.ufunc
+berp: np.ufunc
+besselpoly: np.ufunc
+beta: np.ufunc
+betainc: np.ufunc
+betaincc: np.ufunc
+betainccinv: np.ufunc
+betaincinv: np.ufunc
+betaln: np.ufunc
+binom: np.ufunc
+boxcox1p: np.ufunc
+boxcox: np.ufunc
+btdtria: np.ufunc
+btdtrib: np.ufunc
+cbrt: np.ufunc
+chdtr: np.ufunc
+chdtrc: np.ufunc
+chdtri: np.ufunc
+chdtriv: np.ufunc
+chndtr: np.ufunc
+chndtridf: np.ufunc
+chndtrinc: np.ufunc
+chndtrix: np.ufunc
+cosdg: np.ufunc
+cosm1: np.ufunc
+cotdg: np.ufunc
+dawsn: np.ufunc
+ellipe: np.ufunc
+ellipeinc: np.ufunc
+ellipj: np.ufunc
+ellipk: np.ufunc
+ellipkinc: np.ufunc
+ellipkm1: np.ufunc
+elliprc: np.ufunc
+elliprd: np.ufunc
+elliprf: np.ufunc
+elliprg: np.ufunc
+elliprj: np.ufunc
+entr: np.ufunc
+erf: np.ufunc
+erfc: np.ufunc
+erfcinv: np.ufunc
+erfcx: np.ufunc
+erfi: np.ufunc
+erfinv: np.ufunc
+eval_chebyc: np.ufunc
+eval_chebys: np.ufunc
+eval_chebyt: np.ufunc
+eval_chebyu: np.ufunc
+eval_gegenbauer: np.ufunc
+eval_genlaguerre: np.ufunc
+eval_hermite: np.ufunc
+eval_hermitenorm: np.ufunc
+eval_jacobi: np.ufunc
+eval_laguerre: np.ufunc
+eval_legendre: np.ufunc
+eval_sh_chebyt: np.ufunc
+eval_sh_chebyu: np.ufunc
+eval_sh_jacobi: np.ufunc
+eval_sh_legendre: np.ufunc
+exp10: np.ufunc
+exp1: np.ufunc
+exp2: np.ufunc
+expi: np.ufunc
+expit: np.ufunc
+expm1: np.ufunc
+expn: np.ufunc
+exprel: np.ufunc
+fdtr: np.ufunc
+fdtrc: np.ufunc
+fdtri: np.ufunc
+fdtridfd: np.ufunc
+fresnel: np.ufunc
+gamma: np.ufunc
+gammainc: np.ufunc
+gammaincc: np.ufunc
+gammainccinv: np.ufunc
+gammaincinv: np.ufunc
+gammaln: np.ufunc
+gammasgn: np.ufunc
+gdtr: np.ufunc
+gdtrc: np.ufunc
+gdtria: np.ufunc
+gdtrib: np.ufunc
+gdtrix: np.ufunc
+hankel1: np.ufunc
+hankel1e: np.ufunc
+hankel2: np.ufunc
+hankel2e: np.ufunc
+huber: np.ufunc
+hyp0f1: np.ufunc
+hyp1f1: np.ufunc
+hyp2f1: np.ufunc
+hyperu: np.ufunc
+i0: np.ufunc
+i0e: np.ufunc
+i1: np.ufunc
+i1e: np.ufunc
+inv_boxcox1p: np.ufunc
+inv_boxcox: np.ufunc
+it2i0k0: np.ufunc
+it2j0y0: np.ufunc
+it2struve0: np.ufunc
+itairy: np.ufunc
+iti0k0: np.ufunc
+itj0y0: np.ufunc
+itmodstruve0: np.ufunc
+itstruve0: np.ufunc
+iv: np.ufunc
+ive: np.ufunc
+j0: np.ufunc
+j1: np.ufunc
+jn: np.ufunc
+jv: np.ufunc
+jve: np.ufunc
+k0: np.ufunc
+k0e: np.ufunc
+k1: np.ufunc
+k1e: np.ufunc
+kei: np.ufunc
+keip: np.ufunc
+kelvin: np.ufunc
+ker: np.ufunc
+kerp: np.ufunc
+kl_div: np.ufunc
+kn: np.ufunc
+kolmogi: np.ufunc
+kolmogorov: np.ufunc
+kv: np.ufunc
+kve: np.ufunc
+log1p: np.ufunc
+log_expit: np.ufunc
+log_ndtr: np.ufunc
+log_wright_bessel: np.ufunc
+loggamma: np.ufunc
+logit: np.ufunc
+lpmv: np.ufunc
+mathieu_a: np.ufunc
+mathieu_b: np.ufunc
+mathieu_cem: np.ufunc
+mathieu_modcem1: np.ufunc
+mathieu_modcem2: np.ufunc
+mathieu_modsem1: np.ufunc
+mathieu_modsem2: np.ufunc
+mathieu_sem: np.ufunc
+modfresnelm: np.ufunc
+modfresnelp: np.ufunc
+modstruve: np.ufunc
+nbdtr: np.ufunc
+nbdtrc: np.ufunc
+nbdtri: np.ufunc
+nbdtrik: np.ufunc
+nbdtrin: np.ufunc
+ncfdtr: np.ufunc
+ncfdtri: np.ufunc
+ncfdtridfd: np.ufunc
+ncfdtridfn: np.ufunc
+ncfdtrinc: np.ufunc
+nctdtr: np.ufunc
+nctdtridf: np.ufunc
+nctdtrinc: np.ufunc
+nctdtrit: np.ufunc
+ndtr: np.ufunc
+ndtri: np.ufunc
+ndtri_exp: np.ufunc
+nrdtrimn: np.ufunc
+nrdtrisd: np.ufunc
+obl_ang1: np.ufunc
+obl_ang1_cv: np.ufunc
+obl_cv: np.ufunc
+obl_rad1: np.ufunc
+obl_rad1_cv: np.ufunc
+obl_rad2: np.ufunc
+obl_rad2_cv: np.ufunc
+owens_t: np.ufunc
+pbdv: np.ufunc
+pbvv: np.ufunc
+pbwa: np.ufunc
+pdtr: np.ufunc
+pdtrc: np.ufunc
+pdtri: np.ufunc
+pdtrik: np.ufunc
+poch: np.ufunc
+powm1: np.ufunc
+pro_ang1: np.ufunc
+pro_ang1_cv: np.ufunc
+pro_cv: np.ufunc
+pro_rad1: np.ufunc
+pro_rad1_cv: np.ufunc
+pro_rad2: np.ufunc
+pro_rad2_cv: np.ufunc
+pseudo_huber: np.ufunc
+psi: np.ufunc
+radian: np.ufunc
+rel_entr: np.ufunc
+rgamma: np.ufunc
+round: np.ufunc
+shichi: np.ufunc
+sici: np.ufunc
+sindg: np.ufunc
+smirnov: np.ufunc
+smirnovi: np.ufunc
+spence: np.ufunc
+sph_harm: np.ufunc
+stdtr: np.ufunc
+stdtridf: np.ufunc
+stdtrit: np.ufunc
+struve: np.ufunc
+tandg: np.ufunc
+tklmbda: np.ufunc
+voigt_profile: np.ufunc
+wofz: np.ufunc
+wright_bessel: np.ufunc
+wrightomega: np.ufunc
+xlog1py: np.ufunc
+xlogy: np.ufunc
+y0: np.ufunc
+y1: np.ufunc
+yn: np.ufunc
+yv: np.ufunc
+yve: np.ufunc
+zetac: np.ufunc
+
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..5f9afc828a16d598b3ba76582111cd964cfe764a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx
@@ -0,0 +1,14358 @@
+# This file is automatically generated by _generate_pyx.py.
+# Do not edit manually!
+
+from libc.math cimport NAN
+
+include "_ufuncs_extra_code_common.pxi"
+include "_ufuncs_extra_code.pxi"
+__all__ = ['agm', 'bdtr', 'bdtrc', 'bdtri', 'bdtrik', 'bdtrin', 'betainc', 'betaincc', 'betainccinv', 'betaincinv', 'boxcox', 'boxcox1p', 'btdtria', 'btdtrib', 'chdtr', 'chdtrc', 'chdtri', 'chdtriv', 'chndtr', 'chndtridf', 'chndtrinc', 'chndtrix', 'dawsn', 'elliprc', 'elliprd', 'elliprf', 'elliprg', 'elliprj', 'entr', 'erf', 'erfc', 'erfcinv', 'erfcx', 'erfi', 'erfinv', 'eval_chebyc', 'eval_chebys', 'eval_chebyt', 'eval_chebyu', 'eval_gegenbauer', 'eval_genlaguerre', 'eval_hermite', 'eval_hermitenorm', 'eval_jacobi', 'eval_laguerre', 'eval_legendre', 'eval_sh_chebyt', 'eval_sh_chebyu', 'eval_sh_jacobi', 'eval_sh_legendre', 'exp10', 'exp2', 'expm1', 'expn', 'fdtr', 'fdtrc', 'fdtri', 'fdtridfd', 'gdtr', 'gdtrc', 'gdtria', 'gdtrib', 'gdtrix', 'huber', 'hyp0f1', 'hyp1f1', 'hyperu', 'inv_boxcox', 'inv_boxcox1p', 'kl_div', 'kn', 'kolmogi', 'kolmogorov', 'log1p', 'log_ndtr', 'lpmv', 'nbdtr', 'nbdtrc', 'nbdtri', 'nbdtrik', 'nbdtrin', 'ncfdtr', 'ncfdtri', 'ncfdtridfd', 'ncfdtridfn', 'ncfdtrinc', 'nctdtr', 'nctdtridf', 'nctdtrinc', 'nctdtrit', 'ndtr', 'ndtri', 'ndtri_exp', 'nrdtrimn', 'nrdtrisd', 'owens_t', 'pdtr', 'pdtrc', 'pdtri', 'pdtrik', 'poch', 'powm1', 'pseudo_huber', 'rel_entr', 'round', 'shichi', 'sici', 'smirnov', 'smirnovi', 'spence', 'stdtr', 'stdtridf', 'stdtrit', 'tklmbda', 'voigt_profile', 'wofz', 'wrightomega', 'xlog1py', 'xlogy', 'yn', 'geterr', 'seterr', 'errstate', 'jn', 'airy', 'airye', 'bei', 'beip', 'ber', 'berp', 'binom', 'exp1', 'expi', 'expit', 'exprel', 'gamma', 'gammaln', 'hankel1', 'hankel1e', 'hankel2', 'hankel2e', 'hyp2f1', 'it2i0k0', 'it2j0y0', 'it2struve0', 'itairy', 'iti0k0', 'itj0y0', 'itmodstruve0', 'itstruve0', 'iv', 'ive', 'jv', 'jve', 'kei', 'keip', 'kelvin', 'ker', 'kerp', 'kv', 'kve', 'log_expit', 'log_wright_bessel', 'loggamma', 'logit', 'mathieu_a', 'mathieu_b', 'mathieu_cem', 'mathieu_modcem1', 'mathieu_modcem2', 'mathieu_modsem1', 'mathieu_modsem2', 'mathieu_sem', 'modfresnelm', 'modfresnelp', 'obl_ang1', 'obl_ang1_cv', 'obl_cv', 'obl_rad1', 'obl_rad1_cv', 'obl_rad2', 'obl_rad2_cv', 'pbdv', 'pbvv', 'pbwa', 'pro_ang1', 'pro_ang1_cv', 'pro_cv', 'pro_rad1', 'pro_rad1_cv', 'pro_rad2', 'pro_rad2_cv', 'psi', 'rgamma', 'sph_harm', 'wright_bessel', 'yv', 'yve', 'zetac', 'sindg', 'cosdg', 'tandg', 'cotdg', 'i0', 'i0e', 'i1', 'i1e', 'k0', 'k0e', 'k1', 'k1e', 'y0', 'y1', 'j0', 'j1', 'struve', 'modstruve', 'beta', 'betaln', 'besselpoly', 'gammaln', 'gammasgn', 'cbrt', 'radian', 'cosm1', 'gammainc', 'gammaincinv', 'gammaincc', 'gammainccinv', 'fresnel', 'ellipe', 'ellipeinc', 'ellipk', 'ellipkinc', 'ellipkm1', 'ellipj']
+cdef void loop_D_DDDD__As_DDDD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDDD__As_FFFF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDD__As_DDD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDD__As_FFF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DD__As_DD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DD__As_FF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_D__As_D_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_D__As_F_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dD__As_dD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dD__As_fF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_ddD__As_ddD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_ddD__As_ffF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dddD__As_dddD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dddD__As_fffF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_d__As_d_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_d__As_f_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dd__As_dd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dd__As_ff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddd__As_ddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddd__As_fff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dddd__As_dddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dddd__As_ffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddddddd__As_ddddddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddddddd__As_fffffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddiiddd__As_ddllddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        if (ip2)[0] == (ip2)[0] and (ip3)[0] == (ip3)[0]:
+            ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        else:
+            sf_error.error(func_name, sf_error.DOMAIN, "invalid input argument")
+            ov0 = NAN
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddp_d_As_ddp_dd(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef char *op1 = args[4]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+        op1 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dpd__As_dpd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pd__As_pd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pdd__As_pdd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pddd__As_pddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ppd__As_ppd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_f__As_f_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_ff__As_ff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_fff__As_fff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_ffff__As_ffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_D_DD_As_D_DD(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double complex ov0
+    cdef double complex ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_D_DD_As_F_FF(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double complex ov0
+    cdef double complex ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_d_dd_As_d_dd(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_d_dd_As_f_ff(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_i__As_l_l(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef int ov0
+    for i in range(n):
+        if (ip0)[0] == (ip0)[0]:
+            ov0 = (func)((ip0)[0])
+        else:
+            sf_error.error(func_name, sf_error.DOMAIN, "invalid input argument")
+            ov0 = 0xbad0bad0
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cosine_cdf "cosine_cdf"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cosine_invcdf "cosine_invcdf"(double) noexcept nogil
+from ._ellip_harm cimport ellip_harmonic as _func_ellip_harmonic
+ctypedef double _proto_ellip_harmonic_t(double, double, int, int, double, double, double) noexcept nogil
+cdef _proto_ellip_harmonic_t *_proto_ellip_harmonic_t_var = &_func_ellip_harmonic
+from ._legacy cimport ellip_harmonic_unsafe as _func_ellip_harmonic_unsafe
+ctypedef double _proto_ellip_harmonic_unsafe_t(double, double, double, double, double, double, double) noexcept nogil
+cdef _proto_ellip_harmonic_unsafe_t *_proto_ellip_harmonic_unsafe_t_var = &_func_ellip_harmonic_unsafe
+from ._factorial cimport _factorial as _func__factorial
+ctypedef double _proto__factorial_t(double) noexcept nogil
+cdef _proto__factorial_t *_proto__factorial_t_var = &_func__factorial
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_igam_fac "cephes_igam_fac"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogc "xsf_kolmogc"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogci "xsf_kolmogci"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogp "xsf_kolmogp"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_lanczos_sum_expg_scaled "cephes_lanczos_sum_expg_scaled"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_lgam1p "cephes_lgam1p"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_log1pmx "cephes_log1pmx"(double) noexcept nogil
+from .sf_error cimport _sf_error_test_function as _func__sf_error_test_function
+ctypedef int _proto__sf_error_test_function_t(int) noexcept nogil
+cdef _proto__sf_error_test_function_t *_proto__sf_error_test_function_t_var = &_func__sf_error_test_function
+from ._legacy cimport smirnovc_unsafe as _func_smirnovc_unsafe
+ctypedef double _proto_smirnovc_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovc_unsafe_t *_proto_smirnovc_unsafe_t_var = &_func_smirnovc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovc_wrap "cephes_smirnovc_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovci_unsafe as _func_smirnovci_unsafe
+ctypedef double _proto_smirnovci_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovci_unsafe_t *_proto_smirnovci_unsafe_t_var = &_func_smirnovci_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovci_wrap "cephes_smirnovci_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovp_unsafe as _func_smirnovp_unsafe
+ctypedef double _proto_smirnovp_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovp_unsafe_t *_proto_smirnovp_unsafe_t_var = &_func_smirnovp_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovp_wrap "cephes_smirnovp_wrap"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_asymp_large_z "cephes__struve_asymp_large_z"(double, double, Py_ssize_t, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_bessel_series "cephes__struve_bessel_series"(double, double, Py_ssize_t, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_power_series "cephes__struve_power_series"(double, double, Py_ssize_t, double *) noexcept nogil
+from ._agm cimport agm as _func_agm
+ctypedef double _proto_agm_t(double, double) noexcept nogil
+cdef _proto_agm_t *_proto_agm_t_var = &_func_agm
+from ._legacy cimport bdtr_unsafe as _func_bdtr_unsafe
+ctypedef double _proto_bdtr_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtr_unsafe_t *_proto_bdtr_unsafe_t_var = &_func_bdtr_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtr_wrap "cephes_bdtr_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport bdtrc_unsafe as _func_bdtrc_unsafe
+ctypedef double _proto_bdtrc_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtrc_unsafe_t *_proto_bdtrc_unsafe_t_var = &_func_bdtrc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtrc_wrap "cephes_bdtrc_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport bdtri_unsafe as _func_bdtri_unsafe
+ctypedef double _proto_bdtri_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtri_unsafe_t *_proto_bdtri_unsafe_t_var = &_func_bdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtri_wrap "cephes_bdtri_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport bdtrik as _func_bdtrik
+ctypedef double _proto_bdtrik_t(double, double, double) noexcept nogil
+cdef _proto_bdtrik_t *_proto_bdtrik_t_var = &_func_bdtrik
+from ._cdflib_wrappers cimport bdtrin as _func_bdtrin
+ctypedef double _proto_bdtrin_t(double, double, double) noexcept nogil
+cdef _proto_bdtrin_t *_proto_bdtrin_t_var = &_func_bdtrin
+from ._boxcox cimport boxcox as _func_boxcox
+ctypedef double _proto_boxcox_t(double, double) noexcept nogil
+cdef _proto_boxcox_t *_proto_boxcox_t_var = &_func_boxcox
+from ._boxcox cimport boxcox1p as _func_boxcox1p
+ctypedef double _proto_boxcox1p_t(double, double) noexcept nogil
+cdef _proto_boxcox1p_t *_proto_boxcox1p_t_var = &_func_boxcox1p
+from ._cdflib_wrappers cimport btdtria as _func_btdtria
+ctypedef double _proto_btdtria_t(double, double, double) noexcept nogil
+cdef _proto_btdtria_t *_proto_btdtria_t_var = &_func_btdtria
+from ._cdflib_wrappers cimport btdtrib as _func_btdtrib
+ctypedef double _proto_btdtrib_t(double, double, double) noexcept nogil
+cdef _proto_btdtrib_t *_proto_btdtrib_t_var = &_func_btdtrib
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtr "xsf_chdtr"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtrc "xsf_chdtrc"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtri "xsf_chdtri"(double, double) noexcept nogil
+from ._cdflib_wrappers cimport chdtriv as _func_chdtriv
+ctypedef double _proto_chdtriv_t(double, double) noexcept nogil
+cdef _proto_chdtriv_t *_proto_chdtriv_t_var = &_func_chdtriv
+from ._cdflib_wrappers cimport chndtr as _func_chndtr
+ctypedef double _proto_chndtr_t(double, double, double) noexcept nogil
+cdef _proto_chndtr_t *_proto_chndtr_t_var = &_func_chndtr
+from ._cdflib_wrappers cimport chndtridf as _func_chndtridf
+ctypedef double _proto_chndtridf_t(double, double, double) noexcept nogil
+cdef _proto_chndtridf_t *_proto_chndtridf_t_var = &_func_chndtridf
+from ._cdflib_wrappers cimport chndtrinc as _func_chndtrinc
+ctypedef double _proto_chndtrinc_t(double, double, double) noexcept nogil
+cdef _proto_chndtrinc_t *_proto_chndtrinc_t_var = &_func_chndtrinc
+from ._cdflib_wrappers cimport chndtrix as _func_chndtrix
+ctypedef double _proto_chndtrix_t(double, double, double) noexcept nogil
+cdef _proto_chndtrix_t *_proto_chndtrix_t_var = &_func_chndtrix
+from ._convex_analysis cimport entr as _func_entr
+ctypedef double _proto_entr_t(double) noexcept nogil
+cdef _proto_entr_t *_proto_entr_t_var = &_func_entr
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erf "cephes_erf"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erfc "cephes_erfc"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erfcinv "cephes_erfcinv"(double) noexcept nogil
+from .orthogonal_eval cimport eval_chebyc as _func_eval_chebyc
+ctypedef double complex _proto_eval_chebyc_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyc_double_complex__t *_proto_eval_chebyc_double_complex__t_var = &_func_eval_chebyc[double_complex]
+from .orthogonal_eval cimport eval_chebyc as _func_eval_chebyc
+ctypedef double _proto_eval_chebyc_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyc_double__t *_proto_eval_chebyc_double__t_var = &_func_eval_chebyc[double]
+from .orthogonal_eval cimport eval_chebyc_l as _func_eval_chebyc_l
+ctypedef double _proto_eval_chebyc_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyc_l_t *_proto_eval_chebyc_l_t_var = &_func_eval_chebyc_l
+from .orthogonal_eval cimport eval_chebys as _func_eval_chebys
+ctypedef double complex _proto_eval_chebys_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebys_double_complex__t *_proto_eval_chebys_double_complex__t_var = &_func_eval_chebys[double_complex]
+from .orthogonal_eval cimport eval_chebys as _func_eval_chebys
+ctypedef double _proto_eval_chebys_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebys_double__t *_proto_eval_chebys_double__t_var = &_func_eval_chebys[double]
+from .orthogonal_eval cimport eval_chebys_l as _func_eval_chebys_l
+ctypedef double _proto_eval_chebys_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebys_l_t *_proto_eval_chebys_l_t_var = &_func_eval_chebys_l
+from .orthogonal_eval cimport eval_chebyt as _func_eval_chebyt
+ctypedef double complex _proto_eval_chebyt_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyt_double_complex__t *_proto_eval_chebyt_double_complex__t_var = &_func_eval_chebyt[double_complex]
+from .orthogonal_eval cimport eval_chebyt as _func_eval_chebyt
+ctypedef double _proto_eval_chebyt_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyt_double__t *_proto_eval_chebyt_double__t_var = &_func_eval_chebyt[double]
+from .orthogonal_eval cimport eval_chebyt_l as _func_eval_chebyt_l
+ctypedef double _proto_eval_chebyt_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyt_l_t *_proto_eval_chebyt_l_t_var = &_func_eval_chebyt_l
+from .orthogonal_eval cimport eval_chebyu as _func_eval_chebyu
+ctypedef double complex _proto_eval_chebyu_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyu_double_complex__t *_proto_eval_chebyu_double_complex__t_var = &_func_eval_chebyu[double_complex]
+from .orthogonal_eval cimport eval_chebyu as _func_eval_chebyu
+ctypedef double _proto_eval_chebyu_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyu_double__t *_proto_eval_chebyu_double__t_var = &_func_eval_chebyu[double]
+from .orthogonal_eval cimport eval_chebyu_l as _func_eval_chebyu_l
+ctypedef double _proto_eval_chebyu_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyu_l_t *_proto_eval_chebyu_l_t_var = &_func_eval_chebyu_l
+from .orthogonal_eval cimport eval_gegenbauer as _func_eval_gegenbauer
+ctypedef double complex _proto_eval_gegenbauer_double_complex__t(double, double, double complex) noexcept nogil
+cdef _proto_eval_gegenbauer_double_complex__t *_proto_eval_gegenbauer_double_complex__t_var = &_func_eval_gegenbauer[double_complex]
+from .orthogonal_eval cimport eval_gegenbauer as _func_eval_gegenbauer
+ctypedef double _proto_eval_gegenbauer_double__t(double, double, double) noexcept nogil
+cdef _proto_eval_gegenbauer_double__t *_proto_eval_gegenbauer_double__t_var = &_func_eval_gegenbauer[double]
+from .orthogonal_eval cimport eval_gegenbauer_l as _func_eval_gegenbauer_l
+ctypedef double _proto_eval_gegenbauer_l_t(Py_ssize_t, double, double) noexcept nogil
+cdef _proto_eval_gegenbauer_l_t *_proto_eval_gegenbauer_l_t_var = &_func_eval_gegenbauer_l
+from .orthogonal_eval cimport eval_genlaguerre as _func_eval_genlaguerre
+ctypedef double complex _proto_eval_genlaguerre_double_complex__t(double, double, double complex) noexcept nogil
+cdef _proto_eval_genlaguerre_double_complex__t *_proto_eval_genlaguerre_double_complex__t_var = &_func_eval_genlaguerre[double_complex]
+from .orthogonal_eval cimport eval_genlaguerre as _func_eval_genlaguerre
+ctypedef double _proto_eval_genlaguerre_double__t(double, double, double) noexcept nogil
+cdef _proto_eval_genlaguerre_double__t *_proto_eval_genlaguerre_double__t_var = &_func_eval_genlaguerre[double]
+from .orthogonal_eval cimport eval_genlaguerre_l as _func_eval_genlaguerre_l
+ctypedef double _proto_eval_genlaguerre_l_t(Py_ssize_t, double, double) noexcept nogil
+cdef _proto_eval_genlaguerre_l_t *_proto_eval_genlaguerre_l_t_var = &_func_eval_genlaguerre_l
+from .orthogonal_eval cimport eval_hermite as _func_eval_hermite
+ctypedef double _proto_eval_hermite_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_hermite_t *_proto_eval_hermite_t_var = &_func_eval_hermite
+from .orthogonal_eval cimport eval_hermitenorm as _func_eval_hermitenorm
+ctypedef double _proto_eval_hermitenorm_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_hermitenorm_t *_proto_eval_hermitenorm_t_var = &_func_eval_hermitenorm
+from .orthogonal_eval cimport eval_jacobi as _func_eval_jacobi
+ctypedef double complex _proto_eval_jacobi_double_complex__t(double, double, double, double complex) noexcept nogil
+cdef _proto_eval_jacobi_double_complex__t *_proto_eval_jacobi_double_complex__t_var = &_func_eval_jacobi[double_complex]
+from .orthogonal_eval cimport eval_jacobi as _func_eval_jacobi
+ctypedef double _proto_eval_jacobi_double__t(double, double, double, double) noexcept nogil
+cdef _proto_eval_jacobi_double__t *_proto_eval_jacobi_double__t_var = &_func_eval_jacobi[double]
+from .orthogonal_eval cimport eval_jacobi_l as _func_eval_jacobi_l
+ctypedef double _proto_eval_jacobi_l_t(Py_ssize_t, double, double, double) noexcept nogil
+cdef _proto_eval_jacobi_l_t *_proto_eval_jacobi_l_t_var = &_func_eval_jacobi_l
+from .orthogonal_eval cimport eval_laguerre as _func_eval_laguerre
+ctypedef double complex _proto_eval_laguerre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_laguerre_double_complex__t *_proto_eval_laguerre_double_complex__t_var = &_func_eval_laguerre[double_complex]
+from .orthogonal_eval cimport eval_laguerre as _func_eval_laguerre
+ctypedef double _proto_eval_laguerre_double__t(double, double) noexcept nogil
+cdef _proto_eval_laguerre_double__t *_proto_eval_laguerre_double__t_var = &_func_eval_laguerre[double]
+from .orthogonal_eval cimport eval_laguerre_l as _func_eval_laguerre_l
+ctypedef double _proto_eval_laguerre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_laguerre_l_t *_proto_eval_laguerre_l_t_var = &_func_eval_laguerre_l
+from .orthogonal_eval cimport eval_legendre as _func_eval_legendre
+ctypedef double complex _proto_eval_legendre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_legendre_double_complex__t *_proto_eval_legendre_double_complex__t_var = &_func_eval_legendre[double_complex]
+from .orthogonal_eval cimport eval_legendre as _func_eval_legendre
+ctypedef double _proto_eval_legendre_double__t(double, double) noexcept nogil
+cdef _proto_eval_legendre_double__t *_proto_eval_legendre_double__t_var = &_func_eval_legendre[double]
+from .orthogonal_eval cimport eval_legendre_l as _func_eval_legendre_l
+ctypedef double _proto_eval_legendre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_legendre_l_t *_proto_eval_legendre_l_t_var = &_func_eval_legendre_l
+from .orthogonal_eval cimport eval_sh_chebyt as _func_eval_sh_chebyt
+ctypedef double complex _proto_eval_sh_chebyt_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_chebyt_double_complex__t *_proto_eval_sh_chebyt_double_complex__t_var = &_func_eval_sh_chebyt[double_complex]
+from .orthogonal_eval cimport eval_sh_chebyt as _func_eval_sh_chebyt
+ctypedef double _proto_eval_sh_chebyt_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_chebyt_double__t *_proto_eval_sh_chebyt_double__t_var = &_func_eval_sh_chebyt[double]
+from .orthogonal_eval cimport eval_sh_chebyt_l as _func_eval_sh_chebyt_l
+ctypedef double _proto_eval_sh_chebyt_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_chebyt_l_t *_proto_eval_sh_chebyt_l_t_var = &_func_eval_sh_chebyt_l
+from .orthogonal_eval cimport eval_sh_chebyu as _func_eval_sh_chebyu
+ctypedef double complex _proto_eval_sh_chebyu_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_chebyu_double_complex__t *_proto_eval_sh_chebyu_double_complex__t_var = &_func_eval_sh_chebyu[double_complex]
+from .orthogonal_eval cimport eval_sh_chebyu as _func_eval_sh_chebyu
+ctypedef double _proto_eval_sh_chebyu_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_chebyu_double__t *_proto_eval_sh_chebyu_double__t_var = &_func_eval_sh_chebyu[double]
+from .orthogonal_eval cimport eval_sh_chebyu_l as _func_eval_sh_chebyu_l
+ctypedef double _proto_eval_sh_chebyu_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_chebyu_l_t *_proto_eval_sh_chebyu_l_t_var = &_func_eval_sh_chebyu_l
+from .orthogonal_eval cimport eval_sh_jacobi as _func_eval_sh_jacobi
+ctypedef double complex _proto_eval_sh_jacobi_double_complex__t(double, double, double, double complex) noexcept nogil
+cdef _proto_eval_sh_jacobi_double_complex__t *_proto_eval_sh_jacobi_double_complex__t_var = &_func_eval_sh_jacobi[double_complex]
+from .orthogonal_eval cimport eval_sh_jacobi as _func_eval_sh_jacobi
+ctypedef double _proto_eval_sh_jacobi_double__t(double, double, double, double) noexcept nogil
+cdef _proto_eval_sh_jacobi_double__t *_proto_eval_sh_jacobi_double__t_var = &_func_eval_sh_jacobi[double]
+from .orthogonal_eval cimport eval_sh_jacobi_l as _func_eval_sh_jacobi_l
+ctypedef double _proto_eval_sh_jacobi_l_t(Py_ssize_t, double, double, double) noexcept nogil
+cdef _proto_eval_sh_jacobi_l_t *_proto_eval_sh_jacobi_l_t_var = &_func_eval_sh_jacobi_l
+from .orthogonal_eval cimport eval_sh_legendre as _func_eval_sh_legendre
+ctypedef double complex _proto_eval_sh_legendre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_legendre_double_complex__t *_proto_eval_sh_legendre_double_complex__t_var = &_func_eval_sh_legendre[double_complex]
+from .orthogonal_eval cimport eval_sh_legendre as _func_eval_sh_legendre
+ctypedef double _proto_eval_sh_legendre_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_legendre_double__t *_proto_eval_sh_legendre_double__t_var = &_func_eval_sh_legendre[double]
+from .orthogonal_eval cimport eval_sh_legendre_l as _func_eval_sh_legendre_l
+ctypedef double _proto_eval_sh_legendre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_legendre_l_t *_proto_eval_sh_legendre_l_t_var = &_func_eval_sh_legendre_l
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_exp10 "cephes_exp10"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_exp2 "cephes_exp2"(double) noexcept nogil
+from ._cunity cimport cexpm1 as _func_cexpm1
+ctypedef double complex _proto_cexpm1_t(double complex) noexcept nogil
+cdef _proto_cexpm1_t *_proto_cexpm1_t_var = &_func_cexpm1
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_expm1 "cephes_expm1"(double) noexcept nogil
+from ._legacy cimport expn_unsafe as _func_expn_unsafe
+ctypedef double _proto_expn_unsafe_t(double, double) noexcept nogil
+cdef _proto_expn_unsafe_t *_proto_expn_unsafe_t_var = &_func_expn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_expn_wrap "cephes_expn_wrap"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtr "xsf_fdtr"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtrc "xsf_fdtrc"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtri "xsf_fdtri"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport fdtridfd as _func_fdtridfd
+ctypedef double _proto_fdtridfd_t(double, double, double) noexcept nogil
+cdef _proto_fdtridfd_t *_proto_fdtridfd_t_var = &_func_fdtridfd
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtr "xsf_gdtr"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtrc "xsf_gdtrc"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport gdtria as _func_gdtria
+ctypedef double _proto_gdtria_t(double, double, double) noexcept nogil
+cdef _proto_gdtria_t *_proto_gdtria_t_var = &_func_gdtria
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtrib "xsf_gdtrib"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport gdtrix as _func_gdtrix
+ctypedef double _proto_gdtrix_t(double, double, double) noexcept nogil
+cdef _proto_gdtrix_t *_proto_gdtrix_t_var = &_func_gdtrix
+from ._convex_analysis cimport huber as _func_huber
+ctypedef double _proto_huber_t(double, double) noexcept nogil
+cdef _proto_huber_t *_proto_huber_t_var = &_func_huber
+from ._hyp0f1 cimport _hyp0f1_cmplx as _func__hyp0f1_cmplx
+ctypedef double complex _proto__hyp0f1_cmplx_t(double, double complex) noexcept nogil
+cdef _proto__hyp0f1_cmplx_t *_proto__hyp0f1_cmplx_t_var = &_func__hyp0f1_cmplx
+from ._hyp0f1 cimport _hyp0f1_real as _func__hyp0f1_real
+ctypedef double _proto__hyp0f1_real_t(double, double) noexcept nogil
+cdef _proto__hyp0f1_real_t *_proto__hyp0f1_real_t_var = &_func__hyp0f1_real
+cdef extern from r"_ufuncs_defs.h":
+    cdef double complex _func_chyp1f1_wrap "chyp1f1_wrap"(double, double, double complex) noexcept nogil
+from ._hypergeometric cimport hyperu as _func_hyperu
+ctypedef double _proto_hyperu_t(double, double, double) noexcept nogil
+cdef _proto_hyperu_t *_proto_hyperu_t_var = &_func_hyperu
+from ._boxcox cimport inv_boxcox as _func_inv_boxcox
+ctypedef double _proto_inv_boxcox_t(double, double) noexcept nogil
+cdef _proto_inv_boxcox_t *_proto_inv_boxcox_t_var = &_func_inv_boxcox
+from ._boxcox cimport inv_boxcox1p as _func_inv_boxcox1p
+ctypedef double _proto_inv_boxcox1p_t(double, double) noexcept nogil
+cdef _proto_inv_boxcox1p_t *_proto_inv_boxcox1p_t_var = &_func_inv_boxcox1p
+from ._convex_analysis cimport kl_div as _func_kl_div
+ctypedef double _proto_kl_div_t(double, double) noexcept nogil
+cdef _proto_kl_div_t *_proto_kl_div_t_var = &_func_kl_div
+from ._legacy cimport kn_unsafe as _func_kn_unsafe
+ctypedef double _proto_kn_unsafe_t(double, double) noexcept nogil
+cdef _proto_kn_unsafe_t *_proto_kn_unsafe_t_var = &_func_kn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_special_cyl_bessel_k_int "special_cyl_bessel_k_int"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogi "xsf_kolmogi"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogorov "xsf_kolmogorov"(double) noexcept nogil
+from ._cunity cimport clog1p as _func_clog1p
+ctypedef double complex _proto_clog1p_t(double complex) noexcept nogil
+cdef _proto_clog1p_t *_proto_clog1p_t_var = &_func_clog1p
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_log1p "cephes_log1p"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_pmv_wrap "pmv_wrap"(double, double, double) noexcept nogil
+from ._legacy cimport nbdtr_unsafe as _func_nbdtr_unsafe
+ctypedef double _proto_nbdtr_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtr_unsafe_t *_proto_nbdtr_unsafe_t_var = &_func_nbdtr_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtr_wrap "cephes_nbdtr_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport nbdtrc_unsafe as _func_nbdtrc_unsafe
+ctypedef double _proto_nbdtrc_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrc_unsafe_t *_proto_nbdtrc_unsafe_t_var = &_func_nbdtrc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtrc_wrap "cephes_nbdtrc_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport nbdtri_unsafe as _func_nbdtri_unsafe
+ctypedef double _proto_nbdtri_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtri_unsafe_t *_proto_nbdtri_unsafe_t_var = &_func_nbdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtri_wrap "cephes_nbdtri_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport nbdtrik as _func_nbdtrik
+ctypedef double _proto_nbdtrik_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrik_t *_proto_nbdtrik_t_var = &_func_nbdtrik
+from ._cdflib_wrappers cimport nbdtrin as _func_nbdtrin
+ctypedef double _proto_nbdtrin_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrin_t *_proto_nbdtrin_t_var = &_func_nbdtrin
+from ._cdflib_wrappers cimport ncfdtridfd as _func_ncfdtridfd
+ctypedef double _proto_ncfdtridfd_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtridfd_t *_proto_ncfdtridfd_t_var = &_func_ncfdtridfd
+from ._cdflib_wrappers cimport ncfdtridfn as _func_ncfdtridfn
+ctypedef double _proto_ncfdtridfn_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtridfn_t *_proto_ncfdtridfn_t_var = &_func_ncfdtridfn
+from ._cdflib_wrappers cimport ncfdtrinc as _func_ncfdtrinc
+ctypedef double _proto_ncfdtrinc_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtrinc_t *_proto_ncfdtrinc_t_var = &_func_ncfdtrinc
+from ._cdflib_wrappers cimport nctdtridf as _func_nctdtridf
+ctypedef double _proto_nctdtridf_t(double, double, double) noexcept nogil
+cdef _proto_nctdtridf_t *_proto_nctdtridf_t_var = &_func_nctdtridf
+from ._cdflib_wrappers cimport nctdtrinc as _func_nctdtrinc
+ctypedef double _proto_nctdtrinc_t(double, double, double) noexcept nogil
+cdef _proto_nctdtrinc_t *_proto_nctdtrinc_t_var = &_func_nctdtrinc
+from ._cdflib_wrappers cimport nctdtrit as _func_nctdtrit
+ctypedef double _proto_nctdtrit_t(double, double, double) noexcept nogil
+cdef _proto_nctdtrit_t *_proto_nctdtrit_t_var = &_func_nctdtrit
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_ndtr "xsf_ndtr"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_ndtri "xsf_ndtri"(double) noexcept nogil
+from ._ndtri_exp cimport ndtri_exp as _func_ndtri_exp
+ctypedef double _proto_ndtri_exp_t(double) noexcept nogil
+cdef _proto_ndtri_exp_t *_proto_ndtri_exp_t_var = &_func_ndtri_exp
+from ._cdflib_wrappers cimport nrdtrimn as _func_nrdtrimn
+ctypedef double _proto_nrdtrimn_t(double, double, double) noexcept nogil
+cdef _proto_nrdtrimn_t *_proto_nrdtrimn_t_var = &_func_nrdtrimn
+from ._cdflib_wrappers cimport nrdtrisd as _func_nrdtrisd
+ctypedef double _proto_nrdtrisd_t(double, double, double) noexcept nogil
+cdef _proto_nrdtrisd_t *_proto_nrdtrisd_t_var = &_func_nrdtrisd
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_owens_t "xsf_owens_t"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_pdtr "xsf_pdtr"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_pdtrc "xsf_pdtrc"(double, double) noexcept nogil
+from ._legacy cimport pdtri_unsafe as _func_pdtri_unsafe
+ctypedef double _proto_pdtri_unsafe_t(double, double) noexcept nogil
+cdef _proto_pdtri_unsafe_t *_proto_pdtri_unsafe_t_var = &_func_pdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_pdtri_wrap "cephes_pdtri_wrap"(Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport pdtrik as _func_pdtrik
+ctypedef double _proto_pdtrik_t(double, double) noexcept nogil
+cdef _proto_pdtrik_t *_proto_pdtrik_t_var = &_func_pdtrik
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_poch "cephes_poch"(double, double) noexcept nogil
+from ._convex_analysis cimport pseudo_huber as _func_pseudo_huber
+ctypedef double _proto_pseudo_huber_t(double, double) noexcept nogil
+cdef _proto_pseudo_huber_t *_proto_pseudo_huber_t_var = &_func_pseudo_huber
+from ._convex_analysis cimport rel_entr as _func_rel_entr
+ctypedef double _proto_rel_entr_t(double, double) noexcept nogil
+cdef _proto_rel_entr_t *_proto_rel_entr_t_var = &_func_rel_entr
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_round "cephes_round"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_cshichi "xsf_cshichi"(double complex, double complex *, double complex *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_shichi "xsf_shichi"(double, double *, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_csici "xsf_csici"(double complex, double complex *, double complex *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_sici "xsf_sici"(double, double *, double *) noexcept nogil
+from ._legacy cimport smirnov_unsafe as _func_smirnov_unsafe
+ctypedef double _proto_smirnov_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnov_unsafe_t *_proto_smirnov_unsafe_t_var = &_func_smirnov_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnov_wrap "cephes_smirnov_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovi_unsafe as _func_smirnovi_unsafe
+ctypedef double _proto_smirnovi_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovi_unsafe_t *_proto_smirnovi_unsafe_t_var = &_func_smirnovi_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovi_wrap "cephes_smirnovi_wrap"(Py_ssize_t, double) noexcept nogil
+from ._spence cimport cspence as _func_cspence
+ctypedef double complex _proto_cspence_t(double complex) noexcept nogil
+cdef _proto_cspence_t *_proto_cspence_t_var = &_func_cspence
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_spence "cephes_spence"(double) noexcept nogil
+from ._cdflib_wrappers cimport stdtr as _func_stdtr
+ctypedef double _proto_stdtr_t(double, double) noexcept nogil
+cdef _proto_stdtr_t *_proto_stdtr_t_var = &_func_stdtr
+from ._cdflib_wrappers cimport stdtridf as _func_stdtridf
+ctypedef double _proto_stdtridf_t(double, double) noexcept nogil
+cdef _proto_stdtridf_t *_proto_stdtridf_t_var = &_func_stdtridf
+from ._cdflib_wrappers cimport stdtrit as _func_stdtrit
+ctypedef double _proto_stdtrit_t(double, double) noexcept nogil
+cdef _proto_stdtrit_t *_proto_stdtrit_t_var = &_func_stdtrit
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_tukeylambdacdf "xsf_tukeylambdacdf"(double, double) noexcept nogil
+from ._xlogy cimport xlog1py as _func_xlog1py
+ctypedef double _proto_xlog1py_double__t(double, double) noexcept nogil
+cdef _proto_xlog1py_double__t *_proto_xlog1py_double__t_var = &_func_xlog1py[double]
+from ._xlogy cimport xlog1py as _func_xlog1py
+ctypedef double complex _proto_xlog1py_double_complex__t(double complex, double complex) noexcept nogil
+cdef _proto_xlog1py_double_complex__t *_proto_xlog1py_double_complex__t_var = &_func_xlog1py[double_complex]
+from ._xlogy cimport xlogy as _func_xlogy
+ctypedef double _proto_xlogy_double__t(double, double) noexcept nogil
+cdef _proto_xlogy_double__t *_proto_xlogy_double__t_var = &_func_xlogy[double]
+from ._xlogy cimport xlogy as _func_xlogy
+ctypedef double complex _proto_xlogy_double_complex__t(double complex, double complex) noexcept nogil
+cdef _proto_xlogy_double_complex__t *_proto_xlogy_double_complex__t_var = &_func_xlogy[double_complex]
+from ._legacy cimport yn_unsafe as _func_yn_unsafe
+ctypedef double _proto_yn_unsafe_t(double, double) noexcept nogil
+cdef _proto_yn_unsafe_t *_proto_yn_unsafe_t_var = &_func_yn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_yn_wrap "cephes_yn_wrap"(Py_ssize_t, double) noexcept nogil
+cdef np.PyUFuncGenericFunction ufunc__beta_pdf_loops[2]
+cdef void *ufunc__beta_pdf_ptr[4]
+cdef void *ufunc__beta_pdf_data[2]
+cdef char ufunc__beta_pdf_types[8]
+cdef char *ufunc__beta_pdf_doc = (
+    "_beta_pdf(x, a, b)\n"
+    "\n"
+    "Probability density function of beta distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__beta_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__beta_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__beta_pdf_types[0] = NPY_FLOAT
+ufunc__beta_pdf_types[1] = NPY_FLOAT
+ufunc__beta_pdf_types[2] = NPY_FLOAT
+ufunc__beta_pdf_types[3] = NPY_FLOAT
+ufunc__beta_pdf_types[4] = NPY_DOUBLE
+ufunc__beta_pdf_types[5] = NPY_DOUBLE
+ufunc__beta_pdf_types[6] = NPY_DOUBLE
+ufunc__beta_pdf_types[7] = NPY_DOUBLE
+ufunc__beta_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_beta_pdf_float
+ufunc__beta_pdf_ptr[2*0+1] = ("_beta_pdf")
+ufunc__beta_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_beta_pdf_double
+ufunc__beta_pdf_ptr[2*1+1] = ("_beta_pdf")
+ufunc__beta_pdf_data[0] = &ufunc__beta_pdf_ptr[2*0]
+ufunc__beta_pdf_data[1] = &ufunc__beta_pdf_ptr[2*1]
+_beta_pdf = np.PyUFunc_FromFuncAndData(ufunc__beta_pdf_loops, ufunc__beta_pdf_data, ufunc__beta_pdf_types, 2, 3, 1, 0, "_beta_pdf", ufunc__beta_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__beta_ppf_loops[2]
+cdef void *ufunc__beta_ppf_ptr[4]
+cdef void *ufunc__beta_ppf_data[2]
+cdef char ufunc__beta_ppf_types[8]
+cdef char *ufunc__beta_ppf_doc = (
+    "_beta_ppf(x, a, b)\n"
+    "\n"
+    "Percent point function of beta distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__beta_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__beta_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__beta_ppf_types[0] = NPY_FLOAT
+ufunc__beta_ppf_types[1] = NPY_FLOAT
+ufunc__beta_ppf_types[2] = NPY_FLOAT
+ufunc__beta_ppf_types[3] = NPY_FLOAT
+ufunc__beta_ppf_types[4] = NPY_DOUBLE
+ufunc__beta_ppf_types[5] = NPY_DOUBLE
+ufunc__beta_ppf_types[6] = NPY_DOUBLE
+ufunc__beta_ppf_types[7] = NPY_DOUBLE
+ufunc__beta_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_beta_ppf_float
+ufunc__beta_ppf_ptr[2*0+1] = ("_beta_ppf")
+ufunc__beta_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_beta_ppf_double
+ufunc__beta_ppf_ptr[2*1+1] = ("_beta_ppf")
+ufunc__beta_ppf_data[0] = &ufunc__beta_ppf_ptr[2*0]
+ufunc__beta_ppf_data[1] = &ufunc__beta_ppf_ptr[2*1]
+_beta_ppf = np.PyUFunc_FromFuncAndData(ufunc__beta_ppf_loops, ufunc__beta_ppf_data, ufunc__beta_ppf_types, 2, 3, 1, 0, "_beta_ppf", ufunc__beta_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_cdf_loops[2]
+cdef void *ufunc__binom_cdf_ptr[4]
+cdef void *ufunc__binom_cdf_data[2]
+cdef char ufunc__binom_cdf_types[8]
+cdef char *ufunc__binom_cdf_doc = (
+    "_binom_cdf(x, n, p)\n"
+    "\n"
+    "Cumulative density function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_cdf_types[0] = NPY_FLOAT
+ufunc__binom_cdf_types[1] = NPY_FLOAT
+ufunc__binom_cdf_types[2] = NPY_FLOAT
+ufunc__binom_cdf_types[3] = NPY_FLOAT
+ufunc__binom_cdf_types[4] = NPY_DOUBLE
+ufunc__binom_cdf_types[5] = NPY_DOUBLE
+ufunc__binom_cdf_types[6] = NPY_DOUBLE
+ufunc__binom_cdf_types[7] = NPY_DOUBLE
+ufunc__binom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_cdf_float
+ufunc__binom_cdf_ptr[2*0+1] = ("_binom_cdf")
+ufunc__binom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_cdf_double
+ufunc__binom_cdf_ptr[2*1+1] = ("_binom_cdf")
+ufunc__binom_cdf_data[0] = &ufunc__binom_cdf_ptr[2*0]
+ufunc__binom_cdf_data[1] = &ufunc__binom_cdf_ptr[2*1]
+_binom_cdf = np.PyUFunc_FromFuncAndData(ufunc__binom_cdf_loops, ufunc__binom_cdf_data, ufunc__binom_cdf_types, 2, 3, 1, 0, "_binom_cdf", ufunc__binom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_isf_loops[2]
+cdef void *ufunc__binom_isf_ptr[4]
+cdef void *ufunc__binom_isf_data[2]
+cdef char ufunc__binom_isf_types[8]
+cdef char *ufunc__binom_isf_doc = (
+    "_binom_isf(x, n, p)\n"
+    "\n"
+    "Inverse survival function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_isf_types[0] = NPY_FLOAT
+ufunc__binom_isf_types[1] = NPY_FLOAT
+ufunc__binom_isf_types[2] = NPY_FLOAT
+ufunc__binom_isf_types[3] = NPY_FLOAT
+ufunc__binom_isf_types[4] = NPY_DOUBLE
+ufunc__binom_isf_types[5] = NPY_DOUBLE
+ufunc__binom_isf_types[6] = NPY_DOUBLE
+ufunc__binom_isf_types[7] = NPY_DOUBLE
+ufunc__binom_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_isf_float
+ufunc__binom_isf_ptr[2*0+1] = ("_binom_isf")
+ufunc__binom_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_isf_double
+ufunc__binom_isf_ptr[2*1+1] = ("_binom_isf")
+ufunc__binom_isf_data[0] = &ufunc__binom_isf_ptr[2*0]
+ufunc__binom_isf_data[1] = &ufunc__binom_isf_ptr[2*1]
+_binom_isf = np.PyUFunc_FromFuncAndData(ufunc__binom_isf_loops, ufunc__binom_isf_data, ufunc__binom_isf_types, 2, 3, 1, 0, "_binom_isf", ufunc__binom_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_pmf_loops[2]
+cdef void *ufunc__binom_pmf_ptr[4]
+cdef void *ufunc__binom_pmf_data[2]
+cdef char ufunc__binom_pmf_types[8]
+cdef char *ufunc__binom_pmf_doc = (
+    "_binom_pmf(x, n, p)\n"
+    "\n"
+    "Probability mass function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_pmf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_pmf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_pmf_types[0] = NPY_FLOAT
+ufunc__binom_pmf_types[1] = NPY_FLOAT
+ufunc__binom_pmf_types[2] = NPY_FLOAT
+ufunc__binom_pmf_types[3] = NPY_FLOAT
+ufunc__binom_pmf_types[4] = NPY_DOUBLE
+ufunc__binom_pmf_types[5] = NPY_DOUBLE
+ufunc__binom_pmf_types[6] = NPY_DOUBLE
+ufunc__binom_pmf_types[7] = NPY_DOUBLE
+ufunc__binom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_pmf_float
+ufunc__binom_pmf_ptr[2*0+1] = ("_binom_pmf")
+ufunc__binom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_pmf_double
+ufunc__binom_pmf_ptr[2*1+1] = ("_binom_pmf")
+ufunc__binom_pmf_data[0] = &ufunc__binom_pmf_ptr[2*0]
+ufunc__binom_pmf_data[1] = &ufunc__binom_pmf_ptr[2*1]
+_binom_pmf = np.PyUFunc_FromFuncAndData(ufunc__binom_pmf_loops, ufunc__binom_pmf_data, ufunc__binom_pmf_types, 2, 3, 1, 0, "_binom_pmf", ufunc__binom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_ppf_loops[2]
+cdef void *ufunc__binom_ppf_ptr[4]
+cdef void *ufunc__binom_ppf_data[2]
+cdef char ufunc__binom_ppf_types[8]
+cdef char *ufunc__binom_ppf_doc = (
+    "_binom_ppf(x, n, p)\n"
+    "\n"
+    "Percent point function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_ppf_types[0] = NPY_FLOAT
+ufunc__binom_ppf_types[1] = NPY_FLOAT
+ufunc__binom_ppf_types[2] = NPY_FLOAT
+ufunc__binom_ppf_types[3] = NPY_FLOAT
+ufunc__binom_ppf_types[4] = NPY_DOUBLE
+ufunc__binom_ppf_types[5] = NPY_DOUBLE
+ufunc__binom_ppf_types[6] = NPY_DOUBLE
+ufunc__binom_ppf_types[7] = NPY_DOUBLE
+ufunc__binom_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_ppf_float
+ufunc__binom_ppf_ptr[2*0+1] = ("_binom_ppf")
+ufunc__binom_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_ppf_double
+ufunc__binom_ppf_ptr[2*1+1] = ("_binom_ppf")
+ufunc__binom_ppf_data[0] = &ufunc__binom_ppf_ptr[2*0]
+ufunc__binom_ppf_data[1] = &ufunc__binom_ppf_ptr[2*1]
+_binom_ppf = np.PyUFunc_FromFuncAndData(ufunc__binom_ppf_loops, ufunc__binom_ppf_data, ufunc__binom_ppf_types, 2, 3, 1, 0, "_binom_ppf", ufunc__binom_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_sf_loops[2]
+cdef void *ufunc__binom_sf_ptr[4]
+cdef void *ufunc__binom_sf_data[2]
+cdef char ufunc__binom_sf_types[8]
+cdef char *ufunc__binom_sf_doc = (
+    "_binom_sf(x, n, p)\n"
+    "\n"
+    "Survival function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_sf_types[0] = NPY_FLOAT
+ufunc__binom_sf_types[1] = NPY_FLOAT
+ufunc__binom_sf_types[2] = NPY_FLOAT
+ufunc__binom_sf_types[3] = NPY_FLOAT
+ufunc__binom_sf_types[4] = NPY_DOUBLE
+ufunc__binom_sf_types[5] = NPY_DOUBLE
+ufunc__binom_sf_types[6] = NPY_DOUBLE
+ufunc__binom_sf_types[7] = NPY_DOUBLE
+ufunc__binom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_sf_float
+ufunc__binom_sf_ptr[2*0+1] = ("_binom_sf")
+ufunc__binom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_sf_double
+ufunc__binom_sf_ptr[2*1+1] = ("_binom_sf")
+ufunc__binom_sf_data[0] = &ufunc__binom_sf_ptr[2*0]
+ufunc__binom_sf_data[1] = &ufunc__binom_sf_ptr[2*1]
+_binom_sf = np.PyUFunc_FromFuncAndData(ufunc__binom_sf_loops, ufunc__binom_sf_data, ufunc__binom_sf_types, 2, 3, 1, 0, "_binom_sf", ufunc__binom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cauchy_isf_loops[2]
+cdef void *ufunc__cauchy_isf_ptr[4]
+cdef void *ufunc__cauchy_isf_data[2]
+cdef char ufunc__cauchy_isf_types[8]
+cdef char *ufunc__cauchy_isf_doc = (
+    "_cauchy_isf(p, loc, scale)\n"
+    "\n"
+    "Inverse survival function of the Cauchy distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probabilities\n"
+    "loc : array_like\n"
+    "    Location parameter of the distribution.\n"
+    "scale : array_like\n"
+    "    Scale parameter of the distribution.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__cauchy_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__cauchy_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__cauchy_isf_types[0] = NPY_FLOAT
+ufunc__cauchy_isf_types[1] = NPY_FLOAT
+ufunc__cauchy_isf_types[2] = NPY_FLOAT
+ufunc__cauchy_isf_types[3] = NPY_FLOAT
+ufunc__cauchy_isf_types[4] = NPY_DOUBLE
+ufunc__cauchy_isf_types[5] = NPY_DOUBLE
+ufunc__cauchy_isf_types[6] = NPY_DOUBLE
+ufunc__cauchy_isf_types[7] = NPY_DOUBLE
+ufunc__cauchy_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_cauchy_isf_float
+ufunc__cauchy_isf_ptr[2*0+1] = ("_cauchy_isf")
+ufunc__cauchy_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_cauchy_isf_double
+ufunc__cauchy_isf_ptr[2*1+1] = ("_cauchy_isf")
+ufunc__cauchy_isf_data[0] = &ufunc__cauchy_isf_ptr[2*0]
+ufunc__cauchy_isf_data[1] = &ufunc__cauchy_isf_ptr[2*1]
+_cauchy_isf = np.PyUFunc_FromFuncAndData(ufunc__cauchy_isf_loops, ufunc__cauchy_isf_data, ufunc__cauchy_isf_types, 2, 3, 1, 0, "_cauchy_isf", ufunc__cauchy_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cauchy_ppf_loops[2]
+cdef void *ufunc__cauchy_ppf_ptr[4]
+cdef void *ufunc__cauchy_ppf_data[2]
+cdef char ufunc__cauchy_ppf_types[8]
+cdef char *ufunc__cauchy_ppf_doc = (
+    "_cauchy_ppf(p, loc, scale)\n"
+    "\n"
+    "Percent point function (i.e. quantile) of the Cauchy distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probabilities\n"
+    "loc : array_like\n"
+    "    Location parameter of the distribution.\n"
+    "scale : array_like\n"
+    "    Scale parameter of the distribution.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__cauchy_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__cauchy_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__cauchy_ppf_types[0] = NPY_FLOAT
+ufunc__cauchy_ppf_types[1] = NPY_FLOAT
+ufunc__cauchy_ppf_types[2] = NPY_FLOAT
+ufunc__cauchy_ppf_types[3] = NPY_FLOAT
+ufunc__cauchy_ppf_types[4] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[5] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[6] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[7] = NPY_DOUBLE
+ufunc__cauchy_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_cauchy_ppf_float
+ufunc__cauchy_ppf_ptr[2*0+1] = ("_cauchy_ppf")
+ufunc__cauchy_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_cauchy_ppf_double
+ufunc__cauchy_ppf_ptr[2*1+1] = ("_cauchy_ppf")
+ufunc__cauchy_ppf_data[0] = &ufunc__cauchy_ppf_ptr[2*0]
+ufunc__cauchy_ppf_data[1] = &ufunc__cauchy_ppf_ptr[2*1]
+_cauchy_ppf = np.PyUFunc_FromFuncAndData(ufunc__cauchy_ppf_loops, ufunc__cauchy_ppf_data, ufunc__cauchy_ppf_types, 2, 3, 1, 0, "_cauchy_ppf", ufunc__cauchy_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cosine_cdf_loops[2]
+cdef void *ufunc__cosine_cdf_ptr[4]
+cdef void *ufunc__cosine_cdf_data[2]
+cdef char ufunc__cosine_cdf_types[4]
+cdef char *ufunc__cosine_cdf_doc = (
+    "_cosine_cdf(x)\n"
+    "\n"
+    "Cumulative distribution function (CDF) of the cosine distribution::\n"
+    "\n"
+    "             {             0,              x < -pi\n"
+    "    cdf(x) = { (pi + x + sin(x))/(2*pi),   -pi <= x <= pi\n"
+    "             {             1,              x > pi\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The cosine distribution CDF evaluated at `x`.")
+ufunc__cosine_cdf_loops[0] = loop_d_d__As_f_f
+ufunc__cosine_cdf_loops[1] = loop_d_d__As_d_d
+ufunc__cosine_cdf_types[0] = NPY_FLOAT
+ufunc__cosine_cdf_types[1] = NPY_FLOAT
+ufunc__cosine_cdf_types[2] = NPY_DOUBLE
+ufunc__cosine_cdf_types[3] = NPY_DOUBLE
+ufunc__cosine_cdf_ptr[2*0] = _func_cosine_cdf
+ufunc__cosine_cdf_ptr[2*0+1] = ("_cosine_cdf")
+ufunc__cosine_cdf_ptr[2*1] = _func_cosine_cdf
+ufunc__cosine_cdf_ptr[2*1+1] = ("_cosine_cdf")
+ufunc__cosine_cdf_data[0] = &ufunc__cosine_cdf_ptr[2*0]
+ufunc__cosine_cdf_data[1] = &ufunc__cosine_cdf_ptr[2*1]
+_cosine_cdf = np.PyUFunc_FromFuncAndData(ufunc__cosine_cdf_loops, ufunc__cosine_cdf_data, ufunc__cosine_cdf_types, 2, 1, 1, 0, "_cosine_cdf", ufunc__cosine_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cosine_invcdf_loops[2]
+cdef void *ufunc__cosine_invcdf_ptr[4]
+cdef void *ufunc__cosine_invcdf_data[2]
+cdef char ufunc__cosine_invcdf_types[4]
+cdef char *ufunc__cosine_invcdf_doc = (
+    "_cosine_invcdf(p)\n"
+    "\n"
+    "Inverse of the cumulative distribution function (CDF) of the cosine\n"
+    "distribution.\n"
+    "\n"
+    "The CDF of the cosine distribution is::\n"
+    "\n"
+    "    cdf(x) = (pi + x + sin(x))/(2*pi)\n"
+    "\n"
+    "This function computes the inverse of cdf(x).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    `p` must contain real numbers in the interval ``0 <= p <= 1``.\n"
+    "    `nan` is returned for values of `p` outside the interval [0, 1].\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The inverse of the cosine distribution CDF evaluated at `p`.")
+ufunc__cosine_invcdf_loops[0] = loop_d_d__As_f_f
+ufunc__cosine_invcdf_loops[1] = loop_d_d__As_d_d
+ufunc__cosine_invcdf_types[0] = NPY_FLOAT
+ufunc__cosine_invcdf_types[1] = NPY_FLOAT
+ufunc__cosine_invcdf_types[2] = NPY_DOUBLE
+ufunc__cosine_invcdf_types[3] = NPY_DOUBLE
+ufunc__cosine_invcdf_ptr[2*0] = _func_cosine_invcdf
+ufunc__cosine_invcdf_ptr[2*0+1] = ("_cosine_invcdf")
+ufunc__cosine_invcdf_ptr[2*1] = _func_cosine_invcdf
+ufunc__cosine_invcdf_ptr[2*1+1] = ("_cosine_invcdf")
+ufunc__cosine_invcdf_data[0] = &ufunc__cosine_invcdf_ptr[2*0]
+ufunc__cosine_invcdf_data[1] = &ufunc__cosine_invcdf_ptr[2*1]
+_cosine_invcdf = np.PyUFunc_FromFuncAndData(ufunc__cosine_invcdf_loops, ufunc__cosine_invcdf_data, ufunc__cosine_invcdf_types, 2, 1, 1, 0, "_cosine_invcdf", ufunc__cosine_invcdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ellip_harm_loops[3]
+cdef void *ufunc__ellip_harm_ptr[6]
+cdef void *ufunc__ellip_harm_data[3]
+cdef char ufunc__ellip_harm_types[24]
+cdef char *ufunc__ellip_harm_doc = (
+    "Internal function, use `ellip_harm` instead.")
+ufunc__ellip_harm_loops[0] = loop_d_ddddddd__As_fffffff_f
+ufunc__ellip_harm_loops[1] = loop_d_ddiiddd__As_ddllddd_d
+ufunc__ellip_harm_loops[2] = loop_d_ddddddd__As_ddddddd_d
+ufunc__ellip_harm_types[0] = NPY_FLOAT
+ufunc__ellip_harm_types[1] = NPY_FLOAT
+ufunc__ellip_harm_types[2] = NPY_FLOAT
+ufunc__ellip_harm_types[3] = NPY_FLOAT
+ufunc__ellip_harm_types[4] = NPY_FLOAT
+ufunc__ellip_harm_types[5] = NPY_FLOAT
+ufunc__ellip_harm_types[6] = NPY_FLOAT
+ufunc__ellip_harm_types[7] = NPY_FLOAT
+ufunc__ellip_harm_types[8] = NPY_DOUBLE
+ufunc__ellip_harm_types[9] = NPY_DOUBLE
+ufunc__ellip_harm_types[10] = NPY_LONG
+ufunc__ellip_harm_types[11] = NPY_LONG
+ufunc__ellip_harm_types[12] = NPY_DOUBLE
+ufunc__ellip_harm_types[13] = NPY_DOUBLE
+ufunc__ellip_harm_types[14] = NPY_DOUBLE
+ufunc__ellip_harm_types[15] = NPY_DOUBLE
+ufunc__ellip_harm_types[16] = NPY_DOUBLE
+ufunc__ellip_harm_types[17] = NPY_DOUBLE
+ufunc__ellip_harm_types[18] = NPY_DOUBLE
+ufunc__ellip_harm_types[19] = NPY_DOUBLE
+ufunc__ellip_harm_types[20] = NPY_DOUBLE
+ufunc__ellip_harm_types[21] = NPY_DOUBLE
+ufunc__ellip_harm_types[22] = NPY_DOUBLE
+ufunc__ellip_harm_types[23] = NPY_DOUBLE
+ufunc__ellip_harm_ptr[2*0] = _func_ellip_harmonic_unsafe
+ufunc__ellip_harm_ptr[2*0+1] = ("_ellip_harm")
+ufunc__ellip_harm_ptr[2*1] = _func_ellip_harmonic
+ufunc__ellip_harm_ptr[2*1+1] = ("_ellip_harm")
+ufunc__ellip_harm_ptr[2*2] = _func_ellip_harmonic_unsafe
+ufunc__ellip_harm_ptr[2*2+1] = ("_ellip_harm")
+ufunc__ellip_harm_data[0] = &ufunc__ellip_harm_ptr[2*0]
+ufunc__ellip_harm_data[1] = &ufunc__ellip_harm_ptr[2*1]
+ufunc__ellip_harm_data[2] = &ufunc__ellip_harm_ptr[2*2]
+_ellip_harm = np.PyUFunc_FromFuncAndData(ufunc__ellip_harm_loops, ufunc__ellip_harm_data, ufunc__ellip_harm_types, 3, 7, 1, 0, "_ellip_harm", ufunc__ellip_harm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__factorial_loops[2]
+cdef void *ufunc__factorial_ptr[4]
+cdef void *ufunc__factorial_data[2]
+cdef char ufunc__factorial_types[4]
+cdef char *ufunc__factorial_doc = (
+    "Internal function, do not use.")
+ufunc__factorial_loops[0] = loop_d_d__As_f_f
+ufunc__factorial_loops[1] = loop_d_d__As_d_d
+ufunc__factorial_types[0] = NPY_FLOAT
+ufunc__factorial_types[1] = NPY_FLOAT
+ufunc__factorial_types[2] = NPY_DOUBLE
+ufunc__factorial_types[3] = NPY_DOUBLE
+ufunc__factorial_ptr[2*0] = _func__factorial
+ufunc__factorial_ptr[2*0+1] = ("_factorial")
+ufunc__factorial_ptr[2*1] = _func__factorial
+ufunc__factorial_ptr[2*1+1] = ("_factorial")
+ufunc__factorial_data[0] = &ufunc__factorial_ptr[2*0]
+ufunc__factorial_data[1] = &ufunc__factorial_ptr[2*1]
+_factorial = np.PyUFunc_FromFuncAndData(ufunc__factorial_loops, ufunc__factorial_data, ufunc__factorial_types, 2, 1, 1, 0, "_factorial", ufunc__factorial_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_cdf_loops[2]
+cdef void *ufunc__hypergeom_cdf_ptr[4]
+cdef void *ufunc__hypergeom_cdf_data[2]
+cdef char ufunc__hypergeom_cdf_types[10]
+cdef char *ufunc__hypergeom_cdf_doc = (
+    "_hypergeom_cdf(x, r, N, M)\n"
+    "\n"
+    "Cumulative density function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_cdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_cdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_cdf_types[0] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[1] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[2] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[3] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[4] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_cdf_float
+ufunc__hypergeom_cdf_ptr[2*0+1] = ("_hypergeom_cdf")
+ufunc__hypergeom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_cdf_double
+ufunc__hypergeom_cdf_ptr[2*1+1] = ("_hypergeom_cdf")
+ufunc__hypergeom_cdf_data[0] = &ufunc__hypergeom_cdf_ptr[2*0]
+ufunc__hypergeom_cdf_data[1] = &ufunc__hypergeom_cdf_ptr[2*1]
+_hypergeom_cdf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_cdf_loops, ufunc__hypergeom_cdf_data, ufunc__hypergeom_cdf_types, 2, 4, 1, 0, "_hypergeom_cdf", ufunc__hypergeom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_mean_loops[2]
+cdef void *ufunc__hypergeom_mean_ptr[4]
+cdef void *ufunc__hypergeom_mean_data[2]
+cdef char ufunc__hypergeom_mean_types[8]
+cdef char *ufunc__hypergeom_mean_doc = (
+    "_hypergeom_mean(r, N, M)\n"
+    "\n"
+    "Mean of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_mean_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_mean_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_mean_types[0] = NPY_FLOAT
+ufunc__hypergeom_mean_types[1] = NPY_FLOAT
+ufunc__hypergeom_mean_types[2] = NPY_FLOAT
+ufunc__hypergeom_mean_types[3] = NPY_FLOAT
+ufunc__hypergeom_mean_types[4] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[5] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[6] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[7] = NPY_DOUBLE
+ufunc__hypergeom_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_mean_float
+ufunc__hypergeom_mean_ptr[2*0+1] = ("_hypergeom_mean")
+ufunc__hypergeom_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_mean_double
+ufunc__hypergeom_mean_ptr[2*1+1] = ("_hypergeom_mean")
+ufunc__hypergeom_mean_data[0] = &ufunc__hypergeom_mean_ptr[2*0]
+ufunc__hypergeom_mean_data[1] = &ufunc__hypergeom_mean_ptr[2*1]
+_hypergeom_mean = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_mean_loops, ufunc__hypergeom_mean_data, ufunc__hypergeom_mean_types, 2, 3, 1, 0, "_hypergeom_mean", ufunc__hypergeom_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_pmf_loops[2]
+cdef void *ufunc__hypergeom_pmf_ptr[4]
+cdef void *ufunc__hypergeom_pmf_data[2]
+cdef char ufunc__hypergeom_pmf_types[10]
+cdef char *ufunc__hypergeom_pmf_doc = (
+    "_hypergeom_pmf(x, r, N, M)\n"
+    "\n"
+    "Probability mass function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_pmf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_pmf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_pmf_types[0] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[1] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[2] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[3] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[4] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_pmf_float
+ufunc__hypergeom_pmf_ptr[2*0+1] = ("_hypergeom_pmf")
+ufunc__hypergeom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_pmf_double
+ufunc__hypergeom_pmf_ptr[2*1+1] = ("_hypergeom_pmf")
+ufunc__hypergeom_pmf_data[0] = &ufunc__hypergeom_pmf_ptr[2*0]
+ufunc__hypergeom_pmf_data[1] = &ufunc__hypergeom_pmf_ptr[2*1]
+_hypergeom_pmf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_pmf_loops, ufunc__hypergeom_pmf_data, ufunc__hypergeom_pmf_types, 2, 4, 1, 0, "_hypergeom_pmf", ufunc__hypergeom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_sf_loops[2]
+cdef void *ufunc__hypergeom_sf_ptr[4]
+cdef void *ufunc__hypergeom_sf_data[2]
+cdef char ufunc__hypergeom_sf_types[10]
+cdef char *ufunc__hypergeom_sf_doc = (
+    "_hypergeom_sf(x, r, N, M)\n"
+    "\n"
+    "Survival function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_sf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_sf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_sf_types[0] = NPY_FLOAT
+ufunc__hypergeom_sf_types[1] = NPY_FLOAT
+ufunc__hypergeom_sf_types[2] = NPY_FLOAT
+ufunc__hypergeom_sf_types[3] = NPY_FLOAT
+ufunc__hypergeom_sf_types[4] = NPY_FLOAT
+ufunc__hypergeom_sf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_sf_float
+ufunc__hypergeom_sf_ptr[2*0+1] = ("_hypergeom_sf")
+ufunc__hypergeom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_sf_double
+ufunc__hypergeom_sf_ptr[2*1+1] = ("_hypergeom_sf")
+ufunc__hypergeom_sf_data[0] = &ufunc__hypergeom_sf_ptr[2*0]
+ufunc__hypergeom_sf_data[1] = &ufunc__hypergeom_sf_ptr[2*1]
+_hypergeom_sf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_sf_loops, ufunc__hypergeom_sf_data, ufunc__hypergeom_sf_types, 2, 4, 1, 0, "_hypergeom_sf", ufunc__hypergeom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_skewness_loops[2]
+cdef void *ufunc__hypergeom_skewness_ptr[4]
+cdef void *ufunc__hypergeom_skewness_data[2]
+cdef char ufunc__hypergeom_skewness_types[8]
+cdef char *ufunc__hypergeom_skewness_doc = (
+    "_hypergeom_skewness(r, N, M)\n"
+    "\n"
+    "Skewness of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_skewness_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_skewness_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_skewness_types[0] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[1] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[2] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[3] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[4] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[5] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[6] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[7] = NPY_DOUBLE
+ufunc__hypergeom_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_skewness_float
+ufunc__hypergeom_skewness_ptr[2*0+1] = ("_hypergeom_skewness")
+ufunc__hypergeom_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_skewness_double
+ufunc__hypergeom_skewness_ptr[2*1+1] = ("_hypergeom_skewness")
+ufunc__hypergeom_skewness_data[0] = &ufunc__hypergeom_skewness_ptr[2*0]
+ufunc__hypergeom_skewness_data[1] = &ufunc__hypergeom_skewness_ptr[2*1]
+_hypergeom_skewness = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_skewness_loops, ufunc__hypergeom_skewness_data, ufunc__hypergeom_skewness_types, 2, 3, 1, 0, "_hypergeom_skewness", ufunc__hypergeom_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_variance_loops[2]
+cdef void *ufunc__hypergeom_variance_ptr[4]
+cdef void *ufunc__hypergeom_variance_data[2]
+cdef char ufunc__hypergeom_variance_types[8]
+cdef char *ufunc__hypergeom_variance_doc = (
+    "_hypergeom_variance(r, N, M)\n"
+    "\n"
+    "Mean of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_variance_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_variance_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_variance_types[0] = NPY_FLOAT
+ufunc__hypergeom_variance_types[1] = NPY_FLOAT
+ufunc__hypergeom_variance_types[2] = NPY_FLOAT
+ufunc__hypergeom_variance_types[3] = NPY_FLOAT
+ufunc__hypergeom_variance_types[4] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[5] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[6] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[7] = NPY_DOUBLE
+ufunc__hypergeom_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_variance_float
+ufunc__hypergeom_variance_ptr[2*0+1] = ("_hypergeom_variance")
+ufunc__hypergeom_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_variance_double
+ufunc__hypergeom_variance_ptr[2*1+1] = ("_hypergeom_variance")
+ufunc__hypergeom_variance_data[0] = &ufunc__hypergeom_variance_ptr[2*0]
+ufunc__hypergeom_variance_data[1] = &ufunc__hypergeom_variance_ptr[2*1]
+_hypergeom_variance = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_variance_loops, ufunc__hypergeom_variance_data, ufunc__hypergeom_variance_types, 2, 3, 1, 0, "_hypergeom_variance", ufunc__hypergeom_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__igam_fac_loops[2]
+cdef void *ufunc__igam_fac_ptr[4]
+cdef void *ufunc__igam_fac_data[2]
+cdef char ufunc__igam_fac_types[6]
+cdef char *ufunc__igam_fac_doc = (
+    "Internal function, do not use.")
+ufunc__igam_fac_loops[0] = loop_d_dd__As_ff_f
+ufunc__igam_fac_loops[1] = loop_d_dd__As_dd_d
+ufunc__igam_fac_types[0] = NPY_FLOAT
+ufunc__igam_fac_types[1] = NPY_FLOAT
+ufunc__igam_fac_types[2] = NPY_FLOAT
+ufunc__igam_fac_types[3] = NPY_DOUBLE
+ufunc__igam_fac_types[4] = NPY_DOUBLE
+ufunc__igam_fac_types[5] = NPY_DOUBLE
+ufunc__igam_fac_ptr[2*0] = _func_cephes_igam_fac
+ufunc__igam_fac_ptr[2*0+1] = ("_igam_fac")
+ufunc__igam_fac_ptr[2*1] = _func_cephes_igam_fac
+ufunc__igam_fac_ptr[2*1+1] = ("_igam_fac")
+ufunc__igam_fac_data[0] = &ufunc__igam_fac_ptr[2*0]
+ufunc__igam_fac_data[1] = &ufunc__igam_fac_ptr[2*1]
+_igam_fac = np.PyUFunc_FromFuncAndData(ufunc__igam_fac_loops, ufunc__igam_fac_data, ufunc__igam_fac_types, 2, 2, 1, 0, "_igam_fac", ufunc__igam_fac_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__invgauss_isf_loops[2]
+cdef void *ufunc__invgauss_isf_ptr[4]
+cdef void *ufunc__invgauss_isf_data[2]
+cdef char ufunc__invgauss_isf_types[8]
+cdef char *ufunc__invgauss_isf_doc = (
+    "_invgauss_isf(x, mu, s)\n"
+    "\n"
+    "Inverse survival function of inverse gaussian distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "mu : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "s : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__invgauss_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__invgauss_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__invgauss_isf_types[0] = NPY_FLOAT
+ufunc__invgauss_isf_types[1] = NPY_FLOAT
+ufunc__invgauss_isf_types[2] = NPY_FLOAT
+ufunc__invgauss_isf_types[3] = NPY_FLOAT
+ufunc__invgauss_isf_types[4] = NPY_DOUBLE
+ufunc__invgauss_isf_types[5] = NPY_DOUBLE
+ufunc__invgauss_isf_types[6] = NPY_DOUBLE
+ufunc__invgauss_isf_types[7] = NPY_DOUBLE
+ufunc__invgauss_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_invgauss_isf_float
+ufunc__invgauss_isf_ptr[2*0+1] = ("_invgauss_isf")
+ufunc__invgauss_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_invgauss_isf_double
+ufunc__invgauss_isf_ptr[2*1+1] = ("_invgauss_isf")
+ufunc__invgauss_isf_data[0] = &ufunc__invgauss_isf_ptr[2*0]
+ufunc__invgauss_isf_data[1] = &ufunc__invgauss_isf_ptr[2*1]
+_invgauss_isf = np.PyUFunc_FromFuncAndData(ufunc__invgauss_isf_loops, ufunc__invgauss_isf_data, ufunc__invgauss_isf_types, 2, 3, 1, 0, "_invgauss_isf", ufunc__invgauss_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__invgauss_ppf_loops[2]
+cdef void *ufunc__invgauss_ppf_ptr[4]
+cdef void *ufunc__invgauss_ppf_data[2]
+cdef char ufunc__invgauss_ppf_types[8]
+cdef char *ufunc__invgauss_ppf_doc = (
+    "_invgauss_ppf(x, mu)\n"
+    "\n"
+    "Percent point function of inverse gaussian distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "mu : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__invgauss_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__invgauss_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__invgauss_ppf_types[0] = NPY_FLOAT
+ufunc__invgauss_ppf_types[1] = NPY_FLOAT
+ufunc__invgauss_ppf_types[2] = NPY_FLOAT
+ufunc__invgauss_ppf_types[3] = NPY_FLOAT
+ufunc__invgauss_ppf_types[4] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[5] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[6] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[7] = NPY_DOUBLE
+ufunc__invgauss_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_invgauss_ppf_float
+ufunc__invgauss_ppf_ptr[2*0+1] = ("_invgauss_ppf")
+ufunc__invgauss_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_invgauss_ppf_double
+ufunc__invgauss_ppf_ptr[2*1+1] = ("_invgauss_ppf")
+ufunc__invgauss_ppf_data[0] = &ufunc__invgauss_ppf_ptr[2*0]
+ufunc__invgauss_ppf_data[1] = &ufunc__invgauss_ppf_ptr[2*1]
+_invgauss_ppf = np.PyUFunc_FromFuncAndData(ufunc__invgauss_ppf_loops, ufunc__invgauss_ppf_data, ufunc__invgauss_ppf_types, 2, 3, 1, 0, "_invgauss_ppf", ufunc__invgauss_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogc_loops[2]
+cdef void *ufunc__kolmogc_ptr[4]
+cdef void *ufunc__kolmogc_data[2]
+cdef char ufunc__kolmogc_types[4]
+cdef char *ufunc__kolmogc_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogc_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogc_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogc_types[0] = NPY_FLOAT
+ufunc__kolmogc_types[1] = NPY_FLOAT
+ufunc__kolmogc_types[2] = NPY_DOUBLE
+ufunc__kolmogc_types[3] = NPY_DOUBLE
+ufunc__kolmogc_ptr[2*0] = _func_xsf_kolmogc
+ufunc__kolmogc_ptr[2*0+1] = ("_kolmogc")
+ufunc__kolmogc_ptr[2*1] = _func_xsf_kolmogc
+ufunc__kolmogc_ptr[2*1+1] = ("_kolmogc")
+ufunc__kolmogc_data[0] = &ufunc__kolmogc_ptr[2*0]
+ufunc__kolmogc_data[1] = &ufunc__kolmogc_ptr[2*1]
+_kolmogc = np.PyUFunc_FromFuncAndData(ufunc__kolmogc_loops, ufunc__kolmogc_data, ufunc__kolmogc_types, 2, 1, 1, 0, "_kolmogc", ufunc__kolmogc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogci_loops[2]
+cdef void *ufunc__kolmogci_ptr[4]
+cdef void *ufunc__kolmogci_data[2]
+cdef char ufunc__kolmogci_types[4]
+cdef char *ufunc__kolmogci_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogci_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogci_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogci_types[0] = NPY_FLOAT
+ufunc__kolmogci_types[1] = NPY_FLOAT
+ufunc__kolmogci_types[2] = NPY_DOUBLE
+ufunc__kolmogci_types[3] = NPY_DOUBLE
+ufunc__kolmogci_ptr[2*0] = _func_xsf_kolmogci
+ufunc__kolmogci_ptr[2*0+1] = ("_kolmogci")
+ufunc__kolmogci_ptr[2*1] = _func_xsf_kolmogci
+ufunc__kolmogci_ptr[2*1+1] = ("_kolmogci")
+ufunc__kolmogci_data[0] = &ufunc__kolmogci_ptr[2*0]
+ufunc__kolmogci_data[1] = &ufunc__kolmogci_ptr[2*1]
+_kolmogci = np.PyUFunc_FromFuncAndData(ufunc__kolmogci_loops, ufunc__kolmogci_data, ufunc__kolmogci_types, 2, 1, 1, 0, "_kolmogci", ufunc__kolmogci_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogp_loops[2]
+cdef void *ufunc__kolmogp_ptr[4]
+cdef void *ufunc__kolmogp_data[2]
+cdef char ufunc__kolmogp_types[4]
+cdef char *ufunc__kolmogp_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogp_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogp_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogp_types[0] = NPY_FLOAT
+ufunc__kolmogp_types[1] = NPY_FLOAT
+ufunc__kolmogp_types[2] = NPY_DOUBLE
+ufunc__kolmogp_types[3] = NPY_DOUBLE
+ufunc__kolmogp_ptr[2*0] = _func_xsf_kolmogp
+ufunc__kolmogp_ptr[2*0+1] = ("_kolmogp")
+ufunc__kolmogp_ptr[2*1] = _func_xsf_kolmogp
+ufunc__kolmogp_ptr[2*1+1] = ("_kolmogp")
+ufunc__kolmogp_data[0] = &ufunc__kolmogp_ptr[2*0]
+ufunc__kolmogp_data[1] = &ufunc__kolmogp_ptr[2*1]
+_kolmogp = np.PyUFunc_FromFuncAndData(ufunc__kolmogp_loops, ufunc__kolmogp_data, ufunc__kolmogp_types, 2, 1, 1, 0, "_kolmogp", ufunc__kolmogp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__lanczos_sum_expg_scaled_loops[2]
+cdef void *ufunc__lanczos_sum_expg_scaled_ptr[4]
+cdef void *ufunc__lanczos_sum_expg_scaled_data[2]
+cdef char ufunc__lanczos_sum_expg_scaled_types[4]
+cdef char *ufunc__lanczos_sum_expg_scaled_doc = (
+    "Internal function, do not use.")
+ufunc__lanczos_sum_expg_scaled_loops[0] = loop_d_d__As_f_f
+ufunc__lanczos_sum_expg_scaled_loops[1] = loop_d_d__As_d_d
+ufunc__lanczos_sum_expg_scaled_types[0] = NPY_FLOAT
+ufunc__lanczos_sum_expg_scaled_types[1] = NPY_FLOAT
+ufunc__lanczos_sum_expg_scaled_types[2] = NPY_DOUBLE
+ufunc__lanczos_sum_expg_scaled_types[3] = NPY_DOUBLE
+ufunc__lanczos_sum_expg_scaled_ptr[2*0] = _func_cephes_lanczos_sum_expg_scaled
+ufunc__lanczos_sum_expg_scaled_ptr[2*0+1] = ("_lanczos_sum_expg_scaled")
+ufunc__lanczos_sum_expg_scaled_ptr[2*1] = _func_cephes_lanczos_sum_expg_scaled
+ufunc__lanczos_sum_expg_scaled_ptr[2*1+1] = ("_lanczos_sum_expg_scaled")
+ufunc__lanczos_sum_expg_scaled_data[0] = &ufunc__lanczos_sum_expg_scaled_ptr[2*0]
+ufunc__lanczos_sum_expg_scaled_data[1] = &ufunc__lanczos_sum_expg_scaled_ptr[2*1]
+_lanczos_sum_expg_scaled = np.PyUFunc_FromFuncAndData(ufunc__lanczos_sum_expg_scaled_loops, ufunc__lanczos_sum_expg_scaled_data, ufunc__lanczos_sum_expg_scaled_types, 2, 1, 1, 0, "_lanczos_sum_expg_scaled", ufunc__lanczos_sum_expg_scaled_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_cdf_loops[2]
+cdef void *ufunc__landau_cdf_ptr[4]
+cdef void *ufunc__landau_cdf_data[2]
+cdef char ufunc__landau_cdf_types[8]
+cdef char *ufunc__landau_cdf_doc = (
+    "_landau_cdf(x, loc, scale)\n"
+    "\n"
+    "Cumulative distribution function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_cdf_types[0] = NPY_FLOAT
+ufunc__landau_cdf_types[1] = NPY_FLOAT
+ufunc__landau_cdf_types[2] = NPY_FLOAT
+ufunc__landau_cdf_types[3] = NPY_FLOAT
+ufunc__landau_cdf_types[4] = NPY_DOUBLE
+ufunc__landau_cdf_types[5] = NPY_DOUBLE
+ufunc__landau_cdf_types[6] = NPY_DOUBLE
+ufunc__landau_cdf_types[7] = NPY_DOUBLE
+ufunc__landau_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_cdf_float
+ufunc__landau_cdf_ptr[2*0+1] = ("_landau_cdf")
+ufunc__landau_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_cdf_double
+ufunc__landau_cdf_ptr[2*1+1] = ("_landau_cdf")
+ufunc__landau_cdf_data[0] = &ufunc__landau_cdf_ptr[2*0]
+ufunc__landau_cdf_data[1] = &ufunc__landau_cdf_ptr[2*1]
+_landau_cdf = np.PyUFunc_FromFuncAndData(ufunc__landau_cdf_loops, ufunc__landau_cdf_data, ufunc__landau_cdf_types, 2, 3, 1, 0, "_landau_cdf", ufunc__landau_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_isf_loops[2]
+cdef void *ufunc__landau_isf_ptr[4]
+cdef void *ufunc__landau_isf_data[2]
+cdef char ufunc__landau_isf_types[8]
+cdef char *ufunc__landau_isf_doc = (
+    "_landau_isf(p, loc, scale)\n"
+    "\n"
+    "Inverse survival function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Real-valued argument between 0 and 1\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_isf_types[0] = NPY_FLOAT
+ufunc__landau_isf_types[1] = NPY_FLOAT
+ufunc__landau_isf_types[2] = NPY_FLOAT
+ufunc__landau_isf_types[3] = NPY_FLOAT
+ufunc__landau_isf_types[4] = NPY_DOUBLE
+ufunc__landau_isf_types[5] = NPY_DOUBLE
+ufunc__landau_isf_types[6] = NPY_DOUBLE
+ufunc__landau_isf_types[7] = NPY_DOUBLE
+ufunc__landau_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_isf_float
+ufunc__landau_isf_ptr[2*0+1] = ("_landau_isf")
+ufunc__landau_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_isf_double
+ufunc__landau_isf_ptr[2*1+1] = ("_landau_isf")
+ufunc__landau_isf_data[0] = &ufunc__landau_isf_ptr[2*0]
+ufunc__landau_isf_data[1] = &ufunc__landau_isf_ptr[2*1]
+_landau_isf = np.PyUFunc_FromFuncAndData(ufunc__landau_isf_loops, ufunc__landau_isf_data, ufunc__landau_isf_types, 2, 3, 1, 0, "_landau_isf", ufunc__landau_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_pdf_loops[2]
+cdef void *ufunc__landau_pdf_ptr[4]
+cdef void *ufunc__landau_pdf_data[2]
+cdef char ufunc__landau_pdf_types[8]
+cdef char *ufunc__landau_pdf_doc = (
+    "_landau_pdf(x, loc, scale)\n"
+    "\n"
+    "Probability density function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_pdf_types[0] = NPY_FLOAT
+ufunc__landau_pdf_types[1] = NPY_FLOAT
+ufunc__landau_pdf_types[2] = NPY_FLOAT
+ufunc__landau_pdf_types[3] = NPY_FLOAT
+ufunc__landau_pdf_types[4] = NPY_DOUBLE
+ufunc__landau_pdf_types[5] = NPY_DOUBLE
+ufunc__landau_pdf_types[6] = NPY_DOUBLE
+ufunc__landau_pdf_types[7] = NPY_DOUBLE
+ufunc__landau_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_pdf_float
+ufunc__landau_pdf_ptr[2*0+1] = ("_landau_pdf")
+ufunc__landau_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_pdf_double
+ufunc__landau_pdf_ptr[2*1+1] = ("_landau_pdf")
+ufunc__landau_pdf_data[0] = &ufunc__landau_pdf_ptr[2*0]
+ufunc__landau_pdf_data[1] = &ufunc__landau_pdf_ptr[2*1]
+_landau_pdf = np.PyUFunc_FromFuncAndData(ufunc__landau_pdf_loops, ufunc__landau_pdf_data, ufunc__landau_pdf_types, 2, 3, 1, 0, "_landau_pdf", ufunc__landau_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_ppf_loops[2]
+cdef void *ufunc__landau_ppf_ptr[4]
+cdef void *ufunc__landau_ppf_data[2]
+cdef char ufunc__landau_ppf_types[8]
+cdef char *ufunc__landau_ppf_doc = (
+    "_landau_ppf(p, loc, scale)\n"
+    "\n"
+    "Percent point function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Real-valued argument between 0 and 1\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_ppf_types[0] = NPY_FLOAT
+ufunc__landau_ppf_types[1] = NPY_FLOAT
+ufunc__landau_ppf_types[2] = NPY_FLOAT
+ufunc__landau_ppf_types[3] = NPY_FLOAT
+ufunc__landau_ppf_types[4] = NPY_DOUBLE
+ufunc__landau_ppf_types[5] = NPY_DOUBLE
+ufunc__landau_ppf_types[6] = NPY_DOUBLE
+ufunc__landau_ppf_types[7] = NPY_DOUBLE
+ufunc__landau_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_ppf_float
+ufunc__landau_ppf_ptr[2*0+1] = ("_landau_ppf")
+ufunc__landau_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_ppf_double
+ufunc__landau_ppf_ptr[2*1+1] = ("_landau_ppf")
+ufunc__landau_ppf_data[0] = &ufunc__landau_ppf_ptr[2*0]
+ufunc__landau_ppf_data[1] = &ufunc__landau_ppf_ptr[2*1]
+_landau_ppf = np.PyUFunc_FromFuncAndData(ufunc__landau_ppf_loops, ufunc__landau_ppf_data, ufunc__landau_ppf_types, 2, 3, 1, 0, "_landau_ppf", ufunc__landau_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_sf_loops[2]
+cdef void *ufunc__landau_sf_ptr[4]
+cdef void *ufunc__landau_sf_data[2]
+cdef char ufunc__landau_sf_types[8]
+cdef char *ufunc__landau_sf_doc = (
+    "_landau_sf(x, loc, scale)\n"
+    "\n"
+    "Survival function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_sf_types[0] = NPY_FLOAT
+ufunc__landau_sf_types[1] = NPY_FLOAT
+ufunc__landau_sf_types[2] = NPY_FLOAT
+ufunc__landau_sf_types[3] = NPY_FLOAT
+ufunc__landau_sf_types[4] = NPY_DOUBLE
+ufunc__landau_sf_types[5] = NPY_DOUBLE
+ufunc__landau_sf_types[6] = NPY_DOUBLE
+ufunc__landau_sf_types[7] = NPY_DOUBLE
+ufunc__landau_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_sf_float
+ufunc__landau_sf_ptr[2*0+1] = ("_landau_sf")
+ufunc__landau_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_sf_double
+ufunc__landau_sf_ptr[2*1+1] = ("_landau_sf")
+ufunc__landau_sf_data[0] = &ufunc__landau_sf_ptr[2*0]
+ufunc__landau_sf_data[1] = &ufunc__landau_sf_ptr[2*1]
+_landau_sf = np.PyUFunc_FromFuncAndData(ufunc__landau_sf_loops, ufunc__landau_sf_data, ufunc__landau_sf_types, 2, 3, 1, 0, "_landau_sf", ufunc__landau_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__lgam1p_loops[2]
+cdef void *ufunc__lgam1p_ptr[4]
+cdef void *ufunc__lgam1p_data[2]
+cdef char ufunc__lgam1p_types[4]
+cdef char *ufunc__lgam1p_doc = (
+    "Internal function, do not use.")
+ufunc__lgam1p_loops[0] = loop_d_d__As_f_f
+ufunc__lgam1p_loops[1] = loop_d_d__As_d_d
+ufunc__lgam1p_types[0] = NPY_FLOAT
+ufunc__lgam1p_types[1] = NPY_FLOAT
+ufunc__lgam1p_types[2] = NPY_DOUBLE
+ufunc__lgam1p_types[3] = NPY_DOUBLE
+ufunc__lgam1p_ptr[2*0] = _func_cephes_lgam1p
+ufunc__lgam1p_ptr[2*0+1] = ("_lgam1p")
+ufunc__lgam1p_ptr[2*1] = _func_cephes_lgam1p
+ufunc__lgam1p_ptr[2*1+1] = ("_lgam1p")
+ufunc__lgam1p_data[0] = &ufunc__lgam1p_ptr[2*0]
+ufunc__lgam1p_data[1] = &ufunc__lgam1p_ptr[2*1]
+_lgam1p = np.PyUFunc_FromFuncAndData(ufunc__lgam1p_loops, ufunc__lgam1p_data, ufunc__lgam1p_types, 2, 1, 1, 0, "_lgam1p", ufunc__lgam1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__log1pmx_loops[2]
+cdef void *ufunc__log1pmx_ptr[4]
+cdef void *ufunc__log1pmx_data[2]
+cdef char ufunc__log1pmx_types[4]
+cdef char *ufunc__log1pmx_doc = (
+    "Internal function, do not use.")
+ufunc__log1pmx_loops[0] = loop_d_d__As_f_f
+ufunc__log1pmx_loops[1] = loop_d_d__As_d_d
+ufunc__log1pmx_types[0] = NPY_FLOAT
+ufunc__log1pmx_types[1] = NPY_FLOAT
+ufunc__log1pmx_types[2] = NPY_DOUBLE
+ufunc__log1pmx_types[3] = NPY_DOUBLE
+ufunc__log1pmx_ptr[2*0] = _func_cephes_log1pmx
+ufunc__log1pmx_ptr[2*0+1] = ("_log1pmx")
+ufunc__log1pmx_ptr[2*1] = _func_cephes_log1pmx
+ufunc__log1pmx_ptr[2*1+1] = ("_log1pmx")
+ufunc__log1pmx_data[0] = &ufunc__log1pmx_ptr[2*0]
+ufunc__log1pmx_data[1] = &ufunc__log1pmx_ptr[2*1]
+_log1pmx = np.PyUFunc_FromFuncAndData(ufunc__log1pmx_loops, ufunc__log1pmx_data, ufunc__log1pmx_types, 2, 1, 1, 0, "_log1pmx", ufunc__log1pmx_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_cdf_loops[2]
+cdef void *ufunc__nbinom_cdf_ptr[4]
+cdef void *ufunc__nbinom_cdf_data[2]
+cdef char ufunc__nbinom_cdf_types[8]
+cdef char *ufunc__nbinom_cdf_doc = (
+    "_nbinom_cdf(x, r, p)\n"
+    "\n"
+    "Cumulative density function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_cdf_types[0] = NPY_FLOAT
+ufunc__nbinom_cdf_types[1] = NPY_FLOAT
+ufunc__nbinom_cdf_types[2] = NPY_FLOAT
+ufunc__nbinom_cdf_types[3] = NPY_FLOAT
+ufunc__nbinom_cdf_types[4] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[5] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[6] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[7] = NPY_DOUBLE
+ufunc__nbinom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_cdf_float
+ufunc__nbinom_cdf_ptr[2*0+1] = ("_nbinom_cdf")
+ufunc__nbinom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_cdf_double
+ufunc__nbinom_cdf_ptr[2*1+1] = ("_nbinom_cdf")
+ufunc__nbinom_cdf_data[0] = &ufunc__nbinom_cdf_ptr[2*0]
+ufunc__nbinom_cdf_data[1] = &ufunc__nbinom_cdf_ptr[2*1]
+_nbinom_cdf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_cdf_loops, ufunc__nbinom_cdf_data, ufunc__nbinom_cdf_types, 2, 3, 1, 0, "_nbinom_cdf", ufunc__nbinom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_isf_loops[2]
+cdef void *ufunc__nbinom_isf_ptr[4]
+cdef void *ufunc__nbinom_isf_data[2]
+cdef char ufunc__nbinom_isf_types[8]
+cdef char *ufunc__nbinom_isf_doc = (
+    "_nbinom_isf(x, r, p)\n"
+    "\n"
+    "Inverse survival function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_isf_types[0] = NPY_FLOAT
+ufunc__nbinom_isf_types[1] = NPY_FLOAT
+ufunc__nbinom_isf_types[2] = NPY_FLOAT
+ufunc__nbinom_isf_types[3] = NPY_FLOAT
+ufunc__nbinom_isf_types[4] = NPY_DOUBLE
+ufunc__nbinom_isf_types[5] = NPY_DOUBLE
+ufunc__nbinom_isf_types[6] = NPY_DOUBLE
+ufunc__nbinom_isf_types[7] = NPY_DOUBLE
+ufunc__nbinom_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_isf_float
+ufunc__nbinom_isf_ptr[2*0+1] = ("_nbinom_isf")
+ufunc__nbinom_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_isf_double
+ufunc__nbinom_isf_ptr[2*1+1] = ("_nbinom_isf")
+ufunc__nbinom_isf_data[0] = &ufunc__nbinom_isf_ptr[2*0]
+ufunc__nbinom_isf_data[1] = &ufunc__nbinom_isf_ptr[2*1]
+_nbinom_isf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_isf_loops, ufunc__nbinom_isf_data, ufunc__nbinom_isf_types, 2, 3, 1, 0, "_nbinom_isf", ufunc__nbinom_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_kurtosis_excess_loops[2]
+cdef void *ufunc__nbinom_kurtosis_excess_ptr[4]
+cdef void *ufunc__nbinom_kurtosis_excess_data[2]
+cdef char ufunc__nbinom_kurtosis_excess_types[6]
+cdef char *ufunc__nbinom_kurtosis_excess_doc = (
+    "_nbinom_kurtosis_excess(r, p)\n"
+    "\n"
+    "Kurtosis excess of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_kurtosis_excess_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_kurtosis_excess_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[3] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_kurtosis_excess_float
+ufunc__nbinom_kurtosis_excess_ptr[2*0+1] = ("_nbinom_kurtosis_excess")
+ufunc__nbinom_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_kurtosis_excess_double
+ufunc__nbinom_kurtosis_excess_ptr[2*1+1] = ("_nbinom_kurtosis_excess")
+ufunc__nbinom_kurtosis_excess_data[0] = &ufunc__nbinom_kurtosis_excess_ptr[2*0]
+ufunc__nbinom_kurtosis_excess_data[1] = &ufunc__nbinom_kurtosis_excess_ptr[2*1]
+_nbinom_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__nbinom_kurtosis_excess_loops, ufunc__nbinom_kurtosis_excess_data, ufunc__nbinom_kurtosis_excess_types, 2, 2, 1, 0, "_nbinom_kurtosis_excess", ufunc__nbinom_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_mean_loops[2]
+cdef void *ufunc__nbinom_mean_ptr[4]
+cdef void *ufunc__nbinom_mean_data[2]
+cdef char ufunc__nbinom_mean_types[6]
+cdef char *ufunc__nbinom_mean_doc = (
+    "_nbinom_mean(r, p)\n"
+    "\n"
+    "Mean of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_mean_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_mean_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_mean_types[0] = NPY_FLOAT
+ufunc__nbinom_mean_types[1] = NPY_FLOAT
+ufunc__nbinom_mean_types[2] = NPY_FLOAT
+ufunc__nbinom_mean_types[3] = NPY_DOUBLE
+ufunc__nbinom_mean_types[4] = NPY_DOUBLE
+ufunc__nbinom_mean_types[5] = NPY_DOUBLE
+ufunc__nbinom_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_mean_float
+ufunc__nbinom_mean_ptr[2*0+1] = ("_nbinom_mean")
+ufunc__nbinom_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_mean_double
+ufunc__nbinom_mean_ptr[2*1+1] = ("_nbinom_mean")
+ufunc__nbinom_mean_data[0] = &ufunc__nbinom_mean_ptr[2*0]
+ufunc__nbinom_mean_data[1] = &ufunc__nbinom_mean_ptr[2*1]
+_nbinom_mean = np.PyUFunc_FromFuncAndData(ufunc__nbinom_mean_loops, ufunc__nbinom_mean_data, ufunc__nbinom_mean_types, 2, 2, 1, 0, "_nbinom_mean", ufunc__nbinom_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_pmf_loops[2]
+cdef void *ufunc__nbinom_pmf_ptr[4]
+cdef void *ufunc__nbinom_pmf_data[2]
+cdef char ufunc__nbinom_pmf_types[8]
+cdef char *ufunc__nbinom_pmf_doc = (
+    "_nbinom_pmf(x, r, p)\n"
+    "\n"
+    "Probability mass function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_pmf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_pmf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_pmf_types[0] = NPY_FLOAT
+ufunc__nbinom_pmf_types[1] = NPY_FLOAT
+ufunc__nbinom_pmf_types[2] = NPY_FLOAT
+ufunc__nbinom_pmf_types[3] = NPY_FLOAT
+ufunc__nbinom_pmf_types[4] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[5] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[6] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[7] = NPY_DOUBLE
+ufunc__nbinom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_pmf_float
+ufunc__nbinom_pmf_ptr[2*0+1] = ("_nbinom_pmf")
+ufunc__nbinom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_pmf_double
+ufunc__nbinom_pmf_ptr[2*1+1] = ("_nbinom_pmf")
+ufunc__nbinom_pmf_data[0] = &ufunc__nbinom_pmf_ptr[2*0]
+ufunc__nbinom_pmf_data[1] = &ufunc__nbinom_pmf_ptr[2*1]
+_nbinom_pmf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_pmf_loops, ufunc__nbinom_pmf_data, ufunc__nbinom_pmf_types, 2, 3, 1, 0, "_nbinom_pmf", ufunc__nbinom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_ppf_loops[2]
+cdef void *ufunc__nbinom_ppf_ptr[4]
+cdef void *ufunc__nbinom_ppf_data[2]
+cdef char ufunc__nbinom_ppf_types[8]
+cdef char *ufunc__nbinom_ppf_doc = (
+    "_nbinom_ppf(x, r, p)\n"
+    "\n"
+    "Percent point function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_ppf_types[0] = NPY_FLOAT
+ufunc__nbinom_ppf_types[1] = NPY_FLOAT
+ufunc__nbinom_ppf_types[2] = NPY_FLOAT
+ufunc__nbinom_ppf_types[3] = NPY_FLOAT
+ufunc__nbinom_ppf_types[4] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[5] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[6] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[7] = NPY_DOUBLE
+ufunc__nbinom_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_ppf_float
+ufunc__nbinom_ppf_ptr[2*0+1] = ("_nbinom_ppf")
+ufunc__nbinom_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_ppf_double
+ufunc__nbinom_ppf_ptr[2*1+1] = ("_nbinom_ppf")
+ufunc__nbinom_ppf_data[0] = &ufunc__nbinom_ppf_ptr[2*0]
+ufunc__nbinom_ppf_data[1] = &ufunc__nbinom_ppf_ptr[2*1]
+_nbinom_ppf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_ppf_loops, ufunc__nbinom_ppf_data, ufunc__nbinom_ppf_types, 2, 3, 1, 0, "_nbinom_ppf", ufunc__nbinom_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_sf_loops[2]
+cdef void *ufunc__nbinom_sf_ptr[4]
+cdef void *ufunc__nbinom_sf_data[2]
+cdef char ufunc__nbinom_sf_types[8]
+cdef char *ufunc__nbinom_sf_doc = (
+    "_nbinom_sf(x, r, p)\n"
+    "\n"
+    "Survival function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_sf_types[0] = NPY_FLOAT
+ufunc__nbinom_sf_types[1] = NPY_FLOAT
+ufunc__nbinom_sf_types[2] = NPY_FLOAT
+ufunc__nbinom_sf_types[3] = NPY_FLOAT
+ufunc__nbinom_sf_types[4] = NPY_DOUBLE
+ufunc__nbinom_sf_types[5] = NPY_DOUBLE
+ufunc__nbinom_sf_types[6] = NPY_DOUBLE
+ufunc__nbinom_sf_types[7] = NPY_DOUBLE
+ufunc__nbinom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_sf_float
+ufunc__nbinom_sf_ptr[2*0+1] = ("_nbinom_sf")
+ufunc__nbinom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_sf_double
+ufunc__nbinom_sf_ptr[2*1+1] = ("_nbinom_sf")
+ufunc__nbinom_sf_data[0] = &ufunc__nbinom_sf_ptr[2*0]
+ufunc__nbinom_sf_data[1] = &ufunc__nbinom_sf_ptr[2*1]
+_nbinom_sf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_sf_loops, ufunc__nbinom_sf_data, ufunc__nbinom_sf_types, 2, 3, 1, 0, "_nbinom_sf", ufunc__nbinom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_skewness_loops[2]
+cdef void *ufunc__nbinom_skewness_ptr[4]
+cdef void *ufunc__nbinom_skewness_data[2]
+cdef char ufunc__nbinom_skewness_types[6]
+cdef char *ufunc__nbinom_skewness_doc = (
+    "_nbinom_skewness(r, p)\n"
+    "\n"
+    "Skewness of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_skewness_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_skewness_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_skewness_types[0] = NPY_FLOAT
+ufunc__nbinom_skewness_types[1] = NPY_FLOAT
+ufunc__nbinom_skewness_types[2] = NPY_FLOAT
+ufunc__nbinom_skewness_types[3] = NPY_DOUBLE
+ufunc__nbinom_skewness_types[4] = NPY_DOUBLE
+ufunc__nbinom_skewness_types[5] = NPY_DOUBLE
+ufunc__nbinom_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_skewness_float
+ufunc__nbinom_skewness_ptr[2*0+1] = ("_nbinom_skewness")
+ufunc__nbinom_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_skewness_double
+ufunc__nbinom_skewness_ptr[2*1+1] = ("_nbinom_skewness")
+ufunc__nbinom_skewness_data[0] = &ufunc__nbinom_skewness_ptr[2*0]
+ufunc__nbinom_skewness_data[1] = &ufunc__nbinom_skewness_ptr[2*1]
+_nbinom_skewness = np.PyUFunc_FromFuncAndData(ufunc__nbinom_skewness_loops, ufunc__nbinom_skewness_data, ufunc__nbinom_skewness_types, 2, 2, 1, 0, "_nbinom_skewness", ufunc__nbinom_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_variance_loops[2]
+cdef void *ufunc__nbinom_variance_ptr[4]
+cdef void *ufunc__nbinom_variance_data[2]
+cdef char ufunc__nbinom_variance_types[6]
+cdef char *ufunc__nbinom_variance_doc = (
+    "_nbinom_variance(r, p)\n"
+    "\n"
+    "Variance of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_variance_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_variance_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_variance_types[0] = NPY_FLOAT
+ufunc__nbinom_variance_types[1] = NPY_FLOAT
+ufunc__nbinom_variance_types[2] = NPY_FLOAT
+ufunc__nbinom_variance_types[3] = NPY_DOUBLE
+ufunc__nbinom_variance_types[4] = NPY_DOUBLE
+ufunc__nbinom_variance_types[5] = NPY_DOUBLE
+ufunc__nbinom_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_variance_float
+ufunc__nbinom_variance_ptr[2*0+1] = ("_nbinom_variance")
+ufunc__nbinom_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_variance_double
+ufunc__nbinom_variance_ptr[2*1+1] = ("_nbinom_variance")
+ufunc__nbinom_variance_data[0] = &ufunc__nbinom_variance_ptr[2*0]
+ufunc__nbinom_variance_data[1] = &ufunc__nbinom_variance_ptr[2*1]
+_nbinom_variance = np.PyUFunc_FromFuncAndData(ufunc__nbinom_variance_loops, ufunc__nbinom_variance_data, ufunc__nbinom_variance_types, 2, 2, 1, 0, "_nbinom_variance", ufunc__nbinom_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_isf_loops[2]
+cdef void *ufunc__ncf_isf_ptr[4]
+cdef void *ufunc__ncf_isf_data[2]
+cdef char ufunc__ncf_isf_types[10]
+cdef char *ufunc__ncf_isf_doc = (
+    "_ncf_isf(x, v1, v2, l)\n"
+    "\n"
+    "Inverse survival function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_isf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_isf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_isf_types[0] = NPY_FLOAT
+ufunc__ncf_isf_types[1] = NPY_FLOAT
+ufunc__ncf_isf_types[2] = NPY_FLOAT
+ufunc__ncf_isf_types[3] = NPY_FLOAT
+ufunc__ncf_isf_types[4] = NPY_FLOAT
+ufunc__ncf_isf_types[5] = NPY_DOUBLE
+ufunc__ncf_isf_types[6] = NPY_DOUBLE
+ufunc__ncf_isf_types[7] = NPY_DOUBLE
+ufunc__ncf_isf_types[8] = NPY_DOUBLE
+ufunc__ncf_isf_types[9] = NPY_DOUBLE
+ufunc__ncf_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_isf_float
+ufunc__ncf_isf_ptr[2*0+1] = ("_ncf_isf")
+ufunc__ncf_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_isf_double
+ufunc__ncf_isf_ptr[2*1+1] = ("_ncf_isf")
+ufunc__ncf_isf_data[0] = &ufunc__ncf_isf_ptr[2*0]
+ufunc__ncf_isf_data[1] = &ufunc__ncf_isf_ptr[2*1]
+_ncf_isf = np.PyUFunc_FromFuncAndData(ufunc__ncf_isf_loops, ufunc__ncf_isf_data, ufunc__ncf_isf_types, 2, 4, 1, 0, "_ncf_isf", ufunc__ncf_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_kurtosis_excess_loops[2]
+cdef void *ufunc__ncf_kurtosis_excess_ptr[4]
+cdef void *ufunc__ncf_kurtosis_excess_data[2]
+cdef char ufunc__ncf_kurtosis_excess_types[8]
+cdef char *ufunc__ncf_kurtosis_excess_doc = (
+    "_ncf_kurtosis_excess(v1, v2, l)\n"
+    "\n"
+    "Kurtosis excess of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_kurtosis_excess_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_kurtosis_excess_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[3] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[6] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[7] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_kurtosis_excess_float
+ufunc__ncf_kurtosis_excess_ptr[2*0+1] = ("_ncf_kurtosis_excess")
+ufunc__ncf_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_kurtosis_excess_double
+ufunc__ncf_kurtosis_excess_ptr[2*1+1] = ("_ncf_kurtosis_excess")
+ufunc__ncf_kurtosis_excess_data[0] = &ufunc__ncf_kurtosis_excess_ptr[2*0]
+ufunc__ncf_kurtosis_excess_data[1] = &ufunc__ncf_kurtosis_excess_ptr[2*1]
+_ncf_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__ncf_kurtosis_excess_loops, ufunc__ncf_kurtosis_excess_data, ufunc__ncf_kurtosis_excess_types, 2, 3, 1, 0, "_ncf_kurtosis_excess", ufunc__ncf_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_mean_loops[2]
+cdef void *ufunc__ncf_mean_ptr[4]
+cdef void *ufunc__ncf_mean_data[2]
+cdef char ufunc__ncf_mean_types[8]
+cdef char *ufunc__ncf_mean_doc = (
+    "_ncf_mean(v1, v2, l)\n"
+    "\n"
+    "Mean of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_mean_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_mean_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_mean_types[0] = NPY_FLOAT
+ufunc__ncf_mean_types[1] = NPY_FLOAT
+ufunc__ncf_mean_types[2] = NPY_FLOAT
+ufunc__ncf_mean_types[3] = NPY_FLOAT
+ufunc__ncf_mean_types[4] = NPY_DOUBLE
+ufunc__ncf_mean_types[5] = NPY_DOUBLE
+ufunc__ncf_mean_types[6] = NPY_DOUBLE
+ufunc__ncf_mean_types[7] = NPY_DOUBLE
+ufunc__ncf_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_mean_float
+ufunc__ncf_mean_ptr[2*0+1] = ("_ncf_mean")
+ufunc__ncf_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_mean_double
+ufunc__ncf_mean_ptr[2*1+1] = ("_ncf_mean")
+ufunc__ncf_mean_data[0] = &ufunc__ncf_mean_ptr[2*0]
+ufunc__ncf_mean_data[1] = &ufunc__ncf_mean_ptr[2*1]
+_ncf_mean = np.PyUFunc_FromFuncAndData(ufunc__ncf_mean_loops, ufunc__ncf_mean_data, ufunc__ncf_mean_types, 2, 3, 1, 0, "_ncf_mean", ufunc__ncf_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_pdf_loops[2]
+cdef void *ufunc__ncf_pdf_ptr[4]
+cdef void *ufunc__ncf_pdf_data[2]
+cdef char ufunc__ncf_pdf_types[10]
+cdef char *ufunc__ncf_pdf_doc = (
+    "_ncf_pdf(x, v1, v2, l)\n"
+    "\n"
+    "Probability density function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_pdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_pdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_pdf_types[0] = NPY_FLOAT
+ufunc__ncf_pdf_types[1] = NPY_FLOAT
+ufunc__ncf_pdf_types[2] = NPY_FLOAT
+ufunc__ncf_pdf_types[3] = NPY_FLOAT
+ufunc__ncf_pdf_types[4] = NPY_FLOAT
+ufunc__ncf_pdf_types[5] = NPY_DOUBLE
+ufunc__ncf_pdf_types[6] = NPY_DOUBLE
+ufunc__ncf_pdf_types[7] = NPY_DOUBLE
+ufunc__ncf_pdf_types[8] = NPY_DOUBLE
+ufunc__ncf_pdf_types[9] = NPY_DOUBLE
+ufunc__ncf_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_pdf_float
+ufunc__ncf_pdf_ptr[2*0+1] = ("_ncf_pdf")
+ufunc__ncf_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_pdf_double
+ufunc__ncf_pdf_ptr[2*1+1] = ("_ncf_pdf")
+ufunc__ncf_pdf_data[0] = &ufunc__ncf_pdf_ptr[2*0]
+ufunc__ncf_pdf_data[1] = &ufunc__ncf_pdf_ptr[2*1]
+_ncf_pdf = np.PyUFunc_FromFuncAndData(ufunc__ncf_pdf_loops, ufunc__ncf_pdf_data, ufunc__ncf_pdf_types, 2, 4, 1, 0, "_ncf_pdf", ufunc__ncf_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_sf_loops[2]
+cdef void *ufunc__ncf_sf_ptr[4]
+cdef void *ufunc__ncf_sf_data[2]
+cdef char ufunc__ncf_sf_types[10]
+cdef char *ufunc__ncf_sf_doc = (
+    "_ncf_sf(x, v1, v2, l)\n"
+    "\n"
+    "Survival function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_sf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_sf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_sf_types[0] = NPY_FLOAT
+ufunc__ncf_sf_types[1] = NPY_FLOAT
+ufunc__ncf_sf_types[2] = NPY_FLOAT
+ufunc__ncf_sf_types[3] = NPY_FLOAT
+ufunc__ncf_sf_types[4] = NPY_FLOAT
+ufunc__ncf_sf_types[5] = NPY_DOUBLE
+ufunc__ncf_sf_types[6] = NPY_DOUBLE
+ufunc__ncf_sf_types[7] = NPY_DOUBLE
+ufunc__ncf_sf_types[8] = NPY_DOUBLE
+ufunc__ncf_sf_types[9] = NPY_DOUBLE
+ufunc__ncf_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_sf_float
+ufunc__ncf_sf_ptr[2*0+1] = ("_ncf_sf")
+ufunc__ncf_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_sf_double
+ufunc__ncf_sf_ptr[2*1+1] = ("_ncf_sf")
+ufunc__ncf_sf_data[0] = &ufunc__ncf_sf_ptr[2*0]
+ufunc__ncf_sf_data[1] = &ufunc__ncf_sf_ptr[2*1]
+_ncf_sf = np.PyUFunc_FromFuncAndData(ufunc__ncf_sf_loops, ufunc__ncf_sf_data, ufunc__ncf_sf_types, 2, 4, 1, 0, "_ncf_sf", ufunc__ncf_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_skewness_loops[2]
+cdef void *ufunc__ncf_skewness_ptr[4]
+cdef void *ufunc__ncf_skewness_data[2]
+cdef char ufunc__ncf_skewness_types[8]
+cdef char *ufunc__ncf_skewness_doc = (
+    "_ncf_skewness(v1, v2, l)\n"
+    "\n"
+    "Skewness of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_skewness_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_skewness_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_skewness_types[0] = NPY_FLOAT
+ufunc__ncf_skewness_types[1] = NPY_FLOAT
+ufunc__ncf_skewness_types[2] = NPY_FLOAT
+ufunc__ncf_skewness_types[3] = NPY_FLOAT
+ufunc__ncf_skewness_types[4] = NPY_DOUBLE
+ufunc__ncf_skewness_types[5] = NPY_DOUBLE
+ufunc__ncf_skewness_types[6] = NPY_DOUBLE
+ufunc__ncf_skewness_types[7] = NPY_DOUBLE
+ufunc__ncf_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_skewness_float
+ufunc__ncf_skewness_ptr[2*0+1] = ("_ncf_skewness")
+ufunc__ncf_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_skewness_double
+ufunc__ncf_skewness_ptr[2*1+1] = ("_ncf_skewness")
+ufunc__ncf_skewness_data[0] = &ufunc__ncf_skewness_ptr[2*0]
+ufunc__ncf_skewness_data[1] = &ufunc__ncf_skewness_ptr[2*1]
+_ncf_skewness = np.PyUFunc_FromFuncAndData(ufunc__ncf_skewness_loops, ufunc__ncf_skewness_data, ufunc__ncf_skewness_types, 2, 3, 1, 0, "_ncf_skewness", ufunc__ncf_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_variance_loops[2]
+cdef void *ufunc__ncf_variance_ptr[4]
+cdef void *ufunc__ncf_variance_data[2]
+cdef char ufunc__ncf_variance_types[8]
+cdef char *ufunc__ncf_variance_doc = (
+    "_ncf_variance(v1, v2, l)\n"
+    "\n"
+    "Variance of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_variance_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_variance_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_variance_types[0] = NPY_FLOAT
+ufunc__ncf_variance_types[1] = NPY_FLOAT
+ufunc__ncf_variance_types[2] = NPY_FLOAT
+ufunc__ncf_variance_types[3] = NPY_FLOAT
+ufunc__ncf_variance_types[4] = NPY_DOUBLE
+ufunc__ncf_variance_types[5] = NPY_DOUBLE
+ufunc__ncf_variance_types[6] = NPY_DOUBLE
+ufunc__ncf_variance_types[7] = NPY_DOUBLE
+ufunc__ncf_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_variance_float
+ufunc__ncf_variance_ptr[2*0+1] = ("_ncf_variance")
+ufunc__ncf_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_variance_double
+ufunc__ncf_variance_ptr[2*1+1] = ("_ncf_variance")
+ufunc__ncf_variance_data[0] = &ufunc__ncf_variance_ptr[2*0]
+ufunc__ncf_variance_data[1] = &ufunc__ncf_variance_ptr[2*1]
+_ncf_variance = np.PyUFunc_FromFuncAndData(ufunc__ncf_variance_loops, ufunc__ncf_variance_data, ufunc__ncf_variance_types, 2, 3, 1, 0, "_ncf_variance", ufunc__ncf_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_isf_loops[2]
+cdef void *ufunc__nct_isf_ptr[4]
+cdef void *ufunc__nct_isf_data[2]
+cdef char ufunc__nct_isf_types[8]
+cdef char *ufunc__nct_isf_doc = (
+    "_nct_isf(x, v, l)\n"
+    "\n"
+    "Inverse survival function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_isf_types[0] = NPY_FLOAT
+ufunc__nct_isf_types[1] = NPY_FLOAT
+ufunc__nct_isf_types[2] = NPY_FLOAT
+ufunc__nct_isf_types[3] = NPY_FLOAT
+ufunc__nct_isf_types[4] = NPY_DOUBLE
+ufunc__nct_isf_types[5] = NPY_DOUBLE
+ufunc__nct_isf_types[6] = NPY_DOUBLE
+ufunc__nct_isf_types[7] = NPY_DOUBLE
+ufunc__nct_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_isf_float
+ufunc__nct_isf_ptr[2*0+1] = ("_nct_isf")
+ufunc__nct_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_isf_double
+ufunc__nct_isf_ptr[2*1+1] = ("_nct_isf")
+ufunc__nct_isf_data[0] = &ufunc__nct_isf_ptr[2*0]
+ufunc__nct_isf_data[1] = &ufunc__nct_isf_ptr[2*1]
+_nct_isf = np.PyUFunc_FromFuncAndData(ufunc__nct_isf_loops, ufunc__nct_isf_data, ufunc__nct_isf_types, 2, 3, 1, 0, "_nct_isf", ufunc__nct_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_kurtosis_excess_loops[2]
+cdef void *ufunc__nct_kurtosis_excess_ptr[4]
+cdef void *ufunc__nct_kurtosis_excess_data[2]
+cdef char ufunc__nct_kurtosis_excess_types[6]
+cdef char *ufunc__nct_kurtosis_excess_doc = (
+    "_nct_kurtosis_excess(v, l)\n"
+    "\n"
+    "Kurtosis excess of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_kurtosis_excess_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_kurtosis_excess_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[3] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_kurtosis_excess_float
+ufunc__nct_kurtosis_excess_ptr[2*0+1] = ("_nct_kurtosis_excess")
+ufunc__nct_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_kurtosis_excess_double
+ufunc__nct_kurtosis_excess_ptr[2*1+1] = ("_nct_kurtosis_excess")
+ufunc__nct_kurtosis_excess_data[0] = &ufunc__nct_kurtosis_excess_ptr[2*0]
+ufunc__nct_kurtosis_excess_data[1] = &ufunc__nct_kurtosis_excess_ptr[2*1]
+_nct_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__nct_kurtosis_excess_loops, ufunc__nct_kurtosis_excess_data, ufunc__nct_kurtosis_excess_types, 2, 2, 1, 0, "_nct_kurtosis_excess", ufunc__nct_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_mean_loops[2]
+cdef void *ufunc__nct_mean_ptr[4]
+cdef void *ufunc__nct_mean_data[2]
+cdef char ufunc__nct_mean_types[6]
+cdef char *ufunc__nct_mean_doc = (
+    "_nct_mean(v, l)\n"
+    "\n"
+    "Mean of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_mean_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_mean_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_mean_types[0] = NPY_FLOAT
+ufunc__nct_mean_types[1] = NPY_FLOAT
+ufunc__nct_mean_types[2] = NPY_FLOAT
+ufunc__nct_mean_types[3] = NPY_DOUBLE
+ufunc__nct_mean_types[4] = NPY_DOUBLE
+ufunc__nct_mean_types[5] = NPY_DOUBLE
+ufunc__nct_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_mean_float
+ufunc__nct_mean_ptr[2*0+1] = ("_nct_mean")
+ufunc__nct_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_mean_double
+ufunc__nct_mean_ptr[2*1+1] = ("_nct_mean")
+ufunc__nct_mean_data[0] = &ufunc__nct_mean_ptr[2*0]
+ufunc__nct_mean_data[1] = &ufunc__nct_mean_ptr[2*1]
+_nct_mean = np.PyUFunc_FromFuncAndData(ufunc__nct_mean_loops, ufunc__nct_mean_data, ufunc__nct_mean_types, 2, 2, 1, 0, "_nct_mean", ufunc__nct_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_pdf_loops[2]
+cdef void *ufunc__nct_pdf_ptr[4]
+cdef void *ufunc__nct_pdf_data[2]
+cdef char ufunc__nct_pdf_types[8]
+cdef char *ufunc__nct_pdf_doc = (
+    "_nct_pdf(x, v, l)\n"
+    "\n"
+    "Probability density function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_pdf_types[0] = NPY_FLOAT
+ufunc__nct_pdf_types[1] = NPY_FLOAT
+ufunc__nct_pdf_types[2] = NPY_FLOAT
+ufunc__nct_pdf_types[3] = NPY_FLOAT
+ufunc__nct_pdf_types[4] = NPY_DOUBLE
+ufunc__nct_pdf_types[5] = NPY_DOUBLE
+ufunc__nct_pdf_types[6] = NPY_DOUBLE
+ufunc__nct_pdf_types[7] = NPY_DOUBLE
+ufunc__nct_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_pdf_float
+ufunc__nct_pdf_ptr[2*0+1] = ("_nct_pdf")
+ufunc__nct_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_pdf_double
+ufunc__nct_pdf_ptr[2*1+1] = ("_nct_pdf")
+ufunc__nct_pdf_data[0] = &ufunc__nct_pdf_ptr[2*0]
+ufunc__nct_pdf_data[1] = &ufunc__nct_pdf_ptr[2*1]
+_nct_pdf = np.PyUFunc_FromFuncAndData(ufunc__nct_pdf_loops, ufunc__nct_pdf_data, ufunc__nct_pdf_types, 2, 3, 1, 0, "_nct_pdf", ufunc__nct_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_ppf_loops[2]
+cdef void *ufunc__nct_ppf_ptr[4]
+cdef void *ufunc__nct_ppf_data[2]
+cdef char ufunc__nct_ppf_types[8]
+cdef char *ufunc__nct_ppf_doc = (
+    "_nct_ppf(x, v, l)\n"
+    "\n"
+    "Percent point function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_ppf_types[0] = NPY_FLOAT
+ufunc__nct_ppf_types[1] = NPY_FLOAT
+ufunc__nct_ppf_types[2] = NPY_FLOAT
+ufunc__nct_ppf_types[3] = NPY_FLOAT
+ufunc__nct_ppf_types[4] = NPY_DOUBLE
+ufunc__nct_ppf_types[5] = NPY_DOUBLE
+ufunc__nct_ppf_types[6] = NPY_DOUBLE
+ufunc__nct_ppf_types[7] = NPY_DOUBLE
+ufunc__nct_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_ppf_float
+ufunc__nct_ppf_ptr[2*0+1] = ("_nct_ppf")
+ufunc__nct_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_ppf_double
+ufunc__nct_ppf_ptr[2*1+1] = ("_nct_ppf")
+ufunc__nct_ppf_data[0] = &ufunc__nct_ppf_ptr[2*0]
+ufunc__nct_ppf_data[1] = &ufunc__nct_ppf_ptr[2*1]
+_nct_ppf = np.PyUFunc_FromFuncAndData(ufunc__nct_ppf_loops, ufunc__nct_ppf_data, ufunc__nct_ppf_types, 2, 3, 1, 0, "_nct_ppf", ufunc__nct_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_sf_loops[2]
+cdef void *ufunc__nct_sf_ptr[4]
+cdef void *ufunc__nct_sf_data[2]
+cdef char ufunc__nct_sf_types[8]
+cdef char *ufunc__nct_sf_doc = (
+    "_nct_sf(x, v, l)\n"
+    "\n"
+    "Survival function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_sf_types[0] = NPY_FLOAT
+ufunc__nct_sf_types[1] = NPY_FLOAT
+ufunc__nct_sf_types[2] = NPY_FLOAT
+ufunc__nct_sf_types[3] = NPY_FLOAT
+ufunc__nct_sf_types[4] = NPY_DOUBLE
+ufunc__nct_sf_types[5] = NPY_DOUBLE
+ufunc__nct_sf_types[6] = NPY_DOUBLE
+ufunc__nct_sf_types[7] = NPY_DOUBLE
+ufunc__nct_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_sf_float
+ufunc__nct_sf_ptr[2*0+1] = ("_nct_sf")
+ufunc__nct_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_sf_double
+ufunc__nct_sf_ptr[2*1+1] = ("_nct_sf")
+ufunc__nct_sf_data[0] = &ufunc__nct_sf_ptr[2*0]
+ufunc__nct_sf_data[1] = &ufunc__nct_sf_ptr[2*1]
+_nct_sf = np.PyUFunc_FromFuncAndData(ufunc__nct_sf_loops, ufunc__nct_sf_data, ufunc__nct_sf_types, 2, 3, 1, 0, "_nct_sf", ufunc__nct_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_skewness_loops[2]
+cdef void *ufunc__nct_skewness_ptr[4]
+cdef void *ufunc__nct_skewness_data[2]
+cdef char ufunc__nct_skewness_types[6]
+cdef char *ufunc__nct_skewness_doc = (
+    "_nct_skewness(v, l)\n"
+    "\n"
+    "Skewness of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_skewness_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_skewness_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_skewness_types[0] = NPY_FLOAT
+ufunc__nct_skewness_types[1] = NPY_FLOAT
+ufunc__nct_skewness_types[2] = NPY_FLOAT
+ufunc__nct_skewness_types[3] = NPY_DOUBLE
+ufunc__nct_skewness_types[4] = NPY_DOUBLE
+ufunc__nct_skewness_types[5] = NPY_DOUBLE
+ufunc__nct_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_skewness_float
+ufunc__nct_skewness_ptr[2*0+1] = ("_nct_skewness")
+ufunc__nct_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_skewness_double
+ufunc__nct_skewness_ptr[2*1+1] = ("_nct_skewness")
+ufunc__nct_skewness_data[0] = &ufunc__nct_skewness_ptr[2*0]
+ufunc__nct_skewness_data[1] = &ufunc__nct_skewness_ptr[2*1]
+_nct_skewness = np.PyUFunc_FromFuncAndData(ufunc__nct_skewness_loops, ufunc__nct_skewness_data, ufunc__nct_skewness_types, 2, 2, 1, 0, "_nct_skewness", ufunc__nct_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_variance_loops[2]
+cdef void *ufunc__nct_variance_ptr[4]
+cdef void *ufunc__nct_variance_data[2]
+cdef char ufunc__nct_variance_types[6]
+cdef char *ufunc__nct_variance_doc = (
+    "_nct_variance(v, l)\n"
+    "\n"
+    "Variance of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_variance_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_variance_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_variance_types[0] = NPY_FLOAT
+ufunc__nct_variance_types[1] = NPY_FLOAT
+ufunc__nct_variance_types[2] = NPY_FLOAT
+ufunc__nct_variance_types[3] = NPY_DOUBLE
+ufunc__nct_variance_types[4] = NPY_DOUBLE
+ufunc__nct_variance_types[5] = NPY_DOUBLE
+ufunc__nct_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_variance_float
+ufunc__nct_variance_ptr[2*0+1] = ("_nct_variance")
+ufunc__nct_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_variance_double
+ufunc__nct_variance_ptr[2*1+1] = ("_nct_variance")
+ufunc__nct_variance_data[0] = &ufunc__nct_variance_ptr[2*0]
+ufunc__nct_variance_data[1] = &ufunc__nct_variance_ptr[2*1]
+_nct_variance = np.PyUFunc_FromFuncAndData(ufunc__nct_variance_loops, ufunc__nct_variance_data, ufunc__nct_variance_types, 2, 2, 1, 0, "_nct_variance", ufunc__nct_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_cdf_loops[2]
+cdef void *ufunc__ncx2_cdf_ptr[4]
+cdef void *ufunc__ncx2_cdf_data[2]
+cdef char ufunc__ncx2_cdf_types[8]
+cdef char *ufunc__ncx2_cdf_doc = (
+    "_ncx2_cdf(x, k, l)\n"
+    "\n"
+    "Cumulative density function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_cdf_types[0] = NPY_FLOAT
+ufunc__ncx2_cdf_types[1] = NPY_FLOAT
+ufunc__ncx2_cdf_types[2] = NPY_FLOAT
+ufunc__ncx2_cdf_types[3] = NPY_FLOAT
+ufunc__ncx2_cdf_types[4] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[5] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[6] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[7] = NPY_DOUBLE
+ufunc__ncx2_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_cdf_float
+ufunc__ncx2_cdf_ptr[2*0+1] = ("_ncx2_cdf")
+ufunc__ncx2_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_cdf_double
+ufunc__ncx2_cdf_ptr[2*1+1] = ("_ncx2_cdf")
+ufunc__ncx2_cdf_data[0] = &ufunc__ncx2_cdf_ptr[2*0]
+ufunc__ncx2_cdf_data[1] = &ufunc__ncx2_cdf_ptr[2*1]
+_ncx2_cdf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_cdf_loops, ufunc__ncx2_cdf_data, ufunc__ncx2_cdf_types, 2, 3, 1, 0, "_ncx2_cdf", ufunc__ncx2_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_isf_loops[2]
+cdef void *ufunc__ncx2_isf_ptr[4]
+cdef void *ufunc__ncx2_isf_data[2]
+cdef char ufunc__ncx2_isf_types[8]
+cdef char *ufunc__ncx2_isf_doc = (
+    "_ncx2_isf(x, k, l)\n"
+    "\n"
+    "Inverse survival function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_isf_types[0] = NPY_FLOAT
+ufunc__ncx2_isf_types[1] = NPY_FLOAT
+ufunc__ncx2_isf_types[2] = NPY_FLOAT
+ufunc__ncx2_isf_types[3] = NPY_FLOAT
+ufunc__ncx2_isf_types[4] = NPY_DOUBLE
+ufunc__ncx2_isf_types[5] = NPY_DOUBLE
+ufunc__ncx2_isf_types[6] = NPY_DOUBLE
+ufunc__ncx2_isf_types[7] = NPY_DOUBLE
+ufunc__ncx2_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_isf_float
+ufunc__ncx2_isf_ptr[2*0+1] = ("_ncx2_isf")
+ufunc__ncx2_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_isf_double
+ufunc__ncx2_isf_ptr[2*1+1] = ("_ncx2_isf")
+ufunc__ncx2_isf_data[0] = &ufunc__ncx2_isf_ptr[2*0]
+ufunc__ncx2_isf_data[1] = &ufunc__ncx2_isf_ptr[2*1]
+_ncx2_isf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_isf_loops, ufunc__ncx2_isf_data, ufunc__ncx2_isf_types, 2, 3, 1, 0, "_ncx2_isf", ufunc__ncx2_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_pdf_loops[2]
+cdef void *ufunc__ncx2_pdf_ptr[4]
+cdef void *ufunc__ncx2_pdf_data[2]
+cdef char ufunc__ncx2_pdf_types[8]
+cdef char *ufunc__ncx2_pdf_doc = (
+    "_ncx2_pdf(x, k, l)\n"
+    "\n"
+    "Probability density function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_pdf_types[0] = NPY_FLOAT
+ufunc__ncx2_pdf_types[1] = NPY_FLOAT
+ufunc__ncx2_pdf_types[2] = NPY_FLOAT
+ufunc__ncx2_pdf_types[3] = NPY_FLOAT
+ufunc__ncx2_pdf_types[4] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[5] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[6] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[7] = NPY_DOUBLE
+ufunc__ncx2_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_pdf_float
+ufunc__ncx2_pdf_ptr[2*0+1] = ("_ncx2_pdf")
+ufunc__ncx2_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_pdf_double
+ufunc__ncx2_pdf_ptr[2*1+1] = ("_ncx2_pdf")
+ufunc__ncx2_pdf_data[0] = &ufunc__ncx2_pdf_ptr[2*0]
+ufunc__ncx2_pdf_data[1] = &ufunc__ncx2_pdf_ptr[2*1]
+_ncx2_pdf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_pdf_loops, ufunc__ncx2_pdf_data, ufunc__ncx2_pdf_types, 2, 3, 1, 0, "_ncx2_pdf", ufunc__ncx2_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_ppf_loops[2]
+cdef void *ufunc__ncx2_ppf_ptr[4]
+cdef void *ufunc__ncx2_ppf_data[2]
+cdef char ufunc__ncx2_ppf_types[8]
+cdef char *ufunc__ncx2_ppf_doc = (
+    "_ncx2_ppf(x, k, l)\n"
+    "\n"
+    "Percent point function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_ppf_types[0] = NPY_FLOAT
+ufunc__ncx2_ppf_types[1] = NPY_FLOAT
+ufunc__ncx2_ppf_types[2] = NPY_FLOAT
+ufunc__ncx2_ppf_types[3] = NPY_FLOAT
+ufunc__ncx2_ppf_types[4] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[5] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[6] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[7] = NPY_DOUBLE
+ufunc__ncx2_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_ppf_float
+ufunc__ncx2_ppf_ptr[2*0+1] = ("_ncx2_ppf")
+ufunc__ncx2_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_ppf_double
+ufunc__ncx2_ppf_ptr[2*1+1] = ("_ncx2_ppf")
+ufunc__ncx2_ppf_data[0] = &ufunc__ncx2_ppf_ptr[2*0]
+ufunc__ncx2_ppf_data[1] = &ufunc__ncx2_ppf_ptr[2*1]
+_ncx2_ppf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_ppf_loops, ufunc__ncx2_ppf_data, ufunc__ncx2_ppf_types, 2, 3, 1, 0, "_ncx2_ppf", ufunc__ncx2_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_sf_loops[2]
+cdef void *ufunc__ncx2_sf_ptr[4]
+cdef void *ufunc__ncx2_sf_data[2]
+cdef char ufunc__ncx2_sf_types[8]
+cdef char *ufunc__ncx2_sf_doc = (
+    "_ncx2_sf(x, k, l)\n"
+    "\n"
+    "Survival function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_sf_types[0] = NPY_FLOAT
+ufunc__ncx2_sf_types[1] = NPY_FLOAT
+ufunc__ncx2_sf_types[2] = NPY_FLOAT
+ufunc__ncx2_sf_types[3] = NPY_FLOAT
+ufunc__ncx2_sf_types[4] = NPY_DOUBLE
+ufunc__ncx2_sf_types[5] = NPY_DOUBLE
+ufunc__ncx2_sf_types[6] = NPY_DOUBLE
+ufunc__ncx2_sf_types[7] = NPY_DOUBLE
+ufunc__ncx2_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_sf_float
+ufunc__ncx2_sf_ptr[2*0+1] = ("_ncx2_sf")
+ufunc__ncx2_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_sf_double
+ufunc__ncx2_sf_ptr[2*1+1] = ("_ncx2_sf")
+ufunc__ncx2_sf_data[0] = &ufunc__ncx2_sf_ptr[2*0]
+ufunc__ncx2_sf_data[1] = &ufunc__ncx2_sf_ptr[2*1]
+_ncx2_sf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_sf_loops, ufunc__ncx2_sf_data, ufunc__ncx2_sf_types, 2, 3, 1, 0, "_ncx2_sf", ufunc__ncx2_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__sf_error_test_function_loops[1]
+cdef void *ufunc__sf_error_test_function_ptr[2]
+cdef void *ufunc__sf_error_test_function_data[1]
+cdef char ufunc__sf_error_test_function_types[2]
+cdef char *ufunc__sf_error_test_function_doc = (
+    "Private function; do not use.")
+ufunc__sf_error_test_function_loops[0] = loop_i_i__As_l_l
+ufunc__sf_error_test_function_types[0] = NPY_LONG
+ufunc__sf_error_test_function_types[1] = NPY_LONG
+ufunc__sf_error_test_function_ptr[2*0] = _func__sf_error_test_function
+ufunc__sf_error_test_function_ptr[2*0+1] = ("_sf_error_test_function")
+ufunc__sf_error_test_function_data[0] = &ufunc__sf_error_test_function_ptr[2*0]
+_sf_error_test_function = np.PyUFunc_FromFuncAndData(ufunc__sf_error_test_function_loops, ufunc__sf_error_test_function_data, ufunc__sf_error_test_function_types, 1, 1, 1, 0, "_sf_error_test_function", ufunc__sf_error_test_function_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_cdf_loops[2]
+cdef void *ufunc__skewnorm_cdf_ptr[4]
+cdef void *ufunc__skewnorm_cdf_data[2]
+cdef char ufunc__skewnorm_cdf_types[10]
+cdef char *ufunc__skewnorm_cdf_doc = (
+    "_skewnorm_cdf(x, l, sc, sh)\n"
+    "\n"
+    "Cumulative density function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_cdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_cdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_cdf_types[0] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[1] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[2] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[3] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[4] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_cdf_float
+ufunc__skewnorm_cdf_ptr[2*0+1] = ("_skewnorm_cdf")
+ufunc__skewnorm_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_cdf_double
+ufunc__skewnorm_cdf_ptr[2*1+1] = ("_skewnorm_cdf")
+ufunc__skewnorm_cdf_data[0] = &ufunc__skewnorm_cdf_ptr[2*0]
+ufunc__skewnorm_cdf_data[1] = &ufunc__skewnorm_cdf_ptr[2*1]
+_skewnorm_cdf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_cdf_loops, ufunc__skewnorm_cdf_data, ufunc__skewnorm_cdf_types, 2, 4, 1, 0, "_skewnorm_cdf", ufunc__skewnorm_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_isf_loops[2]
+cdef void *ufunc__skewnorm_isf_ptr[4]
+cdef void *ufunc__skewnorm_isf_data[2]
+cdef char ufunc__skewnorm_isf_types[10]
+cdef char *ufunc__skewnorm_isf_doc = (
+    "_skewnorm_isf(x, l, sc, sh)\n"
+    "\n"
+    "Inverse survival function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_isf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_isf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_isf_types[0] = NPY_FLOAT
+ufunc__skewnorm_isf_types[1] = NPY_FLOAT
+ufunc__skewnorm_isf_types[2] = NPY_FLOAT
+ufunc__skewnorm_isf_types[3] = NPY_FLOAT
+ufunc__skewnorm_isf_types[4] = NPY_FLOAT
+ufunc__skewnorm_isf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_isf_float
+ufunc__skewnorm_isf_ptr[2*0+1] = ("_skewnorm_isf")
+ufunc__skewnorm_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_isf_double
+ufunc__skewnorm_isf_ptr[2*1+1] = ("_skewnorm_isf")
+ufunc__skewnorm_isf_data[0] = &ufunc__skewnorm_isf_ptr[2*0]
+ufunc__skewnorm_isf_data[1] = &ufunc__skewnorm_isf_ptr[2*1]
+_skewnorm_isf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_isf_loops, ufunc__skewnorm_isf_data, ufunc__skewnorm_isf_types, 2, 4, 1, 0, "_skewnorm_isf", ufunc__skewnorm_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_ppf_loops[2]
+cdef void *ufunc__skewnorm_ppf_ptr[4]
+cdef void *ufunc__skewnorm_ppf_data[2]
+cdef char ufunc__skewnorm_ppf_types[10]
+cdef char *ufunc__skewnorm_ppf_doc = (
+    "_skewnorm_ppf(x, l, sc, sh)\n"
+    "\n"
+    "Percent point function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_ppf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_ppf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_ppf_types[0] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[1] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[2] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[3] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[4] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_ppf_float
+ufunc__skewnorm_ppf_ptr[2*0+1] = ("_skewnorm_ppf")
+ufunc__skewnorm_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_ppf_double
+ufunc__skewnorm_ppf_ptr[2*1+1] = ("_skewnorm_ppf")
+ufunc__skewnorm_ppf_data[0] = &ufunc__skewnorm_ppf_ptr[2*0]
+ufunc__skewnorm_ppf_data[1] = &ufunc__skewnorm_ppf_ptr[2*1]
+_skewnorm_ppf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_ppf_loops, ufunc__skewnorm_ppf_data, ufunc__skewnorm_ppf_types, 2, 4, 1, 0, "_skewnorm_ppf", ufunc__skewnorm_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovc_loops[3]
+cdef void *ufunc__smirnovc_ptr[6]
+cdef void *ufunc__smirnovc_data[3]
+cdef char ufunc__smirnovc_types[9]
+cdef char *ufunc__smirnovc_doc = (
+    "_smirnovc(n, d)\n"
+    " Internal function, do not use.")
+ufunc__smirnovc_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovc_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovc_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovc_types[0] = NPY_INTP
+ufunc__smirnovc_types[1] = NPY_DOUBLE
+ufunc__smirnovc_types[2] = NPY_DOUBLE
+ufunc__smirnovc_types[3] = NPY_FLOAT
+ufunc__smirnovc_types[4] = NPY_FLOAT
+ufunc__smirnovc_types[5] = NPY_FLOAT
+ufunc__smirnovc_types[6] = NPY_DOUBLE
+ufunc__smirnovc_types[7] = NPY_DOUBLE
+ufunc__smirnovc_types[8] = NPY_DOUBLE
+ufunc__smirnovc_ptr[2*0] = _func_cephes_smirnovc_wrap
+ufunc__smirnovc_ptr[2*0+1] = ("_smirnovc")
+ufunc__smirnovc_ptr[2*1] = _func_smirnovc_unsafe
+ufunc__smirnovc_ptr[2*1+1] = ("_smirnovc")
+ufunc__smirnovc_ptr[2*2] = _func_smirnovc_unsafe
+ufunc__smirnovc_ptr[2*2+1] = ("_smirnovc")
+ufunc__smirnovc_data[0] = &ufunc__smirnovc_ptr[2*0]
+ufunc__smirnovc_data[1] = &ufunc__smirnovc_ptr[2*1]
+ufunc__smirnovc_data[2] = &ufunc__smirnovc_ptr[2*2]
+_smirnovc = np.PyUFunc_FromFuncAndData(ufunc__smirnovc_loops, ufunc__smirnovc_data, ufunc__smirnovc_types, 3, 2, 1, 0, "_smirnovc", ufunc__smirnovc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovci_loops[3]
+cdef void *ufunc__smirnovci_ptr[6]
+cdef void *ufunc__smirnovci_data[3]
+cdef char ufunc__smirnovci_types[9]
+cdef char *ufunc__smirnovci_doc = (
+    "Internal function, do not use.")
+ufunc__smirnovci_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovci_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovci_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovci_types[0] = NPY_INTP
+ufunc__smirnovci_types[1] = NPY_DOUBLE
+ufunc__smirnovci_types[2] = NPY_DOUBLE
+ufunc__smirnovci_types[3] = NPY_FLOAT
+ufunc__smirnovci_types[4] = NPY_FLOAT
+ufunc__smirnovci_types[5] = NPY_FLOAT
+ufunc__smirnovci_types[6] = NPY_DOUBLE
+ufunc__smirnovci_types[7] = NPY_DOUBLE
+ufunc__smirnovci_types[8] = NPY_DOUBLE
+ufunc__smirnovci_ptr[2*0] = _func_cephes_smirnovci_wrap
+ufunc__smirnovci_ptr[2*0+1] = ("_smirnovci")
+ufunc__smirnovci_ptr[2*1] = _func_smirnovci_unsafe
+ufunc__smirnovci_ptr[2*1+1] = ("_smirnovci")
+ufunc__smirnovci_ptr[2*2] = _func_smirnovci_unsafe
+ufunc__smirnovci_ptr[2*2+1] = ("_smirnovci")
+ufunc__smirnovci_data[0] = &ufunc__smirnovci_ptr[2*0]
+ufunc__smirnovci_data[1] = &ufunc__smirnovci_ptr[2*1]
+ufunc__smirnovci_data[2] = &ufunc__smirnovci_ptr[2*2]
+_smirnovci = np.PyUFunc_FromFuncAndData(ufunc__smirnovci_loops, ufunc__smirnovci_data, ufunc__smirnovci_types, 3, 2, 1, 0, "_smirnovci", ufunc__smirnovci_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovp_loops[3]
+cdef void *ufunc__smirnovp_ptr[6]
+cdef void *ufunc__smirnovp_data[3]
+cdef char ufunc__smirnovp_types[9]
+cdef char *ufunc__smirnovp_doc = (
+    "_smirnovp(n, p)\n"
+    " Internal function, do not use.")
+ufunc__smirnovp_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovp_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovp_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovp_types[0] = NPY_INTP
+ufunc__smirnovp_types[1] = NPY_DOUBLE
+ufunc__smirnovp_types[2] = NPY_DOUBLE
+ufunc__smirnovp_types[3] = NPY_FLOAT
+ufunc__smirnovp_types[4] = NPY_FLOAT
+ufunc__smirnovp_types[5] = NPY_FLOAT
+ufunc__smirnovp_types[6] = NPY_DOUBLE
+ufunc__smirnovp_types[7] = NPY_DOUBLE
+ufunc__smirnovp_types[8] = NPY_DOUBLE
+ufunc__smirnovp_ptr[2*0] = _func_cephes_smirnovp_wrap
+ufunc__smirnovp_ptr[2*0+1] = ("_smirnovp")
+ufunc__smirnovp_ptr[2*1] = _func_smirnovp_unsafe
+ufunc__smirnovp_ptr[2*1+1] = ("_smirnovp")
+ufunc__smirnovp_ptr[2*2] = _func_smirnovp_unsafe
+ufunc__smirnovp_ptr[2*2+1] = ("_smirnovp")
+ufunc__smirnovp_data[0] = &ufunc__smirnovp_ptr[2*0]
+ufunc__smirnovp_data[1] = &ufunc__smirnovp_ptr[2*1]
+ufunc__smirnovp_data[2] = &ufunc__smirnovp_ptr[2*2]
+_smirnovp = np.PyUFunc_FromFuncAndData(ufunc__smirnovp_loops, ufunc__smirnovp_data, ufunc__smirnovp_types, 3, 2, 1, 0, "_smirnovp", ufunc__smirnovp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__stirling2_inexact_loops[2]
+cdef void *ufunc__stirling2_inexact_ptr[4]
+cdef void *ufunc__stirling2_inexact_data[2]
+cdef char ufunc__stirling2_inexact_types[6]
+cdef char *ufunc__stirling2_inexact_doc = (
+    "Internal function, do not use.")
+ufunc__stirling2_inexact_loops[0] = loop_d_dd__As_ff_f
+ufunc__stirling2_inexact_loops[1] = loop_d_dd__As_dd_d
+ufunc__stirling2_inexact_types[0] = NPY_FLOAT
+ufunc__stirling2_inexact_types[1] = NPY_FLOAT
+ufunc__stirling2_inexact_types[2] = NPY_FLOAT
+ufunc__stirling2_inexact_types[3] = NPY_DOUBLE
+ufunc__stirling2_inexact_types[4] = NPY_DOUBLE
+ufunc__stirling2_inexact_types[5] = NPY_DOUBLE
+ufunc__stirling2_inexact_ptr[2*0] = scipy.special._ufuncs_cxx._export__stirling2_inexact
+ufunc__stirling2_inexact_ptr[2*0+1] = ("_stirling2_inexact")
+ufunc__stirling2_inexact_ptr[2*1] = scipy.special._ufuncs_cxx._export__stirling2_inexact
+ufunc__stirling2_inexact_ptr[2*1+1] = ("_stirling2_inexact")
+ufunc__stirling2_inexact_data[0] = &ufunc__stirling2_inexact_ptr[2*0]
+ufunc__stirling2_inexact_data[1] = &ufunc__stirling2_inexact_ptr[2*1]
+_stirling2_inexact = np.PyUFunc_FromFuncAndData(ufunc__stirling2_inexact_loops, ufunc__stirling2_inexact_data, ufunc__stirling2_inexact_types, 2, 2, 1, 0, "_stirling2_inexact", ufunc__stirling2_inexact_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_asymp_large_z_loops[1]
+cdef void *ufunc__struve_asymp_large_z_ptr[2]
+cdef void *ufunc__struve_asymp_large_z_data[1]
+cdef char ufunc__struve_asymp_large_z_types[5]
+cdef char *ufunc__struve_asymp_large_z_doc = (
+    "_struve_asymp_large_z(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using asymptotic expansion\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_asymp_large_z_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_asymp_large_z_types[0] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[1] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[2] = NPY_INTP
+ufunc__struve_asymp_large_z_types[3] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[4] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_ptr[2*0] = _func_cephes__struve_asymp_large_z
+ufunc__struve_asymp_large_z_ptr[2*0+1] = ("_struve_asymp_large_z")
+ufunc__struve_asymp_large_z_data[0] = &ufunc__struve_asymp_large_z_ptr[2*0]
+_struve_asymp_large_z = np.PyUFunc_FromFuncAndData(ufunc__struve_asymp_large_z_loops, ufunc__struve_asymp_large_z_data, ufunc__struve_asymp_large_z_types, 1, 3, 2, 0, "_struve_asymp_large_z", ufunc__struve_asymp_large_z_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_bessel_series_loops[1]
+cdef void *ufunc__struve_bessel_series_ptr[2]
+cdef void *ufunc__struve_bessel_series_data[1]
+cdef char ufunc__struve_bessel_series_types[5]
+cdef char *ufunc__struve_bessel_series_doc = (
+    "_struve_bessel_series(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using Bessel function series\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_bessel_series_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_bessel_series_types[0] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[1] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[2] = NPY_INTP
+ufunc__struve_bessel_series_types[3] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[4] = NPY_DOUBLE
+ufunc__struve_bessel_series_ptr[2*0] = _func_cephes__struve_bessel_series
+ufunc__struve_bessel_series_ptr[2*0+1] = ("_struve_bessel_series")
+ufunc__struve_bessel_series_data[0] = &ufunc__struve_bessel_series_ptr[2*0]
+_struve_bessel_series = np.PyUFunc_FromFuncAndData(ufunc__struve_bessel_series_loops, ufunc__struve_bessel_series_data, ufunc__struve_bessel_series_types, 1, 3, 2, 0, "_struve_bessel_series", ufunc__struve_bessel_series_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_power_series_loops[1]
+cdef void *ufunc__struve_power_series_ptr[2]
+cdef void *ufunc__struve_power_series_data[1]
+cdef char ufunc__struve_power_series_types[5]
+cdef char *ufunc__struve_power_series_doc = (
+    "_struve_power_series(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using power series\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_power_series_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_power_series_types[0] = NPY_DOUBLE
+ufunc__struve_power_series_types[1] = NPY_DOUBLE
+ufunc__struve_power_series_types[2] = NPY_INTP
+ufunc__struve_power_series_types[3] = NPY_DOUBLE
+ufunc__struve_power_series_types[4] = NPY_DOUBLE
+ufunc__struve_power_series_ptr[2*0] = _func_cephes__struve_power_series
+ufunc__struve_power_series_ptr[2*0+1] = ("_struve_power_series")
+ufunc__struve_power_series_data[0] = &ufunc__struve_power_series_ptr[2*0]
+_struve_power_series = np.PyUFunc_FromFuncAndData(ufunc__struve_power_series_loops, ufunc__struve_power_series_data, ufunc__struve_power_series_types, 1, 3, 2, 0, "_struve_power_series", ufunc__struve_power_series_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_agm_loops[2]
+cdef void *ufunc_agm_ptr[4]
+cdef void *ufunc_agm_data[2]
+cdef char ufunc_agm_types[6]
+cdef char *ufunc_agm_doc = (
+    "agm(a, b, out=None)\n"
+    "\n"
+    "Compute the arithmetic-geometric mean of `a` and `b`.\n"
+    "\n"
+    "Start with a_0 = a and b_0 = b and iteratively compute::\n"
+    "\n"
+    "    a_{n+1} = (a_n + b_n)/2\n"
+    "    b_{n+1} = sqrt(a_n*b_n)\n"
+    "\n"
+    "a_n and b_n converge to the same limit as n increases; their common\n"
+    "limit is agm(a, b).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real values only. If the values are both negative, the result\n"
+    "    is negative. If one value is negative and the other is positive,\n"
+    "    `nan` is returned.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The arithmetic-geometric mean of `a` and `b`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import agm\n"
+    ">>> a, b = 24.0, 6.0\n"
+    ">>> agm(a, b)\n"
+    "13.458171481725614\n"
+    "\n"
+    "Compare that result to the iteration:\n"
+    "\n"
+    ">>> while a != b:\n"
+    "...     a, b = (a + b)/2, np.sqrt(a*b)\n"
+    "...     print(\"a = %19.16f  b=%19.16f\" % (a, b))\n"
+    "...\n"
+    "a = 15.0000000000000000  b=12.0000000000000000\n"
+    "a = 13.5000000000000000  b=13.4164078649987388\n"
+    "a = 13.4582039324993694  b=13.4581390309909850\n"
+    "a = 13.4581714817451772  b=13.4581714817060547\n"
+    "a = 13.4581714817256159  b=13.4581714817256159\n"
+    "\n"
+    "When array-like arguments are given, broadcasting applies:\n"
+    "\n"
+    ">>> a = np.array([[1.5], [3], [6]])  # a has shape (3, 1).\n"
+    ">>> b = np.array([6, 12, 24, 48])    # b has shape (4,).\n"
+    ">>> agm(a, b)\n"
+    "array([[  3.36454287,   5.42363427,   9.05798751,  15.53650756],\n"
+    "       [  4.37037309,   6.72908574,  10.84726853,  18.11597502],\n"
+    "       [  6.        ,   8.74074619,  13.45817148,  21.69453707]])")
+ufunc_agm_loops[0] = loop_d_dd__As_ff_f
+ufunc_agm_loops[1] = loop_d_dd__As_dd_d
+ufunc_agm_types[0] = NPY_FLOAT
+ufunc_agm_types[1] = NPY_FLOAT
+ufunc_agm_types[2] = NPY_FLOAT
+ufunc_agm_types[3] = NPY_DOUBLE
+ufunc_agm_types[4] = NPY_DOUBLE
+ufunc_agm_types[5] = NPY_DOUBLE
+ufunc_agm_ptr[2*0] = _func_agm
+ufunc_agm_ptr[2*0+1] = ("agm")
+ufunc_agm_ptr[2*1] = _func_agm
+ufunc_agm_ptr[2*1+1] = ("agm")
+ufunc_agm_data[0] = &ufunc_agm_ptr[2*0]
+ufunc_agm_data[1] = &ufunc_agm_ptr[2*1]
+agm = np.PyUFunc_FromFuncAndData(ufunc_agm_loops, ufunc_agm_data, ufunc_agm_types, 2, 2, 1, 0, "agm", ufunc_agm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtr_loops[3]
+cdef void *ufunc_bdtr_ptr[6]
+cdef void *ufunc_bdtr_data[3]
+cdef char ufunc_bdtr_types[12]
+cdef char *ufunc_bdtr_doc = (
+    "bdtr(k, n, p, out=None)\n"
+    "\n"
+    "Binomial distribution cumulative distribution function.\n"
+    "\n"
+    "Sum of the terms 0 through `floor(k)` of the Binomial probability density.\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtr}(k, n, p) =\n"
+    "    \\sum_{j=0}^{\\lfloor k \\rfloor} {{n}\\choose{j}} p^j (1-p)^{n-j}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (double), rounded down to the nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Probability of `floor(k)` or fewer successes in `n` independent events with\n"
+    "    success probabilities of `p`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtr}(k, n, p) =\n"
+    "    I_{1 - p}(n - \\lfloor k \\rfloor, \\lfloor k \\rfloor + 1).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtr`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtr_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtr_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtr_types[0] = NPY_FLOAT
+ufunc_bdtr_types[1] = NPY_FLOAT
+ufunc_bdtr_types[2] = NPY_FLOAT
+ufunc_bdtr_types[3] = NPY_FLOAT
+ufunc_bdtr_types[4] = NPY_DOUBLE
+ufunc_bdtr_types[5] = NPY_INTP
+ufunc_bdtr_types[6] = NPY_DOUBLE
+ufunc_bdtr_types[7] = NPY_DOUBLE
+ufunc_bdtr_types[8] = NPY_DOUBLE
+ufunc_bdtr_types[9] = NPY_DOUBLE
+ufunc_bdtr_types[10] = NPY_DOUBLE
+ufunc_bdtr_types[11] = NPY_DOUBLE
+ufunc_bdtr_ptr[2*0] = _func_bdtr_unsafe
+ufunc_bdtr_ptr[2*0+1] = ("bdtr")
+ufunc_bdtr_ptr[2*1] = _func_cephes_bdtr_wrap
+ufunc_bdtr_ptr[2*1+1] = ("bdtr")
+ufunc_bdtr_ptr[2*2] = _func_bdtr_unsafe
+ufunc_bdtr_ptr[2*2+1] = ("bdtr")
+ufunc_bdtr_data[0] = &ufunc_bdtr_ptr[2*0]
+ufunc_bdtr_data[1] = &ufunc_bdtr_ptr[2*1]
+ufunc_bdtr_data[2] = &ufunc_bdtr_ptr[2*2]
+bdtr = np.PyUFunc_FromFuncAndData(ufunc_bdtr_loops, ufunc_bdtr_data, ufunc_bdtr_types, 3, 3, 1, 0, "bdtr", ufunc_bdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrc_loops[3]
+cdef void *ufunc_bdtrc_ptr[6]
+cdef void *ufunc_bdtrc_data[3]
+cdef char ufunc_bdtrc_types[12]
+cdef char *ufunc_bdtrc_doc = (
+    "bdtrc(k, n, p, out=None)\n"
+    "\n"
+    "Binomial distribution survival function.\n"
+    "\n"
+    "Sum of the terms `floor(k) + 1` through `n` of the binomial probability\n"
+    "density,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtrc}(k, n, p) =\n"
+    "    \\sum_{j=\\lfloor k \\rfloor +1}^n {{n}\\choose{j}} p^j (1-p)^{n-j}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (double), rounded down to nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (int)\n"
+    "p : array_like\n"
+    "    Probability of success in a single event.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Probability of `floor(k) + 1` or more successes in `n` independent\n"
+    "    events with success probabilities of `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "betainc\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtrc}(k, n, p) = I_{p}(\\lfloor k \\rfloor + 1, n - \\lfloor k \\rfloor).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtrc`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrc_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtrc_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtrc_types[0] = NPY_FLOAT
+ufunc_bdtrc_types[1] = NPY_FLOAT
+ufunc_bdtrc_types[2] = NPY_FLOAT
+ufunc_bdtrc_types[3] = NPY_FLOAT
+ufunc_bdtrc_types[4] = NPY_DOUBLE
+ufunc_bdtrc_types[5] = NPY_INTP
+ufunc_bdtrc_types[6] = NPY_DOUBLE
+ufunc_bdtrc_types[7] = NPY_DOUBLE
+ufunc_bdtrc_types[8] = NPY_DOUBLE
+ufunc_bdtrc_types[9] = NPY_DOUBLE
+ufunc_bdtrc_types[10] = NPY_DOUBLE
+ufunc_bdtrc_types[11] = NPY_DOUBLE
+ufunc_bdtrc_ptr[2*0] = _func_bdtrc_unsafe
+ufunc_bdtrc_ptr[2*0+1] = ("bdtrc")
+ufunc_bdtrc_ptr[2*1] = _func_cephes_bdtrc_wrap
+ufunc_bdtrc_ptr[2*1+1] = ("bdtrc")
+ufunc_bdtrc_ptr[2*2] = _func_bdtrc_unsafe
+ufunc_bdtrc_ptr[2*2+1] = ("bdtrc")
+ufunc_bdtrc_data[0] = &ufunc_bdtrc_ptr[2*0]
+ufunc_bdtrc_data[1] = &ufunc_bdtrc_ptr[2*1]
+ufunc_bdtrc_data[2] = &ufunc_bdtrc_ptr[2*2]
+bdtrc = np.PyUFunc_FromFuncAndData(ufunc_bdtrc_loops, ufunc_bdtrc_data, ufunc_bdtrc_types, 3, 3, 1, 0, "bdtrc", ufunc_bdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtri_loops[3]
+cdef void *ufunc_bdtri_ptr[6]
+cdef void *ufunc_bdtri_data[3]
+cdef char ufunc_bdtri_types[12]
+cdef char *ufunc_bdtri_doc = (
+    "bdtri(k, n, y, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `p`.\n"
+    "\n"
+    "Finds the event probability `p` such that the sum of the terms 0 through\n"
+    "`k` of the binomial probability density is equal to the given cumulative\n"
+    "probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (float), rounded down to the nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (float)\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "p : scalar or ndarray\n"
+    "    The event probability such that `bdtr(\\lfloor k \\rfloor, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "betaincinv\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The computation is carried out using the inverse beta integral function\n"
+    "and the relation,::\n"
+    "\n"
+    "    1 - p = betaincinv(n - k, k + 1, y).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtri`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtri_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtri_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtri_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtri_types[0] = NPY_FLOAT
+ufunc_bdtri_types[1] = NPY_FLOAT
+ufunc_bdtri_types[2] = NPY_FLOAT
+ufunc_bdtri_types[3] = NPY_FLOAT
+ufunc_bdtri_types[4] = NPY_DOUBLE
+ufunc_bdtri_types[5] = NPY_INTP
+ufunc_bdtri_types[6] = NPY_DOUBLE
+ufunc_bdtri_types[7] = NPY_DOUBLE
+ufunc_bdtri_types[8] = NPY_DOUBLE
+ufunc_bdtri_types[9] = NPY_DOUBLE
+ufunc_bdtri_types[10] = NPY_DOUBLE
+ufunc_bdtri_types[11] = NPY_DOUBLE
+ufunc_bdtri_ptr[2*0] = _func_bdtri_unsafe
+ufunc_bdtri_ptr[2*0+1] = ("bdtri")
+ufunc_bdtri_ptr[2*1] = _func_cephes_bdtri_wrap
+ufunc_bdtri_ptr[2*1+1] = ("bdtri")
+ufunc_bdtri_ptr[2*2] = _func_bdtri_unsafe
+ufunc_bdtri_ptr[2*2+1] = ("bdtri")
+ufunc_bdtri_data[0] = &ufunc_bdtri_ptr[2*0]
+ufunc_bdtri_data[1] = &ufunc_bdtri_ptr[2*1]
+ufunc_bdtri_data[2] = &ufunc_bdtri_ptr[2*2]
+bdtri = np.PyUFunc_FromFuncAndData(ufunc_bdtri_loops, ufunc_bdtri_data, ufunc_bdtri_types, 3, 3, 1, 0, "bdtri", ufunc_bdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrik_loops[2]
+cdef void *ufunc_bdtrik_ptr[4]
+cdef void *ufunc_bdtrik_data[2]
+cdef char ufunc_bdtrik_types[8]
+cdef char *ufunc_bdtrik_doc = (
+    "bdtrik(y, n, p, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `k`.\n"
+    "\n"
+    "Finds the number of successes `k` such that the sum of the terms 0 through\n"
+    "`k` of the Binomial probability density for `n` events with probability\n"
+    "`p` is equal to the given cumulative probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "n : array_like\n"
+    "    Number of events (float).\n"
+    "p : array_like\n"
+    "    Success probability (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "k : scalar or ndarray\n"
+    "    The number of successes `k` such that `bdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the\n"
+    "cumulative incomplete beta distribution.\n"
+    "\n"
+    "Computation of `k` involves a search for a value that produces the desired\n"
+    "value of `y`. The search relies on the monotonicity of `y` with `k`.\n"
+    "\n"
+    "Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    ".. [2] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.")
+ufunc_bdtrik_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrik_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_bdtrik_types[0] = NPY_FLOAT
+ufunc_bdtrik_types[1] = NPY_FLOAT
+ufunc_bdtrik_types[2] = NPY_FLOAT
+ufunc_bdtrik_types[3] = NPY_FLOAT
+ufunc_bdtrik_types[4] = NPY_DOUBLE
+ufunc_bdtrik_types[5] = NPY_DOUBLE
+ufunc_bdtrik_types[6] = NPY_DOUBLE
+ufunc_bdtrik_types[7] = NPY_DOUBLE
+ufunc_bdtrik_ptr[2*0] = _func_bdtrik
+ufunc_bdtrik_ptr[2*0+1] = ("bdtrik")
+ufunc_bdtrik_ptr[2*1] = _func_bdtrik
+ufunc_bdtrik_ptr[2*1+1] = ("bdtrik")
+ufunc_bdtrik_data[0] = &ufunc_bdtrik_ptr[2*0]
+ufunc_bdtrik_data[1] = &ufunc_bdtrik_ptr[2*1]
+bdtrik = np.PyUFunc_FromFuncAndData(ufunc_bdtrik_loops, ufunc_bdtrik_data, ufunc_bdtrik_types, 2, 3, 1, 0, "bdtrik", ufunc_bdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrin_loops[2]
+cdef void *ufunc_bdtrin_ptr[4]
+cdef void *ufunc_bdtrin_data[2]
+cdef char ufunc_bdtrin_types[8]
+cdef char *ufunc_bdtrin_doc = (
+    "bdtrin(k, y, p, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `n`.\n"
+    "\n"
+    "Finds the number of events `n` such that the sum of the terms 0 through\n"
+    "`k` of the Binomial probability density for events with probability `p` is\n"
+    "equal to the given cumulative probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (float).\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "p : array_like\n"
+    "    Success probability (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "n : scalar or ndarray\n"
+    "    The number of events `n` such that `bdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the\n"
+    "cumulative incomplete beta distribution.\n"
+    "\n"
+    "Computation of `n` involves a search for a value that produces the desired\n"
+    "value of `y`. The search relies on the monotonicity of `y` with `n`.\n"
+    "\n"
+    "Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    ".. [2] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.")
+ufunc_bdtrin_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrin_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_bdtrin_types[0] = NPY_FLOAT
+ufunc_bdtrin_types[1] = NPY_FLOAT
+ufunc_bdtrin_types[2] = NPY_FLOAT
+ufunc_bdtrin_types[3] = NPY_FLOAT
+ufunc_bdtrin_types[4] = NPY_DOUBLE
+ufunc_bdtrin_types[5] = NPY_DOUBLE
+ufunc_bdtrin_types[6] = NPY_DOUBLE
+ufunc_bdtrin_types[7] = NPY_DOUBLE
+ufunc_bdtrin_ptr[2*0] = _func_bdtrin
+ufunc_bdtrin_ptr[2*0+1] = ("bdtrin")
+ufunc_bdtrin_ptr[2*1] = _func_bdtrin
+ufunc_bdtrin_ptr[2*1+1] = ("bdtrin")
+ufunc_bdtrin_data[0] = &ufunc_bdtrin_ptr[2*0]
+ufunc_bdtrin_data[1] = &ufunc_bdtrin_ptr[2*1]
+bdtrin = np.PyUFunc_FromFuncAndData(ufunc_bdtrin_loops, ufunc_bdtrin_data, ufunc_bdtrin_types, 2, 3, 1, 0, "bdtrin", ufunc_bdtrin_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betainc_loops[2]
+cdef void *ufunc_betainc_ptr[4]
+cdef void *ufunc_betainc_data[2]
+cdef char ufunc_betainc_types[8]
+cdef char *ufunc_betainc_doc = (
+    "betainc(a, b, x, out=None)\n"
+    "\n"
+    "Regularized incomplete beta function.\n"
+    "\n"
+    "Computes the regularized incomplete beta function, defined as [1]_:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    I_x(a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)} \\int_0^x\n"
+    "    t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "for :math:`0 \\leq x \\leq 1`.\n"
+    "\n"
+    "This function is the cumulative distribution function for the beta\n"
+    "distribution; its range is [0, 1].\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "beta : beta function\n"
+    "betaincinv : inverse of the regularized incomplete beta function\n"
+    "betaincc : complement of the regularized incomplete beta function\n"
+    "scipy.stats.beta : beta distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The term *regularized* in the name of this function refers to the\n"
+    "scaling of the function by the gamma function terms shown in the\n"
+    "formula.  When not qualified as *regularized*, the name *incomplete\n"
+    "beta function* often refers to just the integral expression,\n"
+    "without the gamma terms.  One can use the function `beta` from\n"
+    "`scipy.special` to get this \"nonregularized\" incomplete beta\n"
+    "function by multiplying the result of ``betainc(a, b, x)`` by\n"
+    "``beta(a, b)``.\n"
+    "\n"
+    "This function wraps the ``ibeta`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "\n"
+    "Let :math:`B(a, b)` be the `beta` function.\n"
+    "\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "The coefficient in terms of `gamma` is equal to\n"
+    ":math:`1/B(a, b)`. Also, when :math:`x=1`\n"
+    "the integral is equal to :math:`B(a, b)`.\n"
+    "Therefore, :math:`I_{x=1}(a, b) = 1` for any :math:`a, b`.\n"
+    "\n"
+    ">>> sc.betainc(0.2, 3.5, 1.0)\n"
+    "1.0\n"
+    "\n"
+    "It satisfies\n"
+    ":math:`I_x(a, b) = x^a F(a, 1-b, a+1, x)/ (aB(a, b))`,\n"
+    "where :math:`F` is the hypergeometric function `hyp2f1`:\n"
+    "\n"
+    ">>> a, b, x = 1.4, 3.1, 0.5\n"
+    ">>> x**a * sc.hyp2f1(a, 1 - b, a + 1, x)/(a * sc.beta(a, b))\n"
+    "0.8148904036225295\n"
+    ">>> sc.betainc(a, b, x)\n"
+    "0.8148904036225296\n"
+    "\n"
+    "This functions satisfies the relationship\n"
+    ":math:`I_x(a, b) = 1 - I_{1-x}(b, a)`:\n"
+    "\n"
+    ">>> sc.betainc(2.2, 3.1, 0.4)\n"
+    "0.49339638807619446\n"
+    ">>> 1 - sc.betainc(3.1, 2.2, 1 - 0.4)\n"
+    "0.49339638807619446")
+ufunc_betainc_loops[0] = loop_f_fff__As_fff_f
+ufunc_betainc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betainc_types[0] = NPY_FLOAT
+ufunc_betainc_types[1] = NPY_FLOAT
+ufunc_betainc_types[2] = NPY_FLOAT
+ufunc_betainc_types[3] = NPY_FLOAT
+ufunc_betainc_types[4] = NPY_DOUBLE
+ufunc_betainc_types[5] = NPY_DOUBLE
+ufunc_betainc_types[6] = NPY_DOUBLE
+ufunc_betainc_types[7] = NPY_DOUBLE
+ufunc_betainc_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibeta_float
+ufunc_betainc_ptr[2*0+1] = ("betainc")
+ufunc_betainc_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibeta_double
+ufunc_betainc_ptr[2*1+1] = ("betainc")
+ufunc_betainc_data[0] = &ufunc_betainc_ptr[2*0]
+ufunc_betainc_data[1] = &ufunc_betainc_ptr[2*1]
+betainc = np.PyUFunc_FromFuncAndData(ufunc_betainc_loops, ufunc_betainc_data, ufunc_betainc_types, 2, 3, 1, 0, "betainc", ufunc_betainc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betaincc_loops[2]
+cdef void *ufunc_betaincc_ptr[4]
+cdef void *ufunc_betaincc_data[2]
+cdef char ufunc_betaincc_types[8]
+cdef char *ufunc_betaincc_doc = (
+    "betaincc(a, b, x, out=None)\n"
+    "\n"
+    "Complement of the regularized incomplete beta function.\n"
+    "\n"
+    "Computes the complement of the regularized incomplete beta function,\n"
+    "defined as [1]_:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\bar{I}_x(a, b) = 1 - I_x(a, b)\n"
+    "                    = 1 - \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)} \\int_0^x\n"
+    "                              t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "for :math:`0 \\leq x \\leq 1`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "betaincinv : inverse of the regularized incomplete beta function\n"
+    "betainccinv :\n"
+    "    inverse of the complement of the regularized incomplete beta function\n"
+    "beta : beta function\n"
+    "scipy.stats.beta : beta distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.11.0\n"
+    "\n"
+    "This function wraps the ``ibetac`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import betaincc, betainc\n"
+    "\n"
+    "The naive calculation ``1 - betainc(a, b, x)`` loses precision when\n"
+    "the values of ``betainc(a, b, x)`` are close to 1:\n"
+    "\n"
+    ">>> 1 - betainc(0.5, 8, [0.9, 0.99, 0.999])\n"
+    "array([2.0574632e-09, 0.0000000e+00, 0.0000000e+00])\n"
+    "\n"
+    "By using ``betaincc``, we get the correct values:\n"
+    "\n"
+    ">>> betaincc(0.5, 8, [0.9, 0.99, 0.999])\n"
+    "array([2.05746321e-09, 1.97259354e-17, 1.96467954e-25])")
+ufunc_betaincc_loops[0] = loop_f_fff__As_fff_f
+ufunc_betaincc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betaincc_types[0] = NPY_FLOAT
+ufunc_betaincc_types[1] = NPY_FLOAT
+ufunc_betaincc_types[2] = NPY_FLOAT
+ufunc_betaincc_types[3] = NPY_FLOAT
+ufunc_betaincc_types[4] = NPY_DOUBLE
+ufunc_betaincc_types[5] = NPY_DOUBLE
+ufunc_betaincc_types[6] = NPY_DOUBLE
+ufunc_betaincc_types[7] = NPY_DOUBLE
+ufunc_betaincc_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibetac_float
+ufunc_betaincc_ptr[2*0+1] = ("betaincc")
+ufunc_betaincc_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibetac_double
+ufunc_betaincc_ptr[2*1+1] = ("betaincc")
+ufunc_betaincc_data[0] = &ufunc_betaincc_ptr[2*0]
+ufunc_betaincc_data[1] = &ufunc_betaincc_ptr[2*1]
+betaincc = np.PyUFunc_FromFuncAndData(ufunc_betaincc_loops, ufunc_betaincc_data, ufunc_betaincc_types, 2, 3, 1, 0, "betaincc", ufunc_betaincc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betainccinv_loops[2]
+cdef void *ufunc_betainccinv_ptr[4]
+cdef void *ufunc_betainccinv_data[2]
+cdef char ufunc_betainccinv_types[8]
+cdef char *ufunc_betainccinv_doc = (
+    "betainccinv(a, b, y, out=None)\n"
+    "\n"
+    "Inverse of the complemented regularized incomplete beta function.\n"
+    "\n"
+    "Computes :math:`x` such that:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    y = 1 - I_x(a, b) = 1 - \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n"
+    "    \\int_0^x t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "where :math:`I_x` is the normalized incomplete beta function `betainc`\n"
+    "and :math:`\\Gamma` is the `gamma` function [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "y : array_like\n"
+    "    Real-valued input\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the inverse of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "betaincc : complement of the regularized incomplete beta function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.11.0\n"
+    "\n"
+    "This function wraps the ``ibetac_inv`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import betainccinv, betaincc\n"
+    "\n"
+    "This function is the inverse of `betaincc` for fixed\n"
+    "values of :math:`a` and :math:`b`.\n"
+    "\n"
+    ">>> a, b = 1.2, 3.1\n"
+    ">>> y = betaincc(a, b, 0.2)\n"
+    ">>> betainccinv(a, b, y)\n"
+    "0.2\n"
+    "\n"
+    ">>> a, b = 7, 2.5\n"
+    ">>> x = betainccinv(a, b, 0.875)\n"
+    ">>> betaincc(a, b, x)\n"
+    "0.875")
+ufunc_betainccinv_loops[0] = loop_f_fff__As_fff_f
+ufunc_betainccinv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betainccinv_types[0] = NPY_FLOAT
+ufunc_betainccinv_types[1] = NPY_FLOAT
+ufunc_betainccinv_types[2] = NPY_FLOAT
+ufunc_betainccinv_types[3] = NPY_FLOAT
+ufunc_betainccinv_types[4] = NPY_DOUBLE
+ufunc_betainccinv_types[5] = NPY_DOUBLE
+ufunc_betainccinv_types[6] = NPY_DOUBLE
+ufunc_betainccinv_types[7] = NPY_DOUBLE
+ufunc_betainccinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibetac_inv_float
+ufunc_betainccinv_ptr[2*0+1] = ("betainccinv")
+ufunc_betainccinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibetac_inv_double
+ufunc_betainccinv_ptr[2*1+1] = ("betainccinv")
+ufunc_betainccinv_data[0] = &ufunc_betainccinv_ptr[2*0]
+ufunc_betainccinv_data[1] = &ufunc_betainccinv_ptr[2*1]
+betainccinv = np.PyUFunc_FromFuncAndData(ufunc_betainccinv_loops, ufunc_betainccinv_data, ufunc_betainccinv_types, 2, 3, 1, 0, "betainccinv", ufunc_betainccinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betaincinv_loops[2]
+cdef void *ufunc_betaincinv_ptr[4]
+cdef void *ufunc_betaincinv_data[2]
+cdef char ufunc_betaincinv_types[8]
+cdef char *ufunc_betaincinv_doc = (
+    "betaincinv(a, b, y, out=None)\n"
+    "\n"
+    "Inverse of the regularized incomplete beta function.\n"
+    "\n"
+    "Computes :math:`x` such that:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    y = I_x(a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n"
+    "    \\int_0^x t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "where :math:`I_x` is the normalized incomplete beta function `betainc`\n"
+    "and :math:`\\Gamma` is the `gamma` function [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "y : array_like\n"
+    "    Real-valued input\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the inverse of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "gamma : gamma function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function wraps the ``ibeta_inv`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "This function is the inverse of `betainc` for fixed\n"
+    "values of :math:`a` and :math:`b`.\n"
+    "\n"
+    ">>> a, b = 1.2, 3.1\n"
+    ">>> y = sc.betainc(a, b, 0.2)\n"
+    ">>> sc.betaincinv(a, b, y)\n"
+    "0.2\n"
+    ">>>\n"
+    ">>> a, b = 7.5, 0.4\n"
+    ">>> x = sc.betaincinv(a, b, 0.5)\n"
+    ">>> sc.betainc(a, b, x)\n"
+    "0.5")
+ufunc_betaincinv_loops[0] = loop_f_fff__As_fff_f
+ufunc_betaincinv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betaincinv_types[0] = NPY_FLOAT
+ufunc_betaincinv_types[1] = NPY_FLOAT
+ufunc_betaincinv_types[2] = NPY_FLOAT
+ufunc_betaincinv_types[3] = NPY_FLOAT
+ufunc_betaincinv_types[4] = NPY_DOUBLE
+ufunc_betaincinv_types[5] = NPY_DOUBLE
+ufunc_betaincinv_types[6] = NPY_DOUBLE
+ufunc_betaincinv_types[7] = NPY_DOUBLE
+ufunc_betaincinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibeta_inv_float
+ufunc_betaincinv_ptr[2*0+1] = ("betaincinv")
+ufunc_betaincinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibeta_inv_double
+ufunc_betaincinv_ptr[2*1+1] = ("betaincinv")
+ufunc_betaincinv_data[0] = &ufunc_betaincinv_ptr[2*0]
+ufunc_betaincinv_data[1] = &ufunc_betaincinv_ptr[2*1]
+betaincinv = np.PyUFunc_FromFuncAndData(ufunc_betaincinv_loops, ufunc_betaincinv_data, ufunc_betaincinv_types, 2, 3, 1, 0, "betaincinv", ufunc_betaincinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_boxcox_loops[2]
+cdef void *ufunc_boxcox_ptr[4]
+cdef void *ufunc_boxcox_data[2]
+cdef char ufunc_boxcox_types[6]
+cdef char *ufunc_boxcox_doc = (
+    "boxcox(x, lmbda, out=None)\n"
+    "\n"
+    "Compute the Box-Cox transformation.\n"
+    "\n"
+    "The Box-Cox transformation is::\n"
+    "\n"
+    "    y = (x**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(x)                  if lmbda == 0\n"
+    "\n"
+    "Returns `nan` if ``x < 0``.\n"
+    "Returns `-inf` if ``x == 0`` and ``lmbda < 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.14.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox\n"
+    ">>> boxcox([1, 4, 10], 2.5)\n"
+    "array([   0.        ,   12.4       ,  126.09110641])\n"
+    ">>> boxcox(2, [0, 1, 2])\n"
+    "array([ 0.69314718,  1.        ,  1.5       ])")
+ufunc_boxcox_loops[0] = loop_d_dd__As_ff_f
+ufunc_boxcox_loops[1] = loop_d_dd__As_dd_d
+ufunc_boxcox_types[0] = NPY_FLOAT
+ufunc_boxcox_types[1] = NPY_FLOAT
+ufunc_boxcox_types[2] = NPY_FLOAT
+ufunc_boxcox_types[3] = NPY_DOUBLE
+ufunc_boxcox_types[4] = NPY_DOUBLE
+ufunc_boxcox_types[5] = NPY_DOUBLE
+ufunc_boxcox_ptr[2*0] = _func_boxcox
+ufunc_boxcox_ptr[2*0+1] = ("boxcox")
+ufunc_boxcox_ptr[2*1] = _func_boxcox
+ufunc_boxcox_ptr[2*1+1] = ("boxcox")
+ufunc_boxcox_data[0] = &ufunc_boxcox_ptr[2*0]
+ufunc_boxcox_data[1] = &ufunc_boxcox_ptr[2*1]
+boxcox = np.PyUFunc_FromFuncAndData(ufunc_boxcox_loops, ufunc_boxcox_data, ufunc_boxcox_types, 2, 2, 1, 0, "boxcox", ufunc_boxcox_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_boxcox1p_loops[2]
+cdef void *ufunc_boxcox1p_ptr[4]
+cdef void *ufunc_boxcox1p_data[2]
+cdef char ufunc_boxcox1p_types[6]
+cdef char *ufunc_boxcox1p_doc = (
+    "boxcox1p(x, lmbda, out=None)\n"
+    "\n"
+    "Compute the Box-Cox transformation of 1 + `x`.\n"
+    "\n"
+    "The Box-Cox transformation computed by `boxcox1p` is::\n"
+    "\n"
+    "    y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(1+x)                    if lmbda == 0\n"
+    "\n"
+    "Returns `nan` if ``x < -1``.\n"
+    "Returns `-inf` if ``x == -1`` and ``lmbda < 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.14.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox1p\n"
+    ">>> boxcox1p(1e-4, [0, 0.5, 1])\n"
+    "array([  9.99950003e-05,   9.99975001e-05,   1.00000000e-04])\n"
+    ">>> boxcox1p([0.01, 0.1], 0.25)\n"
+    "array([ 0.00996272,  0.09645476])")
+ufunc_boxcox1p_loops[0] = loop_d_dd__As_ff_f
+ufunc_boxcox1p_loops[1] = loop_d_dd__As_dd_d
+ufunc_boxcox1p_types[0] = NPY_FLOAT
+ufunc_boxcox1p_types[1] = NPY_FLOAT
+ufunc_boxcox1p_types[2] = NPY_FLOAT
+ufunc_boxcox1p_types[3] = NPY_DOUBLE
+ufunc_boxcox1p_types[4] = NPY_DOUBLE
+ufunc_boxcox1p_types[5] = NPY_DOUBLE
+ufunc_boxcox1p_ptr[2*0] = _func_boxcox1p
+ufunc_boxcox1p_ptr[2*0+1] = ("boxcox1p")
+ufunc_boxcox1p_ptr[2*1] = _func_boxcox1p
+ufunc_boxcox1p_ptr[2*1+1] = ("boxcox1p")
+ufunc_boxcox1p_data[0] = &ufunc_boxcox1p_ptr[2*0]
+ufunc_boxcox1p_data[1] = &ufunc_boxcox1p_ptr[2*1]
+boxcox1p = np.PyUFunc_FromFuncAndData(ufunc_boxcox1p_loops, ufunc_boxcox1p_data, ufunc_boxcox1p_types, 2, 2, 1, 0, "boxcox1p", ufunc_boxcox1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_btdtria_loops[2]
+cdef void *ufunc_btdtria_ptr[4]
+cdef void *ufunc_btdtria_data[2]
+cdef char ufunc_btdtria_types[8]
+cdef char *ufunc_btdtria_doc = (
+    "btdtria(p, b, x, out=None)\n"
+    "\n"
+    "Inverse of `betainc` with respect to `a`.\n"
+    "\n"
+    "This is the inverse of the beta cumulative distribution function, `betainc`,\n"
+    "considered as a function of `a`, returning the value of `a` for which\n"
+    "`betainc(a, b, x) = p`, or\n"
+    "\n"
+    ".. math::\n"
+    "    p = \\int_0^x \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} t^{a-1} (1-t)^{b-1}\\,dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "b : array_like\n"
+    "    Shape parameter (`b` > 0).\n"
+    "x : array_like\n"
+    "    The quantile, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "a : scalar or ndarray\n"
+    "    The value of the shape parameter `a` such that `betainc(a, b, x) = p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "btdtrib : Inverse of the beta cumulative distribution function, with respect to `b`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `a` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `a`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Algorithm 708: Significant Digit Computation of the Incomplete Beta\n"
+    "       Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.")
+ufunc_btdtria_loops[0] = loop_d_ddd__As_fff_f
+ufunc_btdtria_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_btdtria_types[0] = NPY_FLOAT
+ufunc_btdtria_types[1] = NPY_FLOAT
+ufunc_btdtria_types[2] = NPY_FLOAT
+ufunc_btdtria_types[3] = NPY_FLOAT
+ufunc_btdtria_types[4] = NPY_DOUBLE
+ufunc_btdtria_types[5] = NPY_DOUBLE
+ufunc_btdtria_types[6] = NPY_DOUBLE
+ufunc_btdtria_types[7] = NPY_DOUBLE
+ufunc_btdtria_ptr[2*0] = _func_btdtria
+ufunc_btdtria_ptr[2*0+1] = ("btdtria")
+ufunc_btdtria_ptr[2*1] = _func_btdtria
+ufunc_btdtria_ptr[2*1+1] = ("btdtria")
+ufunc_btdtria_data[0] = &ufunc_btdtria_ptr[2*0]
+ufunc_btdtria_data[1] = &ufunc_btdtria_ptr[2*1]
+btdtria = np.PyUFunc_FromFuncAndData(ufunc_btdtria_loops, ufunc_btdtria_data, ufunc_btdtria_types, 2, 3, 1, 0, "btdtria", ufunc_btdtria_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_btdtrib_loops[2]
+cdef void *ufunc_btdtrib_ptr[4]
+cdef void *ufunc_btdtrib_data[2]
+cdef char ufunc_btdtrib_types[8]
+cdef char *ufunc_btdtrib_doc = (
+    "btdtria(a, p, x, out=None)\n"
+    "\n"
+    "Inverse of `betainc` with respect to `b`.\n"
+    "\n"
+    "This is the inverse of the beta cumulative distribution function, `betainc`,\n"
+    "considered as a function of `b`, returning the value of `b` for which\n"
+    "`betainc(a, b, x) = p`, or\n"
+    "\n"
+    ".. math::\n"
+    "    p = \\int_0^x \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} t^{a-1} (1-t)^{b-1}\\,dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    Shape parameter (`a` > 0).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "x : array_like\n"
+    "    The quantile, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "b : scalar or ndarray\n"
+    "    The value of the shape parameter `b` such that `betainc(a, b, x) = p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "btdtria : Inverse of the beta cumulative distribution function, with respect to `a`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `b` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `b`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Algorithm 708: Significant Digit Computation of the Incomplete Beta\n"
+    "       Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.")
+ufunc_btdtrib_loops[0] = loop_d_ddd__As_fff_f
+ufunc_btdtrib_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_btdtrib_types[0] = NPY_FLOAT
+ufunc_btdtrib_types[1] = NPY_FLOAT
+ufunc_btdtrib_types[2] = NPY_FLOAT
+ufunc_btdtrib_types[3] = NPY_FLOAT
+ufunc_btdtrib_types[4] = NPY_DOUBLE
+ufunc_btdtrib_types[5] = NPY_DOUBLE
+ufunc_btdtrib_types[6] = NPY_DOUBLE
+ufunc_btdtrib_types[7] = NPY_DOUBLE
+ufunc_btdtrib_ptr[2*0] = _func_btdtrib
+ufunc_btdtrib_ptr[2*0+1] = ("btdtrib")
+ufunc_btdtrib_ptr[2*1] = _func_btdtrib
+ufunc_btdtrib_ptr[2*1+1] = ("btdtrib")
+ufunc_btdtrib_data[0] = &ufunc_btdtrib_ptr[2*0]
+ufunc_btdtrib_data[1] = &ufunc_btdtrib_ptr[2*1]
+btdtrib = np.PyUFunc_FromFuncAndData(ufunc_btdtrib_loops, ufunc_btdtrib_data, ufunc_btdtrib_types, 2, 3, 1, 0, "btdtrib", ufunc_btdtrib_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtr_loops[2]
+cdef void *ufunc_chdtr_ptr[4]
+cdef void *ufunc_chdtr_data[2]
+cdef char ufunc_chdtr_types[6]
+cdef char *ufunc_chdtr_doc = (
+    "chdtr(v, x, out=None)\n"
+    "\n"
+    "Chi square cumulative distribution function.\n"
+    "\n"
+    "Returns the area under the left tail (from 0 to `x`) of the Chi\n"
+    "square probability density function with `v` degrees of freedom:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\frac{1}{2^{v/2} \\Gamma(v/2)} \\int_0^x t^{v/2 - 1} e^{-t/2} dt\n"
+    "\n"
+    "Here :math:`\\Gamma` is the Gamma function; see `gamma`. This\n"
+    "integral can be expressed in terms of the regularized lower\n"
+    "incomplete gamma function `gammainc` as\n"
+    "``gammainc(v / 2, x / 2)``. [1]_\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "x : array_like\n"
+    "    Upper bound of the integral.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the cumulative distribution function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtrc, chdtri, chdtriv, gammainc\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It can be expressed in terms of the regularized lower incomplete\n"
+    "gamma function.\n"
+    "\n"
+    ">>> v = 1\n"
+    ">>> x = np.arange(4)\n"
+    ">>> sc.chdtr(v, x)\n"
+    "array([0.        , 0.68268949, 0.84270079, 0.91673548])\n"
+    ">>> sc.gammainc(v / 2, x / 2)\n"
+    "array([0.        , 0.68268949, 0.84270079, 0.91673548])")
+ufunc_chdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtr_types[0] = NPY_FLOAT
+ufunc_chdtr_types[1] = NPY_FLOAT
+ufunc_chdtr_types[2] = NPY_FLOAT
+ufunc_chdtr_types[3] = NPY_DOUBLE
+ufunc_chdtr_types[4] = NPY_DOUBLE
+ufunc_chdtr_types[5] = NPY_DOUBLE
+ufunc_chdtr_ptr[2*0] = _func_xsf_chdtr
+ufunc_chdtr_ptr[2*0+1] = ("chdtr")
+ufunc_chdtr_ptr[2*1] = _func_xsf_chdtr
+ufunc_chdtr_ptr[2*1+1] = ("chdtr")
+ufunc_chdtr_data[0] = &ufunc_chdtr_ptr[2*0]
+ufunc_chdtr_data[1] = &ufunc_chdtr_ptr[2*1]
+chdtr = np.PyUFunc_FromFuncAndData(ufunc_chdtr_loops, ufunc_chdtr_data, ufunc_chdtr_types, 2, 2, 1, 0, "chdtr", ufunc_chdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtrc_loops[2]
+cdef void *ufunc_chdtrc_ptr[4]
+cdef void *ufunc_chdtrc_data[2]
+cdef char ufunc_chdtrc_types[6]
+cdef char *ufunc_chdtrc_doc = (
+    "chdtrc(v, x, out=None)\n"
+    "\n"
+    "Chi square survival function.\n"
+    "\n"
+    "Returns the area under the right hand tail (from `x` to infinity)\n"
+    "of the Chi square probability density function with `v` degrees of\n"
+    "freedom:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\frac{1}{2^{v/2} \\Gamma(v/2)} \\int_x^\\infty t^{v/2 - 1} e^{-t/2} dt\n"
+    "\n"
+    "Here :math:`\\Gamma` is the Gamma function; see `gamma`. This\n"
+    "integral can be expressed in terms of the regularized upper\n"
+    "incomplete gamma function `gammaincc` as\n"
+    "``gammaincc(v / 2, x / 2)``. [1]_\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "x : array_like\n"
+    "    Lower bound of the integral.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the survival function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtr, chdtri, chdtriv, gammaincc\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It can be expressed in terms of the regularized upper incomplete\n"
+    "gamma function.\n"
+    "\n"
+    ">>> v = 1\n"
+    ">>> x = np.arange(4)\n"
+    ">>> sc.chdtrc(v, x)\n"
+    "array([1.        , 0.31731051, 0.15729921, 0.08326452])\n"
+    ">>> sc.gammaincc(v / 2, x / 2)\n"
+    "array([1.        , 0.31731051, 0.15729921, 0.08326452])")
+ufunc_chdtrc_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtrc_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtrc_types[0] = NPY_FLOAT
+ufunc_chdtrc_types[1] = NPY_FLOAT
+ufunc_chdtrc_types[2] = NPY_FLOAT
+ufunc_chdtrc_types[3] = NPY_DOUBLE
+ufunc_chdtrc_types[4] = NPY_DOUBLE
+ufunc_chdtrc_types[5] = NPY_DOUBLE
+ufunc_chdtrc_ptr[2*0] = _func_xsf_chdtrc
+ufunc_chdtrc_ptr[2*0+1] = ("chdtrc")
+ufunc_chdtrc_ptr[2*1] = _func_xsf_chdtrc
+ufunc_chdtrc_ptr[2*1+1] = ("chdtrc")
+ufunc_chdtrc_data[0] = &ufunc_chdtrc_ptr[2*0]
+ufunc_chdtrc_data[1] = &ufunc_chdtrc_ptr[2*1]
+chdtrc = np.PyUFunc_FromFuncAndData(ufunc_chdtrc_loops, ufunc_chdtrc_data, ufunc_chdtrc_types, 2, 2, 1, 0, "chdtrc", ufunc_chdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtri_loops[2]
+cdef void *ufunc_chdtri_ptr[4]
+cdef void *ufunc_chdtri_data[2]
+cdef char ufunc_chdtri_types[6]
+cdef char *ufunc_chdtri_doc = (
+    "chdtri(v, p, out=None)\n"
+    "\n"
+    "Inverse to `chdtrc` with respect to `x`.\n"
+    "\n"
+    "Returns `x` such that ``chdtrc(v, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "p : array_like\n"
+    "    Probability.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value so that the probability a Chi square random variable\n"
+    "    with `v` degrees of freedom is greater than `x` equals `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtrc, chdtr, chdtriv\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It inverts `chdtrc`.\n"
+    "\n"
+    ">>> v, p = 1, 0.3\n"
+    ">>> sc.chdtrc(v, sc.chdtri(v, p))\n"
+    "0.3\n"
+    ">>> x = 1\n"
+    ">>> sc.chdtri(v, sc.chdtrc(v, x))\n"
+    "1.0")
+ufunc_chdtri_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtri_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtri_types[0] = NPY_FLOAT
+ufunc_chdtri_types[1] = NPY_FLOAT
+ufunc_chdtri_types[2] = NPY_FLOAT
+ufunc_chdtri_types[3] = NPY_DOUBLE
+ufunc_chdtri_types[4] = NPY_DOUBLE
+ufunc_chdtri_types[5] = NPY_DOUBLE
+ufunc_chdtri_ptr[2*0] = _func_xsf_chdtri
+ufunc_chdtri_ptr[2*0+1] = ("chdtri")
+ufunc_chdtri_ptr[2*1] = _func_xsf_chdtri
+ufunc_chdtri_ptr[2*1+1] = ("chdtri")
+ufunc_chdtri_data[0] = &ufunc_chdtri_ptr[2*0]
+ufunc_chdtri_data[1] = &ufunc_chdtri_ptr[2*1]
+chdtri = np.PyUFunc_FromFuncAndData(ufunc_chdtri_loops, ufunc_chdtri_data, ufunc_chdtri_types, 2, 2, 1, 0, "chdtri", ufunc_chdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtriv_loops[2]
+cdef void *ufunc_chdtriv_ptr[4]
+cdef void *ufunc_chdtriv_data[2]
+cdef char ufunc_chdtriv_types[6]
+cdef char *ufunc_chdtriv_doc = (
+    "chdtriv(p, x, out=None)\n"
+    "\n"
+    "Inverse to `chdtr` with respect to `v`.\n"
+    "\n"
+    "Returns `v` such that ``chdtr(v, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability that the Chi square random variable is less than\n"
+    "    or equal to `x`.\n"
+    "x : array_like\n"
+    "    Nonnegative input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Degrees of freedom.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtr, chdtrc, chdtri\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It inverts `chdtr`.\n"
+    "\n"
+    ">>> p, x = 0.5, 1\n"
+    ">>> sc.chdtr(sc.chdtriv(p, x), x)\n"
+    "0.5000000000202172\n"
+    ">>> v = 1\n"
+    ">>> sc.chdtriv(sc.chdtr(v, x), v)\n"
+    "1.0000000000000013")
+ufunc_chdtriv_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtriv_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtriv_types[0] = NPY_FLOAT
+ufunc_chdtriv_types[1] = NPY_FLOAT
+ufunc_chdtriv_types[2] = NPY_FLOAT
+ufunc_chdtriv_types[3] = NPY_DOUBLE
+ufunc_chdtriv_types[4] = NPY_DOUBLE
+ufunc_chdtriv_types[5] = NPY_DOUBLE
+ufunc_chdtriv_ptr[2*0] = _func_chdtriv
+ufunc_chdtriv_ptr[2*0+1] = ("chdtriv")
+ufunc_chdtriv_ptr[2*1] = _func_chdtriv
+ufunc_chdtriv_ptr[2*1+1] = ("chdtriv")
+ufunc_chdtriv_data[0] = &ufunc_chdtriv_ptr[2*0]
+ufunc_chdtriv_data[1] = &ufunc_chdtriv_ptr[2*1]
+chdtriv = np.PyUFunc_FromFuncAndData(ufunc_chdtriv_loops, ufunc_chdtriv_data, ufunc_chdtriv_types, 2, 2, 1, 0, "chdtriv", ufunc_chdtriv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtr_loops[2]
+cdef void *ufunc_chndtr_ptr[4]
+cdef void *ufunc_chndtr_data[2]
+cdef char ufunc_chndtr_types[8]
+cdef char *ufunc_chndtr_doc = (
+    "chndtr(x, df, nc, out=None)\n"
+    "\n"
+    "Non-central chi square cumulative distribution function\n"
+    "\n"
+    "The cumulative distribution function is given by:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P(\\chi^{\\prime 2} \\vert \\nu, \\lambda) =\\sum_{j=0}^{\\infty}\n"
+    "    e^{-\\lambda /2}\n"
+    "    \\frac{(\\lambda /2)^j}{j!} P(\\chi^{\\prime 2} \\vert \\nu + 2j),\n"
+    "\n"
+    "where :math:`\\nu > 0` is the degrees of freedom (``df``) and\n"
+    ":math:`\\lambda \\geq 0` is the non-centrality parameter (``nc``).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value of the non-central chi square cumulative distribution function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtrix, chndtridf, chndtrinc")
+ufunc_chndtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtr_types[0] = NPY_FLOAT
+ufunc_chndtr_types[1] = NPY_FLOAT
+ufunc_chndtr_types[2] = NPY_FLOAT
+ufunc_chndtr_types[3] = NPY_FLOAT
+ufunc_chndtr_types[4] = NPY_DOUBLE
+ufunc_chndtr_types[5] = NPY_DOUBLE
+ufunc_chndtr_types[6] = NPY_DOUBLE
+ufunc_chndtr_types[7] = NPY_DOUBLE
+ufunc_chndtr_ptr[2*0] = _func_chndtr
+ufunc_chndtr_ptr[2*0+1] = ("chndtr")
+ufunc_chndtr_ptr[2*1] = _func_chndtr
+ufunc_chndtr_ptr[2*1+1] = ("chndtr")
+ufunc_chndtr_data[0] = &ufunc_chndtr_ptr[2*0]
+ufunc_chndtr_data[1] = &ufunc_chndtr_ptr[2*1]
+chndtr = np.PyUFunc_FromFuncAndData(ufunc_chndtr_loops, ufunc_chndtr_data, ufunc_chndtr_types, 2, 3, 1, 0, "chndtr", ufunc_chndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtridf_loops[2]
+cdef void *ufunc_chndtridf_ptr[4]
+cdef void *ufunc_chndtridf_data[2]
+cdef char ufunc_chndtridf_types[8]
+cdef char *ufunc_chndtridf_doc = (
+    "chndtridf(x, p, nc, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `df`\n"
+    "\n"
+    "Calculated using a search to find a value for `df` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    Degrees of freedom\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtrix, chndtrinc")
+ufunc_chndtridf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtridf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtridf_types[0] = NPY_FLOAT
+ufunc_chndtridf_types[1] = NPY_FLOAT
+ufunc_chndtridf_types[2] = NPY_FLOAT
+ufunc_chndtridf_types[3] = NPY_FLOAT
+ufunc_chndtridf_types[4] = NPY_DOUBLE
+ufunc_chndtridf_types[5] = NPY_DOUBLE
+ufunc_chndtridf_types[6] = NPY_DOUBLE
+ufunc_chndtridf_types[7] = NPY_DOUBLE
+ufunc_chndtridf_ptr[2*0] = _func_chndtridf
+ufunc_chndtridf_ptr[2*0+1] = ("chndtridf")
+ufunc_chndtridf_ptr[2*1] = _func_chndtridf
+ufunc_chndtridf_ptr[2*1+1] = ("chndtridf")
+ufunc_chndtridf_data[0] = &ufunc_chndtridf_ptr[2*0]
+ufunc_chndtridf_data[1] = &ufunc_chndtridf_ptr[2*1]
+chndtridf = np.PyUFunc_FromFuncAndData(ufunc_chndtridf_loops, ufunc_chndtridf_data, ufunc_chndtridf_types, 2, 3, 1, 0, "chndtridf", ufunc_chndtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtrinc_loops[2]
+cdef void *ufunc_chndtrinc_ptr[4]
+cdef void *ufunc_chndtrinc_data[2]
+cdef char ufunc_chndtrinc_types[8]
+cdef char *ufunc_chndtrinc_doc = (
+    "chndtrinc(x, df, p, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `nc`\n"
+    "\n"
+    "Calculated using a search to find a value for `df` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Non-centrality\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtrix, chndtrinc")
+ufunc_chndtrinc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtrinc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtrinc_types[0] = NPY_FLOAT
+ufunc_chndtrinc_types[1] = NPY_FLOAT
+ufunc_chndtrinc_types[2] = NPY_FLOAT
+ufunc_chndtrinc_types[3] = NPY_FLOAT
+ufunc_chndtrinc_types[4] = NPY_DOUBLE
+ufunc_chndtrinc_types[5] = NPY_DOUBLE
+ufunc_chndtrinc_types[6] = NPY_DOUBLE
+ufunc_chndtrinc_types[7] = NPY_DOUBLE
+ufunc_chndtrinc_ptr[2*0] = _func_chndtrinc
+ufunc_chndtrinc_ptr[2*0+1] = ("chndtrinc")
+ufunc_chndtrinc_ptr[2*1] = _func_chndtrinc
+ufunc_chndtrinc_ptr[2*1+1] = ("chndtrinc")
+ufunc_chndtrinc_data[0] = &ufunc_chndtrinc_ptr[2*0]
+ufunc_chndtrinc_data[1] = &ufunc_chndtrinc_ptr[2*1]
+chndtrinc = np.PyUFunc_FromFuncAndData(ufunc_chndtrinc_loops, ufunc_chndtrinc_data, ufunc_chndtrinc_types, 2, 3, 1, 0, "chndtrinc", ufunc_chndtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtrix_loops[2]
+cdef void *ufunc_chndtrix_ptr[4]
+cdef void *ufunc_chndtrix_data[2]
+cdef char ufunc_chndtrix_types[8]
+cdef char *ufunc_chndtrix_doc = (
+    "chndtrix(p, df, nc, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `x`\n"
+    "\n"
+    "Calculated using a search to find a value for `x` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value so that the probability a non-central Chi square random variable\n"
+    "    with `df` degrees of freedom and non-centrality, `nc`, is greater than\n"
+    "    `x` equals `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtridf, chndtrinc")
+ufunc_chndtrix_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtrix_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtrix_types[0] = NPY_FLOAT
+ufunc_chndtrix_types[1] = NPY_FLOAT
+ufunc_chndtrix_types[2] = NPY_FLOAT
+ufunc_chndtrix_types[3] = NPY_FLOAT
+ufunc_chndtrix_types[4] = NPY_DOUBLE
+ufunc_chndtrix_types[5] = NPY_DOUBLE
+ufunc_chndtrix_types[6] = NPY_DOUBLE
+ufunc_chndtrix_types[7] = NPY_DOUBLE
+ufunc_chndtrix_ptr[2*0] = _func_chndtrix
+ufunc_chndtrix_ptr[2*0+1] = ("chndtrix")
+ufunc_chndtrix_ptr[2*1] = _func_chndtrix
+ufunc_chndtrix_ptr[2*1+1] = ("chndtrix")
+ufunc_chndtrix_data[0] = &ufunc_chndtrix_ptr[2*0]
+ufunc_chndtrix_data[1] = &ufunc_chndtrix_ptr[2*1]
+chndtrix = np.PyUFunc_FromFuncAndData(ufunc_chndtrix_loops, ufunc_chndtrix_data, ufunc_chndtrix_types, 2, 3, 1, 0, "chndtrix", ufunc_chndtrix_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_dawsn_loops[4]
+cdef void *ufunc_dawsn_ptr[8]
+cdef void *ufunc_dawsn_data[4]
+cdef char ufunc_dawsn_types[8]
+cdef char *ufunc_dawsn_doc = (
+    "dawsn(x, out=None)\n"
+    "\n"
+    "Dawson's integral.\n"
+    "\n"
+    "Computes::\n"
+    "\n"
+    "    exp(-x**2) * integral(exp(t**2), t=0..x).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Function parameter.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Value of the integral.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "wofz, erf, erfc, erfcx, erfi\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-15, 15, num=1000)\n"
+    ">>> plt.plot(x, special.dawsn(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$dawsn(x)$')\n"
+    ">>> plt.show()")
+ufunc_dawsn_loops[0] = loop_d_d__As_f_f
+ufunc_dawsn_loops[1] = loop_d_d__As_d_d
+ufunc_dawsn_loops[2] = loop_D_D__As_F_F
+ufunc_dawsn_loops[3] = loop_D_D__As_D_D
+ufunc_dawsn_types[0] = NPY_FLOAT
+ufunc_dawsn_types[1] = NPY_FLOAT
+ufunc_dawsn_types[2] = NPY_DOUBLE
+ufunc_dawsn_types[3] = NPY_DOUBLE
+ufunc_dawsn_types[4] = NPY_CFLOAT
+ufunc_dawsn_types[5] = NPY_CFLOAT
+ufunc_dawsn_types[6] = NPY_CDOUBLE
+ufunc_dawsn_types[7] = NPY_CDOUBLE
+ufunc_dawsn_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn
+ufunc_dawsn_ptr[2*0+1] = ("dawsn")
+ufunc_dawsn_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn
+ufunc_dawsn_ptr[2*1+1] = ("dawsn")
+ufunc_dawsn_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn_complex
+ufunc_dawsn_ptr[2*2+1] = ("dawsn")
+ufunc_dawsn_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn_complex
+ufunc_dawsn_ptr[2*3+1] = ("dawsn")
+ufunc_dawsn_data[0] = &ufunc_dawsn_ptr[2*0]
+ufunc_dawsn_data[1] = &ufunc_dawsn_ptr[2*1]
+ufunc_dawsn_data[2] = &ufunc_dawsn_ptr[2*2]
+ufunc_dawsn_data[3] = &ufunc_dawsn_ptr[2*3]
+dawsn = np.PyUFunc_FromFuncAndData(ufunc_dawsn_loops, ufunc_dawsn_data, ufunc_dawsn_types, 4, 1, 1, 0, "dawsn", ufunc_dawsn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprc_loops[4]
+cdef void *ufunc_elliprc_ptr[8]
+cdef void *ufunc_elliprc_data[4]
+cdef char ufunc_elliprc_types[12]
+cdef char *ufunc_elliprc_doc = (
+    "elliprc(x, y, out=None)\n"
+    "\n"
+    "Degenerate symmetric elliptic integral.\n"
+    "\n"
+    "The function RC is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{C}}(x, y) =\n"
+    "       \\frac{1}{2} \\int_0^{+\\infty} (t + x)^{-1/2} (t + y)^{-1} dt\n"
+    "       = R_{\\mathrm{F}}(x, y, y)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Real or complex input parameters. `x` can be any number in the\n"
+    "    complex plane cut along the negative real axis. `y` must be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If `y` is real and negative, the Cauchy\n"
+    "    principal value is returned. If both of `x` and `y` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "RC is a degenerate case of the symmetric integral RF: ``elliprc(x, y) ==\n"
+    "elliprf(x, y, y)``. It is an elementary function rather than an elliptic\n"
+    "integral.\n"
+    "\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E6\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprc\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprc(scale*x, scale*y)\n"
+    "(0.5484493976710874-0.4169557678995833j)\n"
+    "\n"
+    ">>> elliprc(x, y)/np.sqrt(scale)\n"
+    "(0.5484493976710874-0.41695576789958333j)\n"
+    "\n"
+    "When the two arguments coincide, the integral is particularly\n"
+    "simple:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprc(x, x)\n"
+    "(0.4299173120614631-0.3041729818745595j)\n"
+    "\n"
+    ">>> 1/np.sqrt(x)\n"
+    "(0.4299173120614631-0.30417298187455954j)\n"
+    "\n"
+    "Another simple case: the first argument vanishes:\n"
+    "\n"
+    ">>> y = 1.2 + 3.4j\n"
+    ">>> elliprc(0, y)\n"
+    "(0.6753125346116815-0.47779380263880866j)\n"
+    "\n"
+    ">>> np.pi/2/np.sqrt(y)\n"
+    "(0.6753125346116815-0.4777938026388088j)\n"
+    "\n"
+    "When `x` and `y` are both positive, we can express\n"
+    ":math:`R_C(x,y)` in terms of more elementary functions.  For the\n"
+    "case :math:`0 \\le x < y`,\n"
+    "\n"
+    ">>> x = 3.2\n"
+    ">>> y = 6.\n"
+    ">>> elliprc(x, y)\n"
+    "0.44942991498453444\n"
+    "\n"
+    ">>> np.arctan(np.sqrt((y-x)/x))/np.sqrt(y-x)\n"
+    "0.44942991498453433\n"
+    "\n"
+    "And for the case :math:`0 \\le y < x`,\n"
+    "\n"
+    ">>> x = 6.\n"
+    ">>> y = 3.2\n"
+    ">>> elliprc(x,y)\n"
+    "0.4989837501576147\n"
+    "\n"
+    ">>> np.log((np.sqrt(x)+np.sqrt(x-y))/np.sqrt(y))/np.sqrt(x-y)\n"
+    "0.49898375015761476")
+ufunc_elliprc_loops[0] = loop_d_dd__As_ff_f
+ufunc_elliprc_loops[1] = loop_d_dd__As_dd_d
+ufunc_elliprc_loops[2] = loop_D_DD__As_FF_F
+ufunc_elliprc_loops[3] = loop_D_DD__As_DD_D
+ufunc_elliprc_types[0] = NPY_FLOAT
+ufunc_elliprc_types[1] = NPY_FLOAT
+ufunc_elliprc_types[2] = NPY_FLOAT
+ufunc_elliprc_types[3] = NPY_DOUBLE
+ufunc_elliprc_types[4] = NPY_DOUBLE
+ufunc_elliprc_types[5] = NPY_DOUBLE
+ufunc_elliprc_types[6] = NPY_CFLOAT
+ufunc_elliprc_types[7] = NPY_CFLOAT
+ufunc_elliprc_types[8] = NPY_CFLOAT
+ufunc_elliprc_types[9] = NPY_CDOUBLE
+ufunc_elliprc_types[10] = NPY_CDOUBLE
+ufunc_elliprc_types[11] = NPY_CDOUBLE
+ufunc_elliprc_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RC
+ufunc_elliprc_ptr[2*0+1] = ("elliprc")
+ufunc_elliprc_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RC
+ufunc_elliprc_ptr[2*1+1] = ("elliprc")
+ufunc_elliprc_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RC
+ufunc_elliprc_ptr[2*2+1] = ("elliprc")
+ufunc_elliprc_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RC
+ufunc_elliprc_ptr[2*3+1] = ("elliprc")
+ufunc_elliprc_data[0] = &ufunc_elliprc_ptr[2*0]
+ufunc_elliprc_data[1] = &ufunc_elliprc_ptr[2*1]
+ufunc_elliprc_data[2] = &ufunc_elliprc_ptr[2*2]
+ufunc_elliprc_data[3] = &ufunc_elliprc_ptr[2*3]
+elliprc = np.PyUFunc_FromFuncAndData(ufunc_elliprc_loops, ufunc_elliprc_data, ufunc_elliprc_types, 4, 2, 1, 0, "elliprc", ufunc_elliprc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprd_loops[4]
+cdef void *ufunc_elliprd_ptr[8]
+cdef void *ufunc_elliprd_data[4]
+cdef char ufunc_elliprd_types[16]
+cdef char *ufunc_elliprd_doc = (
+    "elliprd(x, y, z, out=None)\n"
+    "\n"
+    "Symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "The function RD is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{D}}(x, y, z) =\n"
+    "       \\frac{3}{2} \\int_0^{+\\infty} [(t + x) (t + y)]^{-1/2} (t + z)^{-3/2}\n"
+    "       dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x` or `y` can be any number in the\n"
+    "    complex plane cut along the negative real axis, but at most one of them\n"
+    "    can be zero, while `z` must be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric elliptic integral.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "RD is a degenerate case of the elliptic integral RJ: ``elliprd(x, y, z) ==\n"
+    "elliprj(x, y, z, z)``.\n"
+    "\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E5\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprd\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprd(scale*x, scale*y, scale*z)\n"
+    "(-0.03703043835680379-0.24500934665683802j)\n"
+    "\n"
+    ">>> elliprd(x, y, z)*np.power(scale, -1.5)\n"
+    "(-0.0370304383568038-0.24500934665683805j)\n"
+    "\n"
+    "All three arguments coincide:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprd(x, x, x)\n"
+    "(-0.03986825876151896-0.14051741840449586j)\n"
+    "\n"
+    ">>> np.power(x, -1.5)\n"
+    "(-0.03986825876151894-0.14051741840449583j)\n"
+    "\n"
+    "The so-called \"second lemniscate constant\":\n"
+    "\n"
+    ">>> elliprd(0, 2, 1)/3\n"
+    "0.5990701173677961\n"
+    "\n"
+    ">>> from scipy.special import gamma\n"
+    ">>> gamma(0.75)**2/np.sqrt(2*np.pi)\n"
+    "0.5990701173677959")
+ufunc_elliprd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprd_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprd_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprd_types[0] = NPY_FLOAT
+ufunc_elliprd_types[1] = NPY_FLOAT
+ufunc_elliprd_types[2] = NPY_FLOAT
+ufunc_elliprd_types[3] = NPY_FLOAT
+ufunc_elliprd_types[4] = NPY_DOUBLE
+ufunc_elliprd_types[5] = NPY_DOUBLE
+ufunc_elliprd_types[6] = NPY_DOUBLE
+ufunc_elliprd_types[7] = NPY_DOUBLE
+ufunc_elliprd_types[8] = NPY_CFLOAT
+ufunc_elliprd_types[9] = NPY_CFLOAT
+ufunc_elliprd_types[10] = NPY_CFLOAT
+ufunc_elliprd_types[11] = NPY_CFLOAT
+ufunc_elliprd_types[12] = NPY_CDOUBLE
+ufunc_elliprd_types[13] = NPY_CDOUBLE
+ufunc_elliprd_types[14] = NPY_CDOUBLE
+ufunc_elliprd_types[15] = NPY_CDOUBLE
+ufunc_elliprd_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RD
+ufunc_elliprd_ptr[2*0+1] = ("elliprd")
+ufunc_elliprd_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RD
+ufunc_elliprd_ptr[2*1+1] = ("elliprd")
+ufunc_elliprd_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RD
+ufunc_elliprd_ptr[2*2+1] = ("elliprd")
+ufunc_elliprd_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RD
+ufunc_elliprd_ptr[2*3+1] = ("elliprd")
+ufunc_elliprd_data[0] = &ufunc_elliprd_ptr[2*0]
+ufunc_elliprd_data[1] = &ufunc_elliprd_ptr[2*1]
+ufunc_elliprd_data[2] = &ufunc_elliprd_ptr[2*2]
+ufunc_elliprd_data[3] = &ufunc_elliprd_ptr[2*3]
+elliprd = np.PyUFunc_FromFuncAndData(ufunc_elliprd_loops, ufunc_elliprd_data, ufunc_elliprd_types, 4, 3, 1, 0, "elliprd", ufunc_elliprd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprf_loops[4]
+cdef void *ufunc_elliprf_ptr[8]
+cdef void *ufunc_elliprf_data[4]
+cdef char ufunc_elliprf_types[16]
+cdef char *ufunc_elliprf_doc = (
+    "elliprf(x, y, z, out=None)\n"
+    "\n"
+    "Completely-symmetric elliptic integral of the first kind.\n"
+    "\n"
+    "The function RF is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{F}}(x, y, z) =\n"
+    "       \\frac{1}{2} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2} dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` can be any number in\n"
+    "    the complex plane cut along the negative real axis, but at most one of\n"
+    "    them can be zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the return\n"
+    "    value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order (cf.:\n"
+    "https://dlmf.nist.gov/19.36.i) and the AGM algorithm for the complete\n"
+    "integral. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E1\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprf\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprf(scale*x, scale*y, scale*z)\n"
+    "(0.5328051227278146-0.4008623567957094j)\n"
+    "\n"
+    ">>> elliprf(x, y, z)/np.sqrt(scale)\n"
+    "(0.5328051227278147-0.4008623567957095j)\n"
+    "\n"
+    "All three arguments coincide:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprf(x, x, x)\n"
+    "(0.42991731206146316-0.30417298187455954j)\n"
+    "\n"
+    ">>> 1/np.sqrt(x)\n"
+    "(0.4299173120614631-0.30417298187455954j)\n"
+    "\n"
+    "The so-called \"first lemniscate constant\":\n"
+    "\n"
+    ">>> elliprf(0, 1, 2)\n"
+    "1.3110287771460598\n"
+    "\n"
+    ">>> from scipy.special import gamma\n"
+    ">>> gamma(0.25)**2/(4*np.sqrt(2*np.pi))\n"
+    "1.3110287771460598")
+ufunc_elliprf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprf_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprf_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprf_types[0] = NPY_FLOAT
+ufunc_elliprf_types[1] = NPY_FLOAT
+ufunc_elliprf_types[2] = NPY_FLOAT
+ufunc_elliprf_types[3] = NPY_FLOAT
+ufunc_elliprf_types[4] = NPY_DOUBLE
+ufunc_elliprf_types[5] = NPY_DOUBLE
+ufunc_elliprf_types[6] = NPY_DOUBLE
+ufunc_elliprf_types[7] = NPY_DOUBLE
+ufunc_elliprf_types[8] = NPY_CFLOAT
+ufunc_elliprf_types[9] = NPY_CFLOAT
+ufunc_elliprf_types[10] = NPY_CFLOAT
+ufunc_elliprf_types[11] = NPY_CFLOAT
+ufunc_elliprf_types[12] = NPY_CDOUBLE
+ufunc_elliprf_types[13] = NPY_CDOUBLE
+ufunc_elliprf_types[14] = NPY_CDOUBLE
+ufunc_elliprf_types[15] = NPY_CDOUBLE
+ufunc_elliprf_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RF
+ufunc_elliprf_ptr[2*0+1] = ("elliprf")
+ufunc_elliprf_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RF
+ufunc_elliprf_ptr[2*1+1] = ("elliprf")
+ufunc_elliprf_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RF
+ufunc_elliprf_ptr[2*2+1] = ("elliprf")
+ufunc_elliprf_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RF
+ufunc_elliprf_ptr[2*3+1] = ("elliprf")
+ufunc_elliprf_data[0] = &ufunc_elliprf_ptr[2*0]
+ufunc_elliprf_data[1] = &ufunc_elliprf_ptr[2*1]
+ufunc_elliprf_data[2] = &ufunc_elliprf_ptr[2*2]
+ufunc_elliprf_data[3] = &ufunc_elliprf_ptr[2*3]
+elliprf = np.PyUFunc_FromFuncAndData(ufunc_elliprf_loops, ufunc_elliprf_data, ufunc_elliprf_types, 4, 3, 1, 0, "elliprf", ufunc_elliprf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprg_loops[4]
+cdef void *ufunc_elliprg_ptr[8]
+cdef void *ufunc_elliprg_data[4]
+cdef char ufunc_elliprg_types[16]
+cdef char *ufunc_elliprg_doc = (
+    "elliprg(x, y, z, out=None)\n"
+    "\n"
+    "Completely-symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "The function RG is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{G}}(x, y, z) =\n"
+    "       \\frac{1}{4} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2}\n"
+    "       \\left(\\frac{x}{t + x} + \\frac{y}{t + y} + \\frac{z}{t + z}\\right) t\n"
+    "       dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` can be any number in\n"
+    "    the complex plane cut along the negative real axis.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the return\n"
+    "    value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The implementation uses the relation [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    2 R_{\\mathrm{G}}(x, y, z) =\n"
+    "       z R_{\\mathrm{F}}(x, y, z) -\n"
+    "       \\frac{1}{3} (x - z) (y - z) R_{\\mathrm{D}}(x, y, z) +\n"
+    "       \\sqrt{\\frac{x y}{z}}\n"
+    "\n"
+    "and the symmetry of `x`, `y`, `z` when at least one non-zero parameter can\n"
+    "be chosen as the pivot. When one of the arguments is close to zero, the AGM\n"
+    "method is applied instead. Other special cases are computed following Ref.\n"
+    "[2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    ".. [2] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E1\n"
+    "       https://dlmf.nist.gov/19.20.ii\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprg\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprg(scale*x, scale*y, scale*z)\n"
+    "(1.195936862005246+0.8470988320464167j)\n"
+    "\n"
+    ">>> elliprg(x, y, z)*np.sqrt(scale)\n"
+    "(1.195936862005246+0.8470988320464165j)\n"
+    "\n"
+    "Simplifications:\n"
+    "\n"
+    ">>> elliprg(0, y, y)\n"
+    "1.756203682760182\n"
+    "\n"
+    ">>> 0.25*np.pi*np.sqrt(y)\n"
+    "1.7562036827601817\n"
+    "\n"
+    ">>> elliprg(0, 0, z)\n"
+    "1.224744871391589\n"
+    "\n"
+    ">>> 0.5*np.sqrt(z)\n"
+    "1.224744871391589\n"
+    "\n"
+    "The surface area of a triaxial ellipsoid with semiaxes ``a``, ``b``, and\n"
+    "``c`` is given by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    S = 4 \\pi a b c R_{\\mathrm{G}}(1 / a^2, 1 / b^2, 1 / c^2).\n"
+    "\n"
+    ">>> def ellipsoid_area(a, b, c):\n"
+    "...     r = 4.0 * np.pi * a * b * c\n"
+    "...     return r * elliprg(1.0 / (a * a), 1.0 / (b * b), 1.0 / (c * c))\n"
+    ">>> print(ellipsoid_area(1, 3, 5))\n"
+    "108.62688289491807")
+ufunc_elliprg_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprg_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprg_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprg_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprg_types[0] = NPY_FLOAT
+ufunc_elliprg_types[1] = NPY_FLOAT
+ufunc_elliprg_types[2] = NPY_FLOAT
+ufunc_elliprg_types[3] = NPY_FLOAT
+ufunc_elliprg_types[4] = NPY_DOUBLE
+ufunc_elliprg_types[5] = NPY_DOUBLE
+ufunc_elliprg_types[6] = NPY_DOUBLE
+ufunc_elliprg_types[7] = NPY_DOUBLE
+ufunc_elliprg_types[8] = NPY_CFLOAT
+ufunc_elliprg_types[9] = NPY_CFLOAT
+ufunc_elliprg_types[10] = NPY_CFLOAT
+ufunc_elliprg_types[11] = NPY_CFLOAT
+ufunc_elliprg_types[12] = NPY_CDOUBLE
+ufunc_elliprg_types[13] = NPY_CDOUBLE
+ufunc_elliprg_types[14] = NPY_CDOUBLE
+ufunc_elliprg_types[15] = NPY_CDOUBLE
+ufunc_elliprg_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RG
+ufunc_elliprg_ptr[2*0+1] = ("elliprg")
+ufunc_elliprg_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RG
+ufunc_elliprg_ptr[2*1+1] = ("elliprg")
+ufunc_elliprg_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RG
+ufunc_elliprg_ptr[2*2+1] = ("elliprg")
+ufunc_elliprg_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RG
+ufunc_elliprg_ptr[2*3+1] = ("elliprg")
+ufunc_elliprg_data[0] = &ufunc_elliprg_ptr[2*0]
+ufunc_elliprg_data[1] = &ufunc_elliprg_ptr[2*1]
+ufunc_elliprg_data[2] = &ufunc_elliprg_ptr[2*2]
+ufunc_elliprg_data[3] = &ufunc_elliprg_ptr[2*3]
+elliprg = np.PyUFunc_FromFuncAndData(ufunc_elliprg_loops, ufunc_elliprg_data, ufunc_elliprg_types, 4, 3, 1, 0, "elliprg", ufunc_elliprg_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprj_loops[4]
+cdef void *ufunc_elliprj_ptr[8]
+cdef void *ufunc_elliprj_data[4]
+cdef char ufunc_elliprj_types[20]
+cdef char *ufunc_elliprj_doc = (
+    "elliprj(x, y, z, p, out=None)\n"
+    "\n"
+    "Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "The function RJ is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{J}}(x, y, z, p) =\n"
+    "       \\frac{3}{2} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2}\n"
+    "       (t + p)^{-1} dt\n"
+    "\n"
+    ".. warning::\n"
+    "    This function should be considered experimental when the inputs are\n"
+    "    unbalanced.  Check correctness with another independent implementation.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z, p : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` are numbers in\n"
+    "    the complex plane cut along the negative real axis (subject to further\n"
+    "    constraints, see Notes), and at most one of them can be zero. `p` must\n"
+    "    be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, `z`, and `p` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "    If `p` is real and negative, while `x`, `y`, and `z` are real,\n"
+    "    non-negative, and at most one of them is zero, the Cauchy principal\n"
+    "    value is returned. [1]_ [2]_\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [3]_ The algorithm is slightly\n"
+    "different from its earlier incarnation as it appears in [1]_, in that the\n"
+    "call to `elliprc` (or ``atan``/``atanh``, see [4]_) is no longer needed in\n"
+    "the inner loop. Asymptotic approximations are used where arguments differ\n"
+    "widely in the order of magnitude. [5]_\n"
+    "\n"
+    "The input values are subject to certain sufficient but not necessary\n"
+    "constraints when input arguments are complex. Notably, ``x``, ``y``, and\n"
+    "``z`` must have non-negative real parts, unless two of them are\n"
+    "non-negative and complex-conjugates to each other while the other is a real\n"
+    "non-negative number. [1]_ If the inputs do not satisfy the sufficient\n"
+    "condition described in Ref. [1]_ they are rejected outright with the output\n"
+    "set to NaN.\n"
+    "\n"
+    "In the case where one of ``x``, ``y``, and ``z`` is equal to ``p``, the\n"
+    "function ``elliprd`` should be preferred because of its less restrictive\n"
+    "domain.\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    ".. [2] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.20.iii\n"
+    ".. [3] B. C. Carlson, J. FitzSimmons, \"Reduction Theorems for Elliptic\n"
+    "       Integrands with the Square Root of Two Quadratic Factors,\" J.\n"
+    "       Comput. Appl. Math., vol. 118, nos. 1-2, pp. 71-85, 2000.\n"
+    "       https://doi.org/10.1016/S0377-0427(00)00282-X\n"
+    ".. [4] F. Johansson, \"Numerical Evaluation of Elliptic Functions, Elliptic\n"
+    "       Integrals and Modular Forms,\" in J. Blumlein, C. Schneider, P.\n"
+    "       Paule, eds., \"Elliptic Integrals, Elliptic Functions and Modular\n"
+    "       Forms in Quantum Field Theory,\" pp. 269-293, 2019 (Cham,\n"
+    "       Switzerland: Springer Nature Switzerland)\n"
+    "       https://arxiv.org/abs/1806.06725\n"
+    "       https://doi.org/10.1007/978-3-030-04480-0\n"
+    ".. [5] B. C. Carlson, J. L. Gustafson, \"Asymptotic Approximations for\n"
+    "       Symmetric Elliptic Integrals,\" SIAM J. Math. Anls., vol. 25, no. 2,\n"
+    "       pp. 288-303, 1994.\n"
+    "       https://arxiv.org/abs/math/9310223\n"
+    "       https://doi.org/10.1137/S0036141092228477\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprj\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> p = 7.\n"
+    ">>> scale = 0.3 - 0.4j\n"
+    ">>> elliprj(scale*x, scale*y, scale*z, scale*p)\n"
+    "(0.10834905565679157+0.19694950747103812j)\n"
+    "\n"
+    ">>> elliprj(x, y, z, p)*np.power(scale, -1.5)\n"
+    "(0.10834905565679556+0.19694950747103854j)\n"
+    "\n"
+    "Reduction to simpler elliptic integral:\n"
+    "\n"
+    ">>> elliprj(x, y, z, z)\n"
+    "(0.08288462362195129-0.028376809745123258j)\n"
+    "\n"
+    ">>> from scipy.special import elliprd\n"
+    ">>> elliprd(x, y, z)\n"
+    "(0.08288462362195136-0.028376809745123296j)\n"
+    "\n"
+    "All arguments coincide:\n"
+    "\n"
+    ">>> elliprj(x, x, x, x)\n"
+    "(-0.03986825876151896-0.14051741840449586j)\n"
+    "\n"
+    ">>> np.power(x, -1.5)\n"
+    "(-0.03986825876151894-0.14051741840449583j)")
+ufunc_elliprj_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_elliprj_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_elliprj_loops[2] = loop_D_DDDD__As_FFFF_F
+ufunc_elliprj_loops[3] = loop_D_DDDD__As_DDDD_D
+ufunc_elliprj_types[0] = NPY_FLOAT
+ufunc_elliprj_types[1] = NPY_FLOAT
+ufunc_elliprj_types[2] = NPY_FLOAT
+ufunc_elliprj_types[3] = NPY_FLOAT
+ufunc_elliprj_types[4] = NPY_FLOAT
+ufunc_elliprj_types[5] = NPY_DOUBLE
+ufunc_elliprj_types[6] = NPY_DOUBLE
+ufunc_elliprj_types[7] = NPY_DOUBLE
+ufunc_elliprj_types[8] = NPY_DOUBLE
+ufunc_elliprj_types[9] = NPY_DOUBLE
+ufunc_elliprj_types[10] = NPY_CFLOAT
+ufunc_elliprj_types[11] = NPY_CFLOAT
+ufunc_elliprj_types[12] = NPY_CFLOAT
+ufunc_elliprj_types[13] = NPY_CFLOAT
+ufunc_elliprj_types[14] = NPY_CFLOAT
+ufunc_elliprj_types[15] = NPY_CDOUBLE
+ufunc_elliprj_types[16] = NPY_CDOUBLE
+ufunc_elliprj_types[17] = NPY_CDOUBLE
+ufunc_elliprj_types[18] = NPY_CDOUBLE
+ufunc_elliprj_types[19] = NPY_CDOUBLE
+ufunc_elliprj_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RJ
+ufunc_elliprj_ptr[2*0+1] = ("elliprj")
+ufunc_elliprj_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RJ
+ufunc_elliprj_ptr[2*1+1] = ("elliprj")
+ufunc_elliprj_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RJ
+ufunc_elliprj_ptr[2*2+1] = ("elliprj")
+ufunc_elliprj_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RJ
+ufunc_elliprj_ptr[2*3+1] = ("elliprj")
+ufunc_elliprj_data[0] = &ufunc_elliprj_ptr[2*0]
+ufunc_elliprj_data[1] = &ufunc_elliprj_ptr[2*1]
+ufunc_elliprj_data[2] = &ufunc_elliprj_ptr[2*2]
+ufunc_elliprj_data[3] = &ufunc_elliprj_ptr[2*3]
+elliprj = np.PyUFunc_FromFuncAndData(ufunc_elliprj_loops, ufunc_elliprj_data, ufunc_elliprj_types, 4, 4, 1, 0, "elliprj", ufunc_elliprj_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_entr_loops[2]
+cdef void *ufunc_entr_ptr[4]
+cdef void *ufunc_entr_data[2]
+cdef char ufunc_entr_types[4]
+cdef char *ufunc_entr_doc = (
+    "entr(x, out=None)\n"
+    "\n"
+    "Elementwise function for computing entropy.\n"
+    "\n"
+    ".. math:: \\text{entr}(x) = \\begin{cases} - x \\log(x) & x > 0  \\\\ 0 & x = 0\n"
+    "          \\\\ -\\infty & \\text{otherwise} \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : ndarray\n"
+    "    Input array.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The value of the elementwise entropy function at the given points `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kl_div, rel_entr, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is concave.\n"
+    "\n"
+    "The origin of this function is in convex programming; see [1]_.\n"
+    "Given a probability distribution :math:`p_1, \\ldots, p_n`,\n"
+    "the definition of entropy in the context of *information theory* is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\sum_{i = 1}^n \\mathrm{entr}(p_i).\n"
+    "\n"
+    "To compute the latter quantity, use `scipy.stats.entropy`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`")
+ufunc_entr_loops[0] = loop_d_d__As_f_f
+ufunc_entr_loops[1] = loop_d_d__As_d_d
+ufunc_entr_types[0] = NPY_FLOAT
+ufunc_entr_types[1] = NPY_FLOAT
+ufunc_entr_types[2] = NPY_DOUBLE
+ufunc_entr_types[3] = NPY_DOUBLE
+ufunc_entr_ptr[2*0] = _func_entr
+ufunc_entr_ptr[2*0+1] = ("entr")
+ufunc_entr_ptr[2*1] = _func_entr
+ufunc_entr_ptr[2*1+1] = ("entr")
+ufunc_entr_data[0] = &ufunc_entr_ptr[2*0]
+ufunc_entr_data[1] = &ufunc_entr_ptr[2*1]
+entr = np.PyUFunc_FromFuncAndData(ufunc_entr_loops, ufunc_entr_data, ufunc_entr_types, 2, 1, 1, 0, "entr", ufunc_entr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erf_loops[4]
+cdef void *ufunc_erf_ptr[8]
+cdef void *ufunc_erf_data[4]
+cdef char ufunc_erf_types[8]
+cdef char *ufunc_erf_doc = (
+    "erf(z, out=None)\n"
+    "\n"
+    "Returns the error function of complex argument.\n"
+    "\n"
+    "It is defined as ``2/sqrt(pi)*integral(exp(-t**2), t=0..z)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : ndarray\n"
+    "    Input array.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The values of the error function at the given points `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erfc, erfinv, erfcinv, wofz, erfcx, erfi\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The cumulative of the unit normal distribution is given by\n"
+    "``Phi(z) = 1/2[1 + erf(z/sqrt(2))]``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Error_function\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover,\n"
+    "    1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm\n"
+    ".. [3] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erf(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erf(x)$')\n"
+    ">>> plt.show()")
+ufunc_erf_loops[0] = loop_d_d__As_f_f
+ufunc_erf_loops[1] = loop_d_d__As_d_d
+ufunc_erf_loops[2] = loop_D_D__As_F_F
+ufunc_erf_loops[3] = loop_D_D__As_D_D
+ufunc_erf_types[0] = NPY_FLOAT
+ufunc_erf_types[1] = NPY_FLOAT
+ufunc_erf_types[2] = NPY_DOUBLE
+ufunc_erf_types[3] = NPY_DOUBLE
+ufunc_erf_types[4] = NPY_CFLOAT
+ufunc_erf_types[5] = NPY_CFLOAT
+ufunc_erf_types[6] = NPY_CDOUBLE
+ufunc_erf_types[7] = NPY_CDOUBLE
+ufunc_erf_ptr[2*0] = _func_cephes_erf
+ufunc_erf_ptr[2*0+1] = ("erf")
+ufunc_erf_ptr[2*1] = _func_cephes_erf
+ufunc_erf_ptr[2*1+1] = ("erf")
+ufunc_erf_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erf
+ufunc_erf_ptr[2*2+1] = ("erf")
+ufunc_erf_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erf
+ufunc_erf_ptr[2*3+1] = ("erf")
+ufunc_erf_data[0] = &ufunc_erf_ptr[2*0]
+ufunc_erf_data[1] = &ufunc_erf_ptr[2*1]
+ufunc_erf_data[2] = &ufunc_erf_ptr[2*2]
+ufunc_erf_data[3] = &ufunc_erf_ptr[2*3]
+erf = np.PyUFunc_FromFuncAndData(ufunc_erf_loops, ufunc_erf_data, ufunc_erf_types, 4, 1, 1, 0, "erf", ufunc_erf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfc_loops[4]
+cdef void *ufunc_erfc_ptr[8]
+cdef void *ufunc_erfc_data[4]
+cdef char ufunc_erfc_types[8]
+cdef char *ufunc_erfc_doc = (
+    "erfc(x, out=None)\n"
+    "\n"
+    "Complementary error function, ``1 - erf(x)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the complementary error function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfi, erfcx, dawsn, wofz\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfc(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfc(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfc_loops[0] = loop_d_d__As_f_f
+ufunc_erfc_loops[1] = loop_d_d__As_d_d
+ufunc_erfc_loops[2] = loop_D_D__As_F_F
+ufunc_erfc_loops[3] = loop_D_D__As_D_D
+ufunc_erfc_types[0] = NPY_FLOAT
+ufunc_erfc_types[1] = NPY_FLOAT
+ufunc_erfc_types[2] = NPY_DOUBLE
+ufunc_erfc_types[3] = NPY_DOUBLE
+ufunc_erfc_types[4] = NPY_CFLOAT
+ufunc_erfc_types[5] = NPY_CFLOAT
+ufunc_erfc_types[6] = NPY_CDOUBLE
+ufunc_erfc_types[7] = NPY_CDOUBLE
+ufunc_erfc_ptr[2*0] = _func_cephes_erfc
+ufunc_erfc_ptr[2*0+1] = ("erfc")
+ufunc_erfc_ptr[2*1] = _func_cephes_erfc
+ufunc_erfc_ptr[2*1+1] = ("erfc")
+ufunc_erfc_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfc_complex
+ufunc_erfc_ptr[2*2+1] = ("erfc")
+ufunc_erfc_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfc_complex
+ufunc_erfc_ptr[2*3+1] = ("erfc")
+ufunc_erfc_data[0] = &ufunc_erfc_ptr[2*0]
+ufunc_erfc_data[1] = &ufunc_erfc_ptr[2*1]
+ufunc_erfc_data[2] = &ufunc_erfc_ptr[2*2]
+ufunc_erfc_data[3] = &ufunc_erfc_ptr[2*3]
+erfc = np.PyUFunc_FromFuncAndData(ufunc_erfc_loops, ufunc_erfc_data, ufunc_erfc_types, 4, 1, 1, 0, "erfc", ufunc_erfc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfcinv_loops[2]
+cdef void *ufunc_erfcinv_ptr[4]
+cdef void *ufunc_erfcinv_data[2]
+cdef char ufunc_erfcinv_types[4]
+cdef char *ufunc_erfcinv_doc = (
+    "erfcinv(y, out=None)\n"
+    "\n"
+    "Inverse of the complementary error function.\n"
+    "\n"
+    "Computes the inverse of the complementary error function.\n"
+    "\n"
+    "In the complex domain, there is no unique complex number w satisfying\n"
+    "erfc(w)=z. This indicates a true inverse function would be multivalued.\n"
+    "When the domain restricts to the real, 0 < x < 2, there is a unique real\n"
+    "number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).\n"
+    "\n"
+    "It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : ndarray\n"
+    "    Argument at which to evaluate. Domain: [0, 2]\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "erfcinv : scalar or ndarray\n"
+    "    The inverse of erfc of y, element-wise\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf : Error function of a complex argument\n"
+    "erfc : Complementary error function, ``1 - erf(x)``\n"
+    "erfinv : Inverse of the error function\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import erfcinv\n"
+    "\n"
+    ">>> erfcinv(0.5)\n"
+    "0.4769362762044699\n"
+    "\n"
+    ">>> y = np.linspace(0.0, 2.0, num=11)\n"
+    ">>> erfcinv(y)\n"
+    "array([        inf,  0.9061938 ,  0.59511608,  0.37080716,  0.17914345,\n"
+    "       -0.        , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,\n"
+    "              -inf])\n"
+    "\n"
+    "Plot the function:\n"
+    "\n"
+    ">>> y = np.linspace(0, 2, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(y, erfcinv(y))\n"
+    ">>> ax.grid(True)\n"
+    ">>> ax.set_xlabel('y')\n"
+    ">>> ax.set_title('erfcinv(y)')\n"
+    ">>> plt.show()")
+ufunc_erfcinv_loops[0] = loop_d_d__As_f_f
+ufunc_erfcinv_loops[1] = loop_d_d__As_d_d
+ufunc_erfcinv_types[0] = NPY_FLOAT
+ufunc_erfcinv_types[1] = NPY_FLOAT
+ufunc_erfcinv_types[2] = NPY_DOUBLE
+ufunc_erfcinv_types[3] = NPY_DOUBLE
+ufunc_erfcinv_ptr[2*0] = _func_cephes_erfcinv
+ufunc_erfcinv_ptr[2*0+1] = ("erfcinv")
+ufunc_erfcinv_ptr[2*1] = _func_cephes_erfcinv
+ufunc_erfcinv_ptr[2*1+1] = ("erfcinv")
+ufunc_erfcinv_data[0] = &ufunc_erfcinv_ptr[2*0]
+ufunc_erfcinv_data[1] = &ufunc_erfcinv_ptr[2*1]
+erfcinv = np.PyUFunc_FromFuncAndData(ufunc_erfcinv_loops, ufunc_erfcinv_data, ufunc_erfcinv_types, 2, 1, 1, 0, "erfcinv", ufunc_erfcinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfcx_loops[4]
+cdef void *ufunc_erfcx_ptr[8]
+cdef void *ufunc_erfcx_data[4]
+cdef char ufunc_erfcx_types[8]
+cdef char *ufunc_erfcx_doc = (
+    "erfcx(x, out=None)\n"
+    "\n"
+    "Scaled complementary error function, ``exp(x**2) * erfc(x)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the scaled complementary error function\n"
+    "\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfc, erfi, dawsn, wofz\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.12.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfcx(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfcx(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfcx_loops[0] = loop_d_d__As_f_f
+ufunc_erfcx_loops[1] = loop_d_d__As_d_d
+ufunc_erfcx_loops[2] = loop_D_D__As_F_F
+ufunc_erfcx_loops[3] = loop_D_D__As_D_D
+ufunc_erfcx_types[0] = NPY_FLOAT
+ufunc_erfcx_types[1] = NPY_FLOAT
+ufunc_erfcx_types[2] = NPY_DOUBLE
+ufunc_erfcx_types[3] = NPY_DOUBLE
+ufunc_erfcx_types[4] = NPY_CFLOAT
+ufunc_erfcx_types[5] = NPY_CFLOAT
+ufunc_erfcx_types[6] = NPY_CDOUBLE
+ufunc_erfcx_types[7] = NPY_CDOUBLE
+ufunc_erfcx_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx
+ufunc_erfcx_ptr[2*0+1] = ("erfcx")
+ufunc_erfcx_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx
+ufunc_erfcx_ptr[2*1+1] = ("erfcx")
+ufunc_erfcx_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx_complex
+ufunc_erfcx_ptr[2*2+1] = ("erfcx")
+ufunc_erfcx_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx_complex
+ufunc_erfcx_ptr[2*3+1] = ("erfcx")
+ufunc_erfcx_data[0] = &ufunc_erfcx_ptr[2*0]
+ufunc_erfcx_data[1] = &ufunc_erfcx_ptr[2*1]
+ufunc_erfcx_data[2] = &ufunc_erfcx_ptr[2*2]
+ufunc_erfcx_data[3] = &ufunc_erfcx_ptr[2*3]
+erfcx = np.PyUFunc_FromFuncAndData(ufunc_erfcx_loops, ufunc_erfcx_data, ufunc_erfcx_types, 4, 1, 1, 0, "erfcx", ufunc_erfcx_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfi_loops[4]
+cdef void *ufunc_erfi_ptr[8]
+cdef void *ufunc_erfi_data[4]
+cdef char ufunc_erfi_types[8]
+cdef char *ufunc_erfi_doc = (
+    "erfi(z, out=None)\n"
+    "\n"
+    "Imaginary error function, ``-i erf(i z)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the imaginary error function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfc, erfcx, dawsn, wofz\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.12.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfi(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfi(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfi_loops[0] = loop_d_d__As_f_f
+ufunc_erfi_loops[1] = loop_d_d__As_d_d
+ufunc_erfi_loops[2] = loop_D_D__As_F_F
+ufunc_erfi_loops[3] = loop_D_D__As_D_D
+ufunc_erfi_types[0] = NPY_FLOAT
+ufunc_erfi_types[1] = NPY_FLOAT
+ufunc_erfi_types[2] = NPY_DOUBLE
+ufunc_erfi_types[3] = NPY_DOUBLE
+ufunc_erfi_types[4] = NPY_CFLOAT
+ufunc_erfi_types[5] = NPY_CFLOAT
+ufunc_erfi_types[6] = NPY_CDOUBLE
+ufunc_erfi_types[7] = NPY_CDOUBLE
+ufunc_erfi_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_erfi
+ufunc_erfi_ptr[2*0+1] = ("erfi")
+ufunc_erfi_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_erfi
+ufunc_erfi_ptr[2*1+1] = ("erfi")
+ufunc_erfi_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfi_complex
+ufunc_erfi_ptr[2*2+1] = ("erfi")
+ufunc_erfi_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfi_complex
+ufunc_erfi_ptr[2*3+1] = ("erfi")
+ufunc_erfi_data[0] = &ufunc_erfi_ptr[2*0]
+ufunc_erfi_data[1] = &ufunc_erfi_ptr[2*1]
+ufunc_erfi_data[2] = &ufunc_erfi_ptr[2*2]
+ufunc_erfi_data[3] = &ufunc_erfi_ptr[2*3]
+erfi = np.PyUFunc_FromFuncAndData(ufunc_erfi_loops, ufunc_erfi_data, ufunc_erfi_types, 4, 1, 1, 0, "erfi", ufunc_erfi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfinv_loops[2]
+cdef void *ufunc_erfinv_ptr[4]
+cdef void *ufunc_erfinv_data[2]
+cdef char ufunc_erfinv_types[4]
+cdef char *ufunc_erfinv_doc = (
+    "erfinv(y, out=None)\n"
+    "\n"
+    "Inverse of the error function.\n"
+    "\n"
+    "Computes the inverse of the error function.\n"
+    "\n"
+    "In the complex domain, there is no unique complex number w satisfying\n"
+    "erf(w)=z. This indicates a true inverse function would be multivalued.\n"
+    "When the domain restricts to the real, -1 < x < 1, there is a unique real\n"
+    "number satisfying erf(erfinv(x)) = x.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : ndarray\n"
+    "    Argument at which to evaluate. Domain: [-1, 1]\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "erfinv : scalar or ndarray\n"
+    "    The inverse of erf of y, element-wise\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf : Error function of a complex argument\n"
+    "erfc : Complementary error function, ``1 - erf(x)``\n"
+    "erfcinv : Inverse of the complementary error function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function wraps the ``erf_inv`` routine from the\n"
+    "Boost Math C++ library [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import erfinv, erf\n"
+    "\n"
+    ">>> erfinv(0.5)\n"
+    "0.4769362762044699\n"
+    "\n"
+    ">>> y = np.linspace(-1.0, 1.0, num=9)\n"
+    ">>> x = erfinv(y)\n"
+    ">>> x\n"
+    "array([       -inf, -0.81341985, -0.47693628, -0.22531206,  0.        ,\n"
+    "        0.22531206,  0.47693628,  0.81341985,         inf])\n"
+    "\n"
+    "Verify that ``erf(erfinv(y))`` is ``y``.\n"
+    "\n"
+    ">>> erf(x)\n"
+    "array([-1.  , -0.75, -0.5 , -0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ])\n"
+    "\n"
+    "Plot the function:\n"
+    "\n"
+    ">>> y = np.linspace(-1, 1, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(y, erfinv(y))\n"
+    ">>> ax.grid(True)\n"
+    ">>> ax.set_xlabel('y')\n"
+    ">>> ax.set_title('erfinv(y)')\n"
+    ">>> plt.show()")
+ufunc_erfinv_loops[0] = loop_f_f__As_f_f
+ufunc_erfinv_loops[1] = loop_d_d__As_d_d
+ufunc_erfinv_types[0] = NPY_FLOAT
+ufunc_erfinv_types[1] = NPY_FLOAT
+ufunc_erfinv_types[2] = NPY_DOUBLE
+ufunc_erfinv_types[3] = NPY_DOUBLE
+ufunc_erfinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_erfinv_float
+ufunc_erfinv_ptr[2*0+1] = ("erfinv")
+ufunc_erfinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_erfinv_double
+ufunc_erfinv_ptr[2*1+1] = ("erfinv")
+ufunc_erfinv_data[0] = &ufunc_erfinv_ptr[2*0]
+ufunc_erfinv_data[1] = &ufunc_erfinv_ptr[2*1]
+erfinv = np.PyUFunc_FromFuncAndData(ufunc_erfinv_loops, ufunc_erfinv_data, ufunc_erfinv_types, 2, 1, 1, 0, "erfinv", ufunc_erfinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyc_loops[5]
+cdef void *ufunc_eval_chebyc_ptr[10]
+cdef void *ufunc_eval_chebyc_data[5]
+cdef char ufunc_eval_chebyc_types[15]
+cdef char *ufunc_eval_chebyc_doc = (
+    "eval_chebyc(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    C_n(x) = 2 T_n(x/2)\n"
+    "\n"
+    "where :math:`T_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.11 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyt`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "C : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyc : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the first kind on [-2, 2]\n"
+    "chebyc : Chebyshev polynomial object\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "eval_chebyt : evaluate Chebycshev polynomials of the first kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "They are a scaled version of the Chebyshev polynomials of the\n"
+    "first kind.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 6)\n"
+    ">>> sc.eval_chebyc(3, x)\n"
+    "array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])\n"
+    ">>> 2 * sc.eval_chebyt(3, x / 2)\n"
+    "array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])")
+ufunc_eval_chebyc_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyc_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyc_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyc_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyc_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyc_types[0] = NPY_INTP
+ufunc_eval_chebyc_types[1] = NPY_DOUBLE
+ufunc_eval_chebyc_types[2] = NPY_DOUBLE
+ufunc_eval_chebyc_types[3] = NPY_FLOAT
+ufunc_eval_chebyc_types[4] = NPY_FLOAT
+ufunc_eval_chebyc_types[5] = NPY_FLOAT
+ufunc_eval_chebyc_types[6] = NPY_FLOAT
+ufunc_eval_chebyc_types[7] = NPY_CFLOAT
+ufunc_eval_chebyc_types[8] = NPY_CFLOAT
+ufunc_eval_chebyc_types[9] = NPY_DOUBLE
+ufunc_eval_chebyc_types[10] = NPY_DOUBLE
+ufunc_eval_chebyc_types[11] = NPY_DOUBLE
+ufunc_eval_chebyc_types[12] = NPY_DOUBLE
+ufunc_eval_chebyc_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyc_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyc_ptr[2*0] = _func_eval_chebyc_l
+ufunc_eval_chebyc_ptr[2*0+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*1] = _func_eval_chebyc[double]
+ufunc_eval_chebyc_ptr[2*1+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*2] = _func_eval_chebyc[double_complex]
+ufunc_eval_chebyc_ptr[2*2+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*3] = _func_eval_chebyc[double]
+ufunc_eval_chebyc_ptr[2*3+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*4] = _func_eval_chebyc[double_complex]
+ufunc_eval_chebyc_ptr[2*4+1] = ("eval_chebyc")
+ufunc_eval_chebyc_data[0] = &ufunc_eval_chebyc_ptr[2*0]
+ufunc_eval_chebyc_data[1] = &ufunc_eval_chebyc_ptr[2*1]
+ufunc_eval_chebyc_data[2] = &ufunc_eval_chebyc_ptr[2*2]
+ufunc_eval_chebyc_data[3] = &ufunc_eval_chebyc_ptr[2*3]
+ufunc_eval_chebyc_data[4] = &ufunc_eval_chebyc_ptr[2*4]
+eval_chebyc = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyc_loops, ufunc_eval_chebyc_data, ufunc_eval_chebyc_types, 5, 2, 1, 0, "eval_chebyc", ufunc_eval_chebyc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebys_loops[5]
+cdef void *ufunc_eval_chebys_ptr[10]
+cdef void *ufunc_eval_chebys_data[5]
+cdef char ufunc_eval_chebys_types[15]
+cdef char *ufunc_eval_chebys_doc = (
+    "eval_chebys(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    S_n(x) = U_n(x/2)\n"
+    "\n"
+    "where :math:`U_n` is a Chebyshev polynomial of the second\n"
+    "kind. See 22.5.13 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyu`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "S : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebys : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the second kind on [-2, 2]\n"
+    "chebys : Chebyshev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "They are a scaled version of the Chebyshev polynomials of the\n"
+    "second kind.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 6)\n"
+    ">>> sc.eval_chebys(3, x)\n"
+    "array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])\n"
+    ">>> sc.eval_chebyu(3, x / 2)\n"
+    "array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])")
+ufunc_eval_chebys_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebys_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebys_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebys_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebys_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebys_types[0] = NPY_INTP
+ufunc_eval_chebys_types[1] = NPY_DOUBLE
+ufunc_eval_chebys_types[2] = NPY_DOUBLE
+ufunc_eval_chebys_types[3] = NPY_FLOAT
+ufunc_eval_chebys_types[4] = NPY_FLOAT
+ufunc_eval_chebys_types[5] = NPY_FLOAT
+ufunc_eval_chebys_types[6] = NPY_FLOAT
+ufunc_eval_chebys_types[7] = NPY_CFLOAT
+ufunc_eval_chebys_types[8] = NPY_CFLOAT
+ufunc_eval_chebys_types[9] = NPY_DOUBLE
+ufunc_eval_chebys_types[10] = NPY_DOUBLE
+ufunc_eval_chebys_types[11] = NPY_DOUBLE
+ufunc_eval_chebys_types[12] = NPY_DOUBLE
+ufunc_eval_chebys_types[13] = NPY_CDOUBLE
+ufunc_eval_chebys_types[14] = NPY_CDOUBLE
+ufunc_eval_chebys_ptr[2*0] = _func_eval_chebys_l
+ufunc_eval_chebys_ptr[2*0+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*1] = _func_eval_chebys[double]
+ufunc_eval_chebys_ptr[2*1+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*2] = _func_eval_chebys[double_complex]
+ufunc_eval_chebys_ptr[2*2+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*3] = _func_eval_chebys[double]
+ufunc_eval_chebys_ptr[2*3+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*4] = _func_eval_chebys[double_complex]
+ufunc_eval_chebys_ptr[2*4+1] = ("eval_chebys")
+ufunc_eval_chebys_data[0] = &ufunc_eval_chebys_ptr[2*0]
+ufunc_eval_chebys_data[1] = &ufunc_eval_chebys_ptr[2*1]
+ufunc_eval_chebys_data[2] = &ufunc_eval_chebys_ptr[2*2]
+ufunc_eval_chebys_data[3] = &ufunc_eval_chebys_ptr[2*3]
+ufunc_eval_chebys_data[4] = &ufunc_eval_chebys_ptr[2*4]
+eval_chebys = np.PyUFunc_FromFuncAndData(ufunc_eval_chebys_loops, ufunc_eval_chebys_data, ufunc_eval_chebys_types, 5, 2, 1, 0, "eval_chebys", ufunc_eval_chebys_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyt_loops[5]
+cdef void *ufunc_eval_chebyt_ptr[10]
+cdef void *ufunc_eval_chebyt_data[5]
+cdef char ufunc_eval_chebyt_types[15]
+cdef char *ufunc_eval_chebyt_doc = (
+    "eval_chebyt(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the first kind at a point.\n"
+    "\n"
+    "The Chebyshev polynomials of the first kind can be defined via the\n"
+    "Gauss hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    T_n(x) = {}_2F_1(n, -n; 1/2; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.47 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "T : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyt : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the first kind\n"
+    "chebyu : Chebychev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This routine is numerically stable for `x` in ``[-1, 1]`` at least\n"
+    "up to order ``10000``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_chebyt_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyt_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyt_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyt_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyt_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyt_types[0] = NPY_INTP
+ufunc_eval_chebyt_types[1] = NPY_DOUBLE
+ufunc_eval_chebyt_types[2] = NPY_DOUBLE
+ufunc_eval_chebyt_types[3] = NPY_FLOAT
+ufunc_eval_chebyt_types[4] = NPY_FLOAT
+ufunc_eval_chebyt_types[5] = NPY_FLOAT
+ufunc_eval_chebyt_types[6] = NPY_FLOAT
+ufunc_eval_chebyt_types[7] = NPY_CFLOAT
+ufunc_eval_chebyt_types[8] = NPY_CFLOAT
+ufunc_eval_chebyt_types[9] = NPY_DOUBLE
+ufunc_eval_chebyt_types[10] = NPY_DOUBLE
+ufunc_eval_chebyt_types[11] = NPY_DOUBLE
+ufunc_eval_chebyt_types[12] = NPY_DOUBLE
+ufunc_eval_chebyt_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyt_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyt_ptr[2*0] = _func_eval_chebyt_l
+ufunc_eval_chebyt_ptr[2*0+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*1] = _func_eval_chebyt[double]
+ufunc_eval_chebyt_ptr[2*1+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*2] = _func_eval_chebyt[double_complex]
+ufunc_eval_chebyt_ptr[2*2+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*3] = _func_eval_chebyt[double]
+ufunc_eval_chebyt_ptr[2*3+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*4] = _func_eval_chebyt[double_complex]
+ufunc_eval_chebyt_ptr[2*4+1] = ("eval_chebyt")
+ufunc_eval_chebyt_data[0] = &ufunc_eval_chebyt_ptr[2*0]
+ufunc_eval_chebyt_data[1] = &ufunc_eval_chebyt_ptr[2*1]
+ufunc_eval_chebyt_data[2] = &ufunc_eval_chebyt_ptr[2*2]
+ufunc_eval_chebyt_data[3] = &ufunc_eval_chebyt_ptr[2*3]
+ufunc_eval_chebyt_data[4] = &ufunc_eval_chebyt_ptr[2*4]
+eval_chebyt = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyt_loops, ufunc_eval_chebyt_data, ufunc_eval_chebyt_types, 5, 2, 1, 0, "eval_chebyt", ufunc_eval_chebyt_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyu_loops[5]
+cdef void *ufunc_eval_chebyu_ptr[10]
+cdef void *ufunc_eval_chebyu_data[5]
+cdef char ufunc_eval_chebyu_types[15]
+cdef char *ufunc_eval_chebyu_doc = (
+    "eval_chebyu(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the second kind at a point.\n"
+    "\n"
+    "The Chebyshev polynomials of the second kind can be defined via\n"
+    "the Gauss hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    U_n(x) = (n + 1) {}_2F_1(-n, n + 2; 3/2; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.48 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "U : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyu : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the second kind\n"
+    "chebyu : Chebyshev polynomial object\n"
+    "eval_chebyt : evaluate Chebyshev polynomials of the first kind\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_chebyu_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyu_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyu_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyu_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyu_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyu_types[0] = NPY_INTP
+ufunc_eval_chebyu_types[1] = NPY_DOUBLE
+ufunc_eval_chebyu_types[2] = NPY_DOUBLE
+ufunc_eval_chebyu_types[3] = NPY_FLOAT
+ufunc_eval_chebyu_types[4] = NPY_FLOAT
+ufunc_eval_chebyu_types[5] = NPY_FLOAT
+ufunc_eval_chebyu_types[6] = NPY_FLOAT
+ufunc_eval_chebyu_types[7] = NPY_CFLOAT
+ufunc_eval_chebyu_types[8] = NPY_CFLOAT
+ufunc_eval_chebyu_types[9] = NPY_DOUBLE
+ufunc_eval_chebyu_types[10] = NPY_DOUBLE
+ufunc_eval_chebyu_types[11] = NPY_DOUBLE
+ufunc_eval_chebyu_types[12] = NPY_DOUBLE
+ufunc_eval_chebyu_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyu_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyu_ptr[2*0] = _func_eval_chebyu_l
+ufunc_eval_chebyu_ptr[2*0+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*1] = _func_eval_chebyu[double]
+ufunc_eval_chebyu_ptr[2*1+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*2] = _func_eval_chebyu[double_complex]
+ufunc_eval_chebyu_ptr[2*2+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*3] = _func_eval_chebyu[double]
+ufunc_eval_chebyu_ptr[2*3+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*4] = _func_eval_chebyu[double_complex]
+ufunc_eval_chebyu_ptr[2*4+1] = ("eval_chebyu")
+ufunc_eval_chebyu_data[0] = &ufunc_eval_chebyu_ptr[2*0]
+ufunc_eval_chebyu_data[1] = &ufunc_eval_chebyu_ptr[2*1]
+ufunc_eval_chebyu_data[2] = &ufunc_eval_chebyu_ptr[2*2]
+ufunc_eval_chebyu_data[3] = &ufunc_eval_chebyu_ptr[2*3]
+ufunc_eval_chebyu_data[4] = &ufunc_eval_chebyu_ptr[2*4]
+eval_chebyu = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyu_loops, ufunc_eval_chebyu_data, ufunc_eval_chebyu_types, 5, 2, 1, 0, "eval_chebyu", ufunc_eval_chebyu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_gegenbauer_loops[5]
+cdef void *ufunc_eval_gegenbauer_ptr[10]
+cdef void *ufunc_eval_gegenbauer_data[5]
+cdef char ufunc_eval_gegenbauer_types[20]
+cdef char *ufunc_eval_gegenbauer_doc = (
+    "eval_gegenbauer(n, alpha, x, out=None)\n"
+    "\n"
+    "Evaluate Gegenbauer polynomial at a point.\n"
+    "\n"
+    "The Gegenbauer polynomials can be defined via the Gauss\n"
+    "hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    C_n^{(\\alpha)} = \\frac{(2\\alpha)_n}{\\Gamma(n + 1)}\n"
+    "      {}_2F_1(-n, 2\\alpha + n; \\alpha + 1/2; (1 - z)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.46 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Gegenbauer polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "C : scalar or ndarray\n"
+    "    Values of the Gegenbauer polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_gegenbauer : roots and quadrature weights of Gegenbauer\n"
+    "                   polynomials\n"
+    "gegenbauer : Gegenbauer polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_gegenbauer_loops[0] = loop_d_pdd__As_pdd_d
+ufunc_eval_gegenbauer_loops[1] = loop_d_ddd__As_fff_f
+ufunc_eval_gegenbauer_loops[2] = loop_D_ddD__As_ffF_F
+ufunc_eval_gegenbauer_loops[3] = loop_d_ddd__As_ddd_d
+ufunc_eval_gegenbauer_loops[4] = loop_D_ddD__As_ddD_D
+ufunc_eval_gegenbauer_types[0] = NPY_INTP
+ufunc_eval_gegenbauer_types[1] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[2] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[3] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[4] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[5] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[6] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[7] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[8] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[9] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[10] = NPY_CFLOAT
+ufunc_eval_gegenbauer_types[11] = NPY_CFLOAT
+ufunc_eval_gegenbauer_types[12] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[13] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[14] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[15] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[16] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[17] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[18] = NPY_CDOUBLE
+ufunc_eval_gegenbauer_types[19] = NPY_CDOUBLE
+ufunc_eval_gegenbauer_ptr[2*0] = _func_eval_gegenbauer_l
+ufunc_eval_gegenbauer_ptr[2*0+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*1] = _func_eval_gegenbauer[double]
+ufunc_eval_gegenbauer_ptr[2*1+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*2] = _func_eval_gegenbauer[double_complex]
+ufunc_eval_gegenbauer_ptr[2*2+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*3] = _func_eval_gegenbauer[double]
+ufunc_eval_gegenbauer_ptr[2*3+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*4] = _func_eval_gegenbauer[double_complex]
+ufunc_eval_gegenbauer_ptr[2*4+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_data[0] = &ufunc_eval_gegenbauer_ptr[2*0]
+ufunc_eval_gegenbauer_data[1] = &ufunc_eval_gegenbauer_ptr[2*1]
+ufunc_eval_gegenbauer_data[2] = &ufunc_eval_gegenbauer_ptr[2*2]
+ufunc_eval_gegenbauer_data[3] = &ufunc_eval_gegenbauer_ptr[2*3]
+ufunc_eval_gegenbauer_data[4] = &ufunc_eval_gegenbauer_ptr[2*4]
+eval_gegenbauer = np.PyUFunc_FromFuncAndData(ufunc_eval_gegenbauer_loops, ufunc_eval_gegenbauer_data, ufunc_eval_gegenbauer_types, 5, 3, 1, 0, "eval_gegenbauer", ufunc_eval_gegenbauer_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_genlaguerre_loops[5]
+cdef void *ufunc_eval_genlaguerre_ptr[10]
+cdef void *ufunc_eval_genlaguerre_data[5]
+cdef char ufunc_eval_genlaguerre_types[20]
+cdef char *ufunc_eval_genlaguerre_doc = (
+    "eval_genlaguerre(n, alpha, x, out=None)\n"
+    "\n"
+    "Evaluate generalized Laguerre polynomial at a point.\n"
+    "\n"
+    "The generalized Laguerre polynomials can be defined via the\n"
+    "confluent hypergeometric function :math:`{}_1F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    L_n^{(\\alpha)}(x) = \\binom{n + \\alpha}{n}\n"
+    "      {}_1F_1(-n, \\alpha + 1, x).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.54 in [AS]_ for details. The Laguerre\n"
+    "polynomials are the special case where :math:`\\alpha = 0`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the confluent hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter; must have ``alpha > -1``\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the generalized Laguerre\n"
+    "    polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "L : scalar or ndarray\n"
+    "    Values of the generalized Laguerre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_genlaguerre : roots and quadrature weights of generalized\n"
+    "                    Laguerre polynomials\n"
+    "genlaguerre : generalized Laguerre polynomial object\n"
+    "hyp1f1 : confluent hypergeometric function\n"
+    "eval_laguerre : evaluate Laguerre polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_genlaguerre_loops[0] = loop_d_pdd__As_pdd_d
+ufunc_eval_genlaguerre_loops[1] = loop_d_ddd__As_fff_f
+ufunc_eval_genlaguerre_loops[2] = loop_D_ddD__As_ffF_F
+ufunc_eval_genlaguerre_loops[3] = loop_d_ddd__As_ddd_d
+ufunc_eval_genlaguerre_loops[4] = loop_D_ddD__As_ddD_D
+ufunc_eval_genlaguerre_types[0] = NPY_INTP
+ufunc_eval_genlaguerre_types[1] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[2] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[3] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[4] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[5] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[6] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[7] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[8] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[9] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[10] = NPY_CFLOAT
+ufunc_eval_genlaguerre_types[11] = NPY_CFLOAT
+ufunc_eval_genlaguerre_types[12] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[13] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[14] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[15] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[16] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[17] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[18] = NPY_CDOUBLE
+ufunc_eval_genlaguerre_types[19] = NPY_CDOUBLE
+ufunc_eval_genlaguerre_ptr[2*0] = _func_eval_genlaguerre_l
+ufunc_eval_genlaguerre_ptr[2*0+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*1] = _func_eval_genlaguerre[double]
+ufunc_eval_genlaguerre_ptr[2*1+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*2] = _func_eval_genlaguerre[double_complex]
+ufunc_eval_genlaguerre_ptr[2*2+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*3] = _func_eval_genlaguerre[double]
+ufunc_eval_genlaguerre_ptr[2*3+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*4] = _func_eval_genlaguerre[double_complex]
+ufunc_eval_genlaguerre_ptr[2*4+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_data[0] = &ufunc_eval_genlaguerre_ptr[2*0]
+ufunc_eval_genlaguerre_data[1] = &ufunc_eval_genlaguerre_ptr[2*1]
+ufunc_eval_genlaguerre_data[2] = &ufunc_eval_genlaguerre_ptr[2*2]
+ufunc_eval_genlaguerre_data[3] = &ufunc_eval_genlaguerre_ptr[2*3]
+ufunc_eval_genlaguerre_data[4] = &ufunc_eval_genlaguerre_ptr[2*4]
+eval_genlaguerre = np.PyUFunc_FromFuncAndData(ufunc_eval_genlaguerre_loops, ufunc_eval_genlaguerre_data, ufunc_eval_genlaguerre_types, 5, 3, 1, 0, "eval_genlaguerre", ufunc_eval_genlaguerre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_hermite_loops[1]
+cdef void *ufunc_eval_hermite_ptr[2]
+cdef void *ufunc_eval_hermite_data[1]
+cdef char ufunc_eval_hermite_types[3]
+cdef char *ufunc_eval_hermite_doc = (
+    "eval_hermite(n, x, out=None)\n"
+    "\n"
+    "Evaluate physicist's Hermite polynomial at a point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    H_n(x) = (-1)^n e^{x^2} \\frac{d^n}{dx^n} e^{-x^2};\n"
+    "\n"
+    ":math:`H_n` is a polynomial of degree :math:`n`. See 22.11.7 in\n"
+    "[AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Hermite polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "H : scalar or ndarray\n"
+    "    Values of the Hermite polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_hermite : roots and quadrature weights of physicist's\n"
+    "                Hermite polynomials\n"
+    "hermite : physicist's Hermite polynomial object\n"
+    "numpy.polynomial.hermite.Hermite : Physicist's Hermite series\n"
+    "eval_hermitenorm : evaluate Probabilist's Hermite polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_hermite_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_hermite_types[0] = NPY_INTP
+ufunc_eval_hermite_types[1] = NPY_DOUBLE
+ufunc_eval_hermite_types[2] = NPY_DOUBLE
+ufunc_eval_hermite_ptr[2*0] = _func_eval_hermite
+ufunc_eval_hermite_ptr[2*0+1] = ("eval_hermite")
+ufunc_eval_hermite_data[0] = &ufunc_eval_hermite_ptr[2*0]
+eval_hermite = np.PyUFunc_FromFuncAndData(ufunc_eval_hermite_loops, ufunc_eval_hermite_data, ufunc_eval_hermite_types, 1, 2, 1, 0, "eval_hermite", ufunc_eval_hermite_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_hermitenorm_loops[1]
+cdef void *ufunc_eval_hermitenorm_ptr[2]
+cdef void *ufunc_eval_hermitenorm_data[1]
+cdef char ufunc_eval_hermitenorm_types[3]
+cdef char *ufunc_eval_hermitenorm_doc = (
+    "eval_hermitenorm(n, x, out=None)\n"
+    "\n"
+    "Evaluate probabilist's (normalized) Hermite polynomial at a\n"
+    "point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    He_n(x) = (-1)^n e^{x^2/2} \\frac{d^n}{dx^n} e^{-x^2/2};\n"
+    "\n"
+    ":math:`He_n` is a polynomial of degree :math:`n`. See 22.11.8 in\n"
+    "[AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Hermite polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "He : scalar or ndarray\n"
+    "    Values of the Hermite polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_hermitenorm : roots and quadrature weights of probabilist's\n"
+    "                    Hermite polynomials\n"
+    "hermitenorm : probabilist's Hermite polynomial object\n"
+    "numpy.polynomial.hermite_e.HermiteE : Probabilist's Hermite series\n"
+    "eval_hermite : evaluate physicist's Hermite polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_hermitenorm_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_hermitenorm_types[0] = NPY_INTP
+ufunc_eval_hermitenorm_types[1] = NPY_DOUBLE
+ufunc_eval_hermitenorm_types[2] = NPY_DOUBLE
+ufunc_eval_hermitenorm_ptr[2*0] = _func_eval_hermitenorm
+ufunc_eval_hermitenorm_ptr[2*0+1] = ("eval_hermitenorm")
+ufunc_eval_hermitenorm_data[0] = &ufunc_eval_hermitenorm_ptr[2*0]
+eval_hermitenorm = np.PyUFunc_FromFuncAndData(ufunc_eval_hermitenorm_loops, ufunc_eval_hermitenorm_data, ufunc_eval_hermitenorm_types, 1, 2, 1, 0, "eval_hermitenorm", ufunc_eval_hermitenorm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_jacobi_loops[5]
+cdef void *ufunc_eval_jacobi_ptr[10]
+cdef void *ufunc_eval_jacobi_data[5]
+cdef char ufunc_eval_jacobi_types[25]
+cdef char *ufunc_eval_jacobi_doc = (
+    "eval_jacobi(n, alpha, beta, x, out=None)\n"
+    "\n"
+    "Evaluate Jacobi polynomial at a point.\n"
+    "\n"
+    "The Jacobi polynomials can be defined via the Gauss hypergeometric\n"
+    "function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n^{(\\alpha, \\beta)}(x) = \\frac{(\\alpha + 1)_n}{\\Gamma(n + 1)}\n"
+    "      {}_2F_1(-n, 1 + \\alpha + \\beta + n; \\alpha + 1; (1 - z)/2)\n"
+    "\n"
+    "where :math:`(\\cdot)_n` is the Pochhammer symbol; see `poch`. When\n"
+    ":math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.42 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter\n"
+    "beta : array_like\n"
+    "    Parameter\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the Jacobi polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_jacobi : roots and quadrature weights of Jacobi polynomials\n"
+    "jacobi : Jacobi polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_jacobi_loops[0] = loop_d_pddd__As_pddd_d
+ufunc_eval_jacobi_loops[1] = loop_d_dddd__As_ffff_f
+ufunc_eval_jacobi_loops[2] = loop_D_dddD__As_fffF_F
+ufunc_eval_jacobi_loops[3] = loop_d_dddd__As_dddd_d
+ufunc_eval_jacobi_loops[4] = loop_D_dddD__As_dddD_D
+ufunc_eval_jacobi_types[0] = NPY_INTP
+ufunc_eval_jacobi_types[1] = NPY_DOUBLE
+ufunc_eval_jacobi_types[2] = NPY_DOUBLE
+ufunc_eval_jacobi_types[3] = NPY_DOUBLE
+ufunc_eval_jacobi_types[4] = NPY_DOUBLE
+ufunc_eval_jacobi_types[5] = NPY_FLOAT
+ufunc_eval_jacobi_types[6] = NPY_FLOAT
+ufunc_eval_jacobi_types[7] = NPY_FLOAT
+ufunc_eval_jacobi_types[8] = NPY_FLOAT
+ufunc_eval_jacobi_types[9] = NPY_FLOAT
+ufunc_eval_jacobi_types[10] = NPY_FLOAT
+ufunc_eval_jacobi_types[11] = NPY_FLOAT
+ufunc_eval_jacobi_types[12] = NPY_FLOAT
+ufunc_eval_jacobi_types[13] = NPY_CFLOAT
+ufunc_eval_jacobi_types[14] = NPY_CFLOAT
+ufunc_eval_jacobi_types[15] = NPY_DOUBLE
+ufunc_eval_jacobi_types[16] = NPY_DOUBLE
+ufunc_eval_jacobi_types[17] = NPY_DOUBLE
+ufunc_eval_jacobi_types[18] = NPY_DOUBLE
+ufunc_eval_jacobi_types[19] = NPY_DOUBLE
+ufunc_eval_jacobi_types[20] = NPY_DOUBLE
+ufunc_eval_jacobi_types[21] = NPY_DOUBLE
+ufunc_eval_jacobi_types[22] = NPY_DOUBLE
+ufunc_eval_jacobi_types[23] = NPY_CDOUBLE
+ufunc_eval_jacobi_types[24] = NPY_CDOUBLE
+ufunc_eval_jacobi_ptr[2*0] = _func_eval_jacobi_l
+ufunc_eval_jacobi_ptr[2*0+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*1] = _func_eval_jacobi[double]
+ufunc_eval_jacobi_ptr[2*1+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*2] = _func_eval_jacobi[double_complex]
+ufunc_eval_jacobi_ptr[2*2+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*3] = _func_eval_jacobi[double]
+ufunc_eval_jacobi_ptr[2*3+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*4] = _func_eval_jacobi[double_complex]
+ufunc_eval_jacobi_ptr[2*4+1] = ("eval_jacobi")
+ufunc_eval_jacobi_data[0] = &ufunc_eval_jacobi_ptr[2*0]
+ufunc_eval_jacobi_data[1] = &ufunc_eval_jacobi_ptr[2*1]
+ufunc_eval_jacobi_data[2] = &ufunc_eval_jacobi_ptr[2*2]
+ufunc_eval_jacobi_data[3] = &ufunc_eval_jacobi_ptr[2*3]
+ufunc_eval_jacobi_data[4] = &ufunc_eval_jacobi_ptr[2*4]
+eval_jacobi = np.PyUFunc_FromFuncAndData(ufunc_eval_jacobi_loops, ufunc_eval_jacobi_data, ufunc_eval_jacobi_types, 5, 4, 1, 0, "eval_jacobi", ufunc_eval_jacobi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_laguerre_loops[5]
+cdef void *ufunc_eval_laguerre_ptr[10]
+cdef void *ufunc_eval_laguerre_data[5]
+cdef char ufunc_eval_laguerre_types[15]
+cdef char *ufunc_eval_laguerre_doc = (
+    "eval_laguerre(n, x, out=None)\n"
+    "\n"
+    "Evaluate Laguerre polynomial at a point.\n"
+    "\n"
+    "The Laguerre polynomials can be defined via the confluent\n"
+    "hypergeometric function :math:`{}_1F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    L_n(x) = {}_1F_1(-n, 1, x).\n"
+    "\n"
+    "See 22.5.16 and 22.5.54 in [AS]_ for details. When :math:`n` is an\n"
+    "integer the result is a polynomial of degree :math:`n`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer the result is\n"
+    "    determined via the relation to the confluent hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Laguerre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "L : scalar or ndarray\n"
+    "    Values of the Laguerre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_laguerre : roots and quadrature weights of Laguerre\n"
+    "                 polynomials\n"
+    "laguerre : Laguerre polynomial object\n"
+    "numpy.polynomial.laguerre.Laguerre : Laguerre series\n"
+    "eval_genlaguerre : evaluate generalized Laguerre polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_laguerre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_laguerre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_laguerre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_laguerre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_laguerre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_laguerre_types[0] = NPY_INTP
+ufunc_eval_laguerre_types[1] = NPY_DOUBLE
+ufunc_eval_laguerre_types[2] = NPY_DOUBLE
+ufunc_eval_laguerre_types[3] = NPY_FLOAT
+ufunc_eval_laguerre_types[4] = NPY_FLOAT
+ufunc_eval_laguerre_types[5] = NPY_FLOAT
+ufunc_eval_laguerre_types[6] = NPY_FLOAT
+ufunc_eval_laguerre_types[7] = NPY_CFLOAT
+ufunc_eval_laguerre_types[8] = NPY_CFLOAT
+ufunc_eval_laguerre_types[9] = NPY_DOUBLE
+ufunc_eval_laguerre_types[10] = NPY_DOUBLE
+ufunc_eval_laguerre_types[11] = NPY_DOUBLE
+ufunc_eval_laguerre_types[12] = NPY_DOUBLE
+ufunc_eval_laguerre_types[13] = NPY_CDOUBLE
+ufunc_eval_laguerre_types[14] = NPY_CDOUBLE
+ufunc_eval_laguerre_ptr[2*0] = _func_eval_laguerre_l
+ufunc_eval_laguerre_ptr[2*0+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*1] = _func_eval_laguerre[double]
+ufunc_eval_laguerre_ptr[2*1+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*2] = _func_eval_laguerre[double_complex]
+ufunc_eval_laguerre_ptr[2*2+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*3] = _func_eval_laguerre[double]
+ufunc_eval_laguerre_ptr[2*3+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*4] = _func_eval_laguerre[double_complex]
+ufunc_eval_laguerre_ptr[2*4+1] = ("eval_laguerre")
+ufunc_eval_laguerre_data[0] = &ufunc_eval_laguerre_ptr[2*0]
+ufunc_eval_laguerre_data[1] = &ufunc_eval_laguerre_ptr[2*1]
+ufunc_eval_laguerre_data[2] = &ufunc_eval_laguerre_ptr[2*2]
+ufunc_eval_laguerre_data[3] = &ufunc_eval_laguerre_ptr[2*3]
+ufunc_eval_laguerre_data[4] = &ufunc_eval_laguerre_ptr[2*4]
+eval_laguerre = np.PyUFunc_FromFuncAndData(ufunc_eval_laguerre_loops, ufunc_eval_laguerre_data, ufunc_eval_laguerre_types, 5, 2, 1, 0, "eval_laguerre", ufunc_eval_laguerre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_legendre_loops[5]
+cdef void *ufunc_eval_legendre_ptr[10]
+cdef void *ufunc_eval_legendre_data[5]
+cdef char ufunc_eval_legendre_types[15]
+cdef char *ufunc_eval_legendre_doc = (
+    "eval_legendre(n, x, out=None)\n"
+    "\n"
+    "Evaluate Legendre polynomial at a point.\n"
+    "\n"
+    "The Legendre polynomials can be defined via the Gauss\n"
+    "hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n(x) = {}_2F_1(-n, n + 1; 1; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.49 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Legendre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the Legendre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_legendre : roots and quadrature weights of Legendre\n"
+    "                 polynomials\n"
+    "legendre : Legendre polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "numpy.polynomial.legendre.Legendre : Legendre series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import eval_legendre\n"
+    "\n"
+    "Evaluate the zero-order Legendre polynomial at x = 0\n"
+    "\n"
+    ">>> eval_legendre(0, 0)\n"
+    "1.0\n"
+    "\n"
+    "Evaluate the first-order Legendre polynomial between -1 and 1\n"
+    "\n"
+    ">>> X = np.linspace(-1, 1, 5)  # Domain of Legendre polynomials\n"
+    ">>> eval_legendre(1, X)\n"
+    "array([-1. , -0.5,  0. ,  0.5,  1. ])\n"
+    "\n"
+    "Evaluate Legendre polynomials of order 0 through 4 at x = 0\n"
+    "\n"
+    ">>> N = range(0, 5)\n"
+    ">>> eval_legendre(N, 0)\n"
+    "array([ 1.   ,  0.   , -0.5  ,  0.   ,  0.375])\n"
+    "\n"
+    "Plot Legendre polynomials of order 0 through 4\n"
+    "\n"
+    ">>> X = np.linspace(-1, 1)\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> for n in range(0, 5):\n"
+    "...     y = eval_legendre(n, X)\n"
+    "...     plt.plot(X, y, label=r'$P_{}(x)$'.format(n))\n"
+    "\n"
+    ">>> plt.title(\"Legendre Polynomials\")\n"
+    ">>> plt.xlabel(\"x\")\n"
+    ">>> plt.ylabel(r'$P_n(x)$')\n"
+    ">>> plt.legend(loc='lower right')\n"
+    ">>> plt.show()")
+ufunc_eval_legendre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_legendre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_legendre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_legendre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_legendre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_legendre_types[0] = NPY_INTP
+ufunc_eval_legendre_types[1] = NPY_DOUBLE
+ufunc_eval_legendre_types[2] = NPY_DOUBLE
+ufunc_eval_legendre_types[3] = NPY_FLOAT
+ufunc_eval_legendre_types[4] = NPY_FLOAT
+ufunc_eval_legendre_types[5] = NPY_FLOAT
+ufunc_eval_legendre_types[6] = NPY_FLOAT
+ufunc_eval_legendre_types[7] = NPY_CFLOAT
+ufunc_eval_legendre_types[8] = NPY_CFLOAT
+ufunc_eval_legendre_types[9] = NPY_DOUBLE
+ufunc_eval_legendre_types[10] = NPY_DOUBLE
+ufunc_eval_legendre_types[11] = NPY_DOUBLE
+ufunc_eval_legendre_types[12] = NPY_DOUBLE
+ufunc_eval_legendre_types[13] = NPY_CDOUBLE
+ufunc_eval_legendre_types[14] = NPY_CDOUBLE
+ufunc_eval_legendre_ptr[2*0] = _func_eval_legendre_l
+ufunc_eval_legendre_ptr[2*0+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*1] = _func_eval_legendre[double]
+ufunc_eval_legendre_ptr[2*1+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*2] = _func_eval_legendre[double_complex]
+ufunc_eval_legendre_ptr[2*2+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*3] = _func_eval_legendre[double]
+ufunc_eval_legendre_ptr[2*3+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*4] = _func_eval_legendre[double_complex]
+ufunc_eval_legendre_ptr[2*4+1] = ("eval_legendre")
+ufunc_eval_legendre_data[0] = &ufunc_eval_legendre_ptr[2*0]
+ufunc_eval_legendre_data[1] = &ufunc_eval_legendre_ptr[2*1]
+ufunc_eval_legendre_data[2] = &ufunc_eval_legendre_ptr[2*2]
+ufunc_eval_legendre_data[3] = &ufunc_eval_legendre_ptr[2*3]
+ufunc_eval_legendre_data[4] = &ufunc_eval_legendre_ptr[2*4]
+eval_legendre = np.PyUFunc_FromFuncAndData(ufunc_eval_legendre_loops, ufunc_eval_legendre_data, ufunc_eval_legendre_types, 5, 2, 1, 0, "eval_legendre", ufunc_eval_legendre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_chebyt_loops[5]
+cdef void *ufunc_eval_sh_chebyt_ptr[10]
+cdef void *ufunc_eval_sh_chebyt_data[5]
+cdef char ufunc_eval_sh_chebyt_types[15]
+cdef char *ufunc_eval_sh_chebyt_doc = (
+    "eval_sh_chebyt(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Chebyshev polynomial of the first kind at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    T_n^*(x) = T_n(2x - 1)\n"
+    "\n"
+    "where :math:`T_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.14 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyt`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "T : scalar or ndarray\n"
+    "    Values of the shifted Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_chebyt : roots and quadrature weights of shifted\n"
+    "                  Chebyshev polynomials of the first kind\n"
+    "sh_chebyt : shifted Chebyshev polynomial object\n"
+    "eval_chebyt : evaluate Chebyshev polynomials of the first kind\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_chebyt_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_chebyt_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_chebyt_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_chebyt_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_chebyt_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_chebyt_types[0] = NPY_INTP
+ufunc_eval_sh_chebyt_types[1] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[2] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[3] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[4] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[5] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[6] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[7] = NPY_CFLOAT
+ufunc_eval_sh_chebyt_types[8] = NPY_CFLOAT
+ufunc_eval_sh_chebyt_types[9] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[10] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[11] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[12] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_chebyt_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_chebyt_ptr[2*0] = _func_eval_sh_chebyt_l
+ufunc_eval_sh_chebyt_ptr[2*0+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*1] = _func_eval_sh_chebyt[double]
+ufunc_eval_sh_chebyt_ptr[2*1+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*2] = _func_eval_sh_chebyt[double_complex]
+ufunc_eval_sh_chebyt_ptr[2*2+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*3] = _func_eval_sh_chebyt[double]
+ufunc_eval_sh_chebyt_ptr[2*3+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*4] = _func_eval_sh_chebyt[double_complex]
+ufunc_eval_sh_chebyt_ptr[2*4+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_data[0] = &ufunc_eval_sh_chebyt_ptr[2*0]
+ufunc_eval_sh_chebyt_data[1] = &ufunc_eval_sh_chebyt_ptr[2*1]
+ufunc_eval_sh_chebyt_data[2] = &ufunc_eval_sh_chebyt_ptr[2*2]
+ufunc_eval_sh_chebyt_data[3] = &ufunc_eval_sh_chebyt_ptr[2*3]
+ufunc_eval_sh_chebyt_data[4] = &ufunc_eval_sh_chebyt_ptr[2*4]
+eval_sh_chebyt = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_chebyt_loops, ufunc_eval_sh_chebyt_data, ufunc_eval_sh_chebyt_types, 5, 2, 1, 0, "eval_sh_chebyt", ufunc_eval_sh_chebyt_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_chebyu_loops[5]
+cdef void *ufunc_eval_sh_chebyu_ptr[10]
+cdef void *ufunc_eval_sh_chebyu_data[5]
+cdef char ufunc_eval_sh_chebyu_types[15]
+cdef char *ufunc_eval_sh_chebyu_doc = (
+    "eval_sh_chebyu(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Chebyshev polynomial of the second kind at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    U_n^*(x) = U_n(2x - 1)\n"
+    "\n"
+    "where :math:`U_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.15 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyu`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "U : scalar or ndarray\n"
+    "    Values of the shifted Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_chebyu : roots and quadrature weights of shifted\n"
+    "                  Chebychev polynomials of the second kind\n"
+    "sh_chebyu : shifted Chebyshev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_chebyu_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_chebyu_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_chebyu_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_chebyu_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_chebyu_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_chebyu_types[0] = NPY_INTP
+ufunc_eval_sh_chebyu_types[1] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[2] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[3] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[4] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[5] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[6] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[7] = NPY_CFLOAT
+ufunc_eval_sh_chebyu_types[8] = NPY_CFLOAT
+ufunc_eval_sh_chebyu_types[9] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[10] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[11] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[12] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_chebyu_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_chebyu_ptr[2*0] = _func_eval_sh_chebyu_l
+ufunc_eval_sh_chebyu_ptr[2*0+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*1] = _func_eval_sh_chebyu[double]
+ufunc_eval_sh_chebyu_ptr[2*1+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*2] = _func_eval_sh_chebyu[double_complex]
+ufunc_eval_sh_chebyu_ptr[2*2+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*3] = _func_eval_sh_chebyu[double]
+ufunc_eval_sh_chebyu_ptr[2*3+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*4] = _func_eval_sh_chebyu[double_complex]
+ufunc_eval_sh_chebyu_ptr[2*4+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_data[0] = &ufunc_eval_sh_chebyu_ptr[2*0]
+ufunc_eval_sh_chebyu_data[1] = &ufunc_eval_sh_chebyu_ptr[2*1]
+ufunc_eval_sh_chebyu_data[2] = &ufunc_eval_sh_chebyu_ptr[2*2]
+ufunc_eval_sh_chebyu_data[3] = &ufunc_eval_sh_chebyu_ptr[2*3]
+ufunc_eval_sh_chebyu_data[4] = &ufunc_eval_sh_chebyu_ptr[2*4]
+eval_sh_chebyu = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_chebyu_loops, ufunc_eval_sh_chebyu_data, ufunc_eval_sh_chebyu_types, 5, 2, 1, 0, "eval_sh_chebyu", ufunc_eval_sh_chebyu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_jacobi_loops[5]
+cdef void *ufunc_eval_sh_jacobi_ptr[10]
+cdef void *ufunc_eval_sh_jacobi_data[5]
+cdef char ufunc_eval_sh_jacobi_types[25]
+cdef char *ufunc_eval_sh_jacobi_doc = (
+    "eval_sh_jacobi(n, p, q, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Jacobi polynomial at a point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    G_n^{(p, q)}(x)\n"
+    "      = \\binom{2n + p - 1}{n}^{-1} P_n^{(p - q, q - 1)}(2x - 1),\n"
+    "\n"
+    "where :math:`P_n^{(\\cdot, \\cdot)}` is the n-th Jacobi\n"
+    "polynomial. See 22.5.2 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `binom` and `eval_jacobi`.\n"
+    "p : float\n"
+    "    Parameter\n"
+    "q : float\n"
+    "    Parameter\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "G : scalar or ndarray\n"
+    "    Values of the shifted Jacobi polynomial.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_jacobi : roots and quadrature weights of shifted Jacobi\n"
+    "                  polynomials\n"
+    "sh_jacobi : shifted Jacobi polynomial object\n"
+    "eval_jacobi : evaluate Jacobi polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_jacobi_loops[0] = loop_d_pddd__As_pddd_d
+ufunc_eval_sh_jacobi_loops[1] = loop_d_dddd__As_ffff_f
+ufunc_eval_sh_jacobi_loops[2] = loop_D_dddD__As_fffF_F
+ufunc_eval_sh_jacobi_loops[3] = loop_d_dddd__As_dddd_d
+ufunc_eval_sh_jacobi_loops[4] = loop_D_dddD__As_dddD_D
+ufunc_eval_sh_jacobi_types[0] = NPY_INTP
+ufunc_eval_sh_jacobi_types[1] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[2] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[3] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[4] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[5] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[6] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[7] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[8] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[9] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[10] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[11] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[12] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[13] = NPY_CFLOAT
+ufunc_eval_sh_jacobi_types[14] = NPY_CFLOAT
+ufunc_eval_sh_jacobi_types[15] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[16] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[17] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[18] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[19] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[20] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[21] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[22] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[23] = NPY_CDOUBLE
+ufunc_eval_sh_jacobi_types[24] = NPY_CDOUBLE
+ufunc_eval_sh_jacobi_ptr[2*0] = _func_eval_sh_jacobi_l
+ufunc_eval_sh_jacobi_ptr[2*0+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*1] = _func_eval_sh_jacobi[double]
+ufunc_eval_sh_jacobi_ptr[2*1+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*2] = _func_eval_sh_jacobi[double_complex]
+ufunc_eval_sh_jacobi_ptr[2*2+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*3] = _func_eval_sh_jacobi[double]
+ufunc_eval_sh_jacobi_ptr[2*3+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*4] = _func_eval_sh_jacobi[double_complex]
+ufunc_eval_sh_jacobi_ptr[2*4+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_data[0] = &ufunc_eval_sh_jacobi_ptr[2*0]
+ufunc_eval_sh_jacobi_data[1] = &ufunc_eval_sh_jacobi_ptr[2*1]
+ufunc_eval_sh_jacobi_data[2] = &ufunc_eval_sh_jacobi_ptr[2*2]
+ufunc_eval_sh_jacobi_data[3] = &ufunc_eval_sh_jacobi_ptr[2*3]
+ufunc_eval_sh_jacobi_data[4] = &ufunc_eval_sh_jacobi_ptr[2*4]
+eval_sh_jacobi = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_jacobi_loops, ufunc_eval_sh_jacobi_data, ufunc_eval_sh_jacobi_types, 5, 4, 1, 0, "eval_sh_jacobi", ufunc_eval_sh_jacobi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_legendre_loops[5]
+cdef void *ufunc_eval_sh_legendre_ptr[10]
+cdef void *ufunc_eval_sh_legendre_data[5]
+cdef char ufunc_eval_sh_legendre_types[15]
+cdef char *ufunc_eval_sh_legendre_doc = (
+    "eval_sh_legendre(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Legendre polynomial at a point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n^*(x) = P_n(2x - 1)\n"
+    "\n"
+    "where :math:`P_n` is a Legendre polynomial. See 2.2.11 in [AS]_\n"
+    "for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the value is\n"
+    "    determined via the relation to `eval_legendre`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Legendre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the shifted Legendre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_legendre : roots and quadrature weights of shifted\n"
+    "                    Legendre polynomials\n"
+    "sh_legendre : shifted Legendre polynomial object\n"
+    "eval_legendre : evaluate Legendre polynomials\n"
+    "numpy.polynomial.legendre.Legendre : Legendre series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_legendre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_legendre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_legendre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_legendre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_legendre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_legendre_types[0] = NPY_INTP
+ufunc_eval_sh_legendre_types[1] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[2] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[3] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[4] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[5] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[6] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[7] = NPY_CFLOAT
+ufunc_eval_sh_legendre_types[8] = NPY_CFLOAT
+ufunc_eval_sh_legendre_types[9] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[10] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[11] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[12] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_legendre_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_legendre_ptr[2*0] = _func_eval_sh_legendre_l
+ufunc_eval_sh_legendre_ptr[2*0+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*1] = _func_eval_sh_legendre[double]
+ufunc_eval_sh_legendre_ptr[2*1+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*2] = _func_eval_sh_legendre[double_complex]
+ufunc_eval_sh_legendre_ptr[2*2+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*3] = _func_eval_sh_legendre[double]
+ufunc_eval_sh_legendre_ptr[2*3+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*4] = _func_eval_sh_legendre[double_complex]
+ufunc_eval_sh_legendre_ptr[2*4+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_data[0] = &ufunc_eval_sh_legendre_ptr[2*0]
+ufunc_eval_sh_legendre_data[1] = &ufunc_eval_sh_legendre_ptr[2*1]
+ufunc_eval_sh_legendre_data[2] = &ufunc_eval_sh_legendre_ptr[2*2]
+ufunc_eval_sh_legendre_data[3] = &ufunc_eval_sh_legendre_ptr[2*3]
+ufunc_eval_sh_legendre_data[4] = &ufunc_eval_sh_legendre_ptr[2*4]
+eval_sh_legendre = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_legendre_loops, ufunc_eval_sh_legendre_data, ufunc_eval_sh_legendre_types, 5, 2, 1, 0, "eval_sh_legendre", ufunc_eval_sh_legendre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_exp10_loops[2]
+cdef void *ufunc_exp10_ptr[4]
+cdef void *ufunc_exp10_data[2]
+cdef char ufunc_exp10_types[4]
+cdef char *ufunc_exp10_doc = (
+    "exp10(x, out=None)\n"
+    "\n"
+    "Compute ``10**x`` element-wise.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``10**x``, computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import exp10\n"
+    "\n"
+    ">>> exp10(3)\n"
+    "1000.0\n"
+    ">>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])\n"
+    ">>> exp10(x)\n"
+    "array([[  0.1       ,   0.31622777,   1.        ],\n"
+    "       [  3.16227766,  10.        ,  31.6227766 ]])")
+ufunc_exp10_loops[0] = loop_d_d__As_f_f
+ufunc_exp10_loops[1] = loop_d_d__As_d_d
+ufunc_exp10_types[0] = NPY_FLOAT
+ufunc_exp10_types[1] = NPY_FLOAT
+ufunc_exp10_types[2] = NPY_DOUBLE
+ufunc_exp10_types[3] = NPY_DOUBLE
+ufunc_exp10_ptr[2*0] = _func_cephes_exp10
+ufunc_exp10_ptr[2*0+1] = ("exp10")
+ufunc_exp10_ptr[2*1] = _func_cephes_exp10
+ufunc_exp10_ptr[2*1+1] = ("exp10")
+ufunc_exp10_data[0] = &ufunc_exp10_ptr[2*0]
+ufunc_exp10_data[1] = &ufunc_exp10_ptr[2*1]
+exp10 = np.PyUFunc_FromFuncAndData(ufunc_exp10_loops, ufunc_exp10_data, ufunc_exp10_types, 2, 1, 1, 0, "exp10", ufunc_exp10_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_exp2_loops[2]
+cdef void *ufunc_exp2_ptr[4]
+cdef void *ufunc_exp2_data[2]
+cdef char ufunc_exp2_types[4]
+cdef char *ufunc_exp2_doc = (
+    "exp2(x, out=None)\n"
+    "\n"
+    "Compute ``2**x`` element-wise.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``2**x``, computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import exp2\n"
+    "\n"
+    ">>> exp2(3)\n"
+    "8.0\n"
+    ">>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])\n"
+    ">>> exp2(x)\n"
+    "array([[ 0.5       ,  0.70710678,  1.        ],\n"
+    "       [ 1.41421356,  2.        ,  2.82842712]])")
+ufunc_exp2_loops[0] = loop_d_d__As_f_f
+ufunc_exp2_loops[1] = loop_d_d__As_d_d
+ufunc_exp2_types[0] = NPY_FLOAT
+ufunc_exp2_types[1] = NPY_FLOAT
+ufunc_exp2_types[2] = NPY_DOUBLE
+ufunc_exp2_types[3] = NPY_DOUBLE
+ufunc_exp2_ptr[2*0] = _func_cephes_exp2
+ufunc_exp2_ptr[2*0+1] = ("exp2")
+ufunc_exp2_ptr[2*1] = _func_cephes_exp2
+ufunc_exp2_ptr[2*1+1] = ("exp2")
+ufunc_exp2_data[0] = &ufunc_exp2_ptr[2*0]
+ufunc_exp2_data[1] = &ufunc_exp2_ptr[2*1]
+exp2 = np.PyUFunc_FromFuncAndData(ufunc_exp2_loops, ufunc_exp2_data, ufunc_exp2_types, 2, 1, 1, 0, "exp2", ufunc_exp2_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_expm1_loops[4]
+cdef void *ufunc_expm1_ptr[8]
+cdef void *ufunc_expm1_data[4]
+cdef char ufunc_expm1_types[8]
+cdef char *ufunc_expm1_doc = (
+    "expm1(x, out=None)\n"
+    "\n"
+    "Compute ``exp(x) - 1``.\n"
+    "\n"
+    "When `x` is near zero, ``exp(x)`` is near 1, so the numerical calculation\n"
+    "of ``exp(x) - 1`` can suffer from catastrophic loss of precision.\n"
+    "``expm1(x)`` is implemented to avoid the loss of precision that occurs when\n"
+    "`x` is near zero.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``exp(x) - 1`` computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import expm1\n"
+    "\n"
+    ">>> expm1(1.0)\n"
+    "1.7182818284590451\n"
+    ">>> expm1([-0.2, -0.1, 0, 0.1, 0.2])\n"
+    "array([-0.18126925, -0.09516258,  0.        ,  0.10517092,  0.22140276])\n"
+    "\n"
+    "The exact value of ``exp(7.5e-13) - 1`` is::\n"
+    "\n"
+    "    7.5000000000028125000000007031250000001318...*10**-13.\n"
+    "\n"
+    "Here is what ``expm1(7.5e-13)`` gives:\n"
+    "\n"
+    ">>> expm1(7.5e-13)\n"
+    "7.5000000000028135e-13\n"
+    "\n"
+    "Compare that to ``exp(7.5e-13) - 1``, where the subtraction results in\n"
+    "a \"catastrophic\" loss of precision:\n"
+    "\n"
+    ">>> np.exp(7.5e-13) - 1\n"
+    "7.5006667543675576e-13")
+ufunc_expm1_loops[0] = loop_d_d__As_f_f
+ufunc_expm1_loops[1] = loop_d_d__As_d_d
+ufunc_expm1_loops[2] = loop_D_D__As_F_F
+ufunc_expm1_loops[3] = loop_D_D__As_D_D
+ufunc_expm1_types[0] = NPY_FLOAT
+ufunc_expm1_types[1] = NPY_FLOAT
+ufunc_expm1_types[2] = NPY_DOUBLE
+ufunc_expm1_types[3] = NPY_DOUBLE
+ufunc_expm1_types[4] = NPY_CFLOAT
+ufunc_expm1_types[5] = NPY_CFLOAT
+ufunc_expm1_types[6] = NPY_CDOUBLE
+ufunc_expm1_types[7] = NPY_CDOUBLE
+ufunc_expm1_ptr[2*0] = _func_cephes_expm1
+ufunc_expm1_ptr[2*0+1] = ("expm1")
+ufunc_expm1_ptr[2*1] = _func_cephes_expm1
+ufunc_expm1_ptr[2*1+1] = ("expm1")
+ufunc_expm1_ptr[2*2] = _func_cexpm1
+ufunc_expm1_ptr[2*2+1] = ("expm1")
+ufunc_expm1_ptr[2*3] = _func_cexpm1
+ufunc_expm1_ptr[2*3+1] = ("expm1")
+ufunc_expm1_data[0] = &ufunc_expm1_ptr[2*0]
+ufunc_expm1_data[1] = &ufunc_expm1_ptr[2*1]
+ufunc_expm1_data[2] = &ufunc_expm1_ptr[2*2]
+ufunc_expm1_data[3] = &ufunc_expm1_ptr[2*3]
+expm1 = np.PyUFunc_FromFuncAndData(ufunc_expm1_loops, ufunc_expm1_data, ufunc_expm1_types, 4, 1, 1, 0, "expm1", ufunc_expm1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_expn_loops[3]
+cdef void *ufunc_expn_ptr[6]
+cdef void *ufunc_expn_data[3]
+cdef char ufunc_expn_types[9]
+cdef char *ufunc_expn_doc = (
+    "expn(n, x, out=None)\n"
+    "\n"
+    "Generalized exponential integral En.\n"
+    "\n"
+    "For integer :math:`n \\geq 0` and real :math:`x \\geq 0` the\n"
+    "generalized exponential integral is defined as [dlmf]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    E_n(x) = x^{n - 1} \\int_x^\\infty \\frac{e^{-t}}{t^n} dt.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Non-negative integers\n"
+    "x : array_like\n"
+    "    Real argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the generalized exponential integral\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "exp1 : special case of :math:`E_n` for :math:`n = 1`\n"
+    "expi : related to :math:`E_n` when :math:`n = 1`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] Digital Library of Mathematical Functions, 8.19.2\n"
+    "          https://dlmf.nist.gov/8.19#E2\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Its domain is nonnegative n and x.\n"
+    "\n"
+    ">>> sc.expn(-1, 1.0), sc.expn(1, -1.0)\n"
+    "(nan, nan)\n"
+    "\n"
+    "It has a pole at ``x = 0`` for ``n = 1, 2``; for larger ``n`` it\n"
+    "is equal to ``1 / (n - 1)``.\n"
+    "\n"
+    ">>> sc.expn([0, 1, 2, 3, 4], 0)\n"
+    "array([       inf,        inf, 1.        , 0.5       , 0.33333333])\n"
+    "\n"
+    "For n equal to 0 it reduces to ``exp(-x) / x``.\n"
+    "\n"
+    ">>> x = np.array([1, 2, 3, 4])\n"
+    ">>> sc.expn(0, x)\n"
+    "array([0.36787944, 0.06766764, 0.01659569, 0.00457891])\n"
+    ">>> np.exp(-x) / x\n"
+    "array([0.36787944, 0.06766764, 0.01659569, 0.00457891])\n"
+    "\n"
+    "For n equal to 1 it reduces to `exp1`.\n"
+    "\n"
+    ">>> sc.expn(1, x)\n"
+    "array([0.21938393, 0.04890051, 0.01304838, 0.00377935])\n"
+    ">>> sc.exp1(x)\n"
+    "array([0.21938393, 0.04890051, 0.01304838, 0.00377935])")
+ufunc_expn_loops[0] = loop_d_pd__As_pd_d
+ufunc_expn_loops[1] = loop_d_dd__As_ff_f
+ufunc_expn_loops[2] = loop_d_dd__As_dd_d
+ufunc_expn_types[0] = NPY_INTP
+ufunc_expn_types[1] = NPY_DOUBLE
+ufunc_expn_types[2] = NPY_DOUBLE
+ufunc_expn_types[3] = NPY_FLOAT
+ufunc_expn_types[4] = NPY_FLOAT
+ufunc_expn_types[5] = NPY_FLOAT
+ufunc_expn_types[6] = NPY_DOUBLE
+ufunc_expn_types[7] = NPY_DOUBLE
+ufunc_expn_types[8] = NPY_DOUBLE
+ufunc_expn_ptr[2*0] = _func_cephes_expn_wrap
+ufunc_expn_ptr[2*0+1] = ("expn")
+ufunc_expn_ptr[2*1] = _func_expn_unsafe
+ufunc_expn_ptr[2*1+1] = ("expn")
+ufunc_expn_ptr[2*2] = _func_expn_unsafe
+ufunc_expn_ptr[2*2+1] = ("expn")
+ufunc_expn_data[0] = &ufunc_expn_ptr[2*0]
+ufunc_expn_data[1] = &ufunc_expn_ptr[2*1]
+ufunc_expn_data[2] = &ufunc_expn_ptr[2*2]
+expn = np.PyUFunc_FromFuncAndData(ufunc_expn_loops, ufunc_expn_data, ufunc_expn_types, 3, 2, 1, 0, "expn", ufunc_expn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtr_loops[2]
+cdef void *ufunc_fdtr_ptr[4]
+cdef void *ufunc_fdtr_data[2]
+cdef char ufunc_fdtr_types[8]
+cdef char *ufunc_fdtr_doc = (
+    "fdtr(dfn, dfd, x, out=None)\n"
+    "\n"
+    "F cumulative distribution function.\n"
+    "\n"
+    "Returns the value of the cumulative distribution function of the\n"
+    "F-distribution, also known as Snedecor's F-distribution or the\n"
+    "Fisher-Snedecor distribution.\n"
+    "\n"
+    "The F-distribution with parameters :math:`d_n` and :math:`d_d` is the\n"
+    "distribution of the random variable,\n"
+    "\n"
+    ".. math::\n"
+    "    X = \\frac{U_n/d_n}{U_d/d_d},\n"
+    "\n"
+    "where :math:`U_n` and :math:`U_d` are random variables distributed\n"
+    ":math:`\\chi^2`, with :math:`d_n` and :math:`d_d` degrees of freedom,\n"
+    "respectively.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    The CDF of the F-distribution with parameters `dfn` and `dfd` at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtrc : F distribution survival function\n"
+    "fdtri : F distribution inverse cumulative distribution\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The regularized incomplete beta function is used, according to the\n"
+    "formula,\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d; x) = I_{xd_n/(d_d + xd_n)}(d_n/2, d_d/2).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtr`. The F distribution is also\n"
+    "available as `scipy.stats.f`. Calling `fdtr` directly can improve\n"
+    "performance compared to the ``cdf`` method of `scipy.stats.f` (see last\n"
+    "example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtr\n"
+    ">>> fdtr(1, 2, 1)\n"
+    "0.5773502691896258\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.5, 2., 3.])\n"
+    ">>> fdtr(1, 2, x)\n"
+    "array([0.4472136 , 0.70710678, 0.77459667])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [1, 5, 10, 50]\n"
+    ">>> dfd_parameters = [1, 1, 2, 3]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtr_vals = fdtr(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtr_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"F distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtr`\n"
+    "directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).cdf(x)=fdtr(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 1\n"
+    ">>> fdtr_res = fdtr(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).cdf(x)\n"
+    ">>> fdtr_res == f_dist_res  # test that results are equal\n"
+    "True")
+ufunc_fdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtr_types[0] = NPY_FLOAT
+ufunc_fdtr_types[1] = NPY_FLOAT
+ufunc_fdtr_types[2] = NPY_FLOAT
+ufunc_fdtr_types[3] = NPY_FLOAT
+ufunc_fdtr_types[4] = NPY_DOUBLE
+ufunc_fdtr_types[5] = NPY_DOUBLE
+ufunc_fdtr_types[6] = NPY_DOUBLE
+ufunc_fdtr_types[7] = NPY_DOUBLE
+ufunc_fdtr_ptr[2*0] = _func_xsf_fdtr
+ufunc_fdtr_ptr[2*0+1] = ("fdtr")
+ufunc_fdtr_ptr[2*1] = _func_xsf_fdtr
+ufunc_fdtr_ptr[2*1+1] = ("fdtr")
+ufunc_fdtr_data[0] = &ufunc_fdtr_ptr[2*0]
+ufunc_fdtr_data[1] = &ufunc_fdtr_ptr[2*1]
+fdtr = np.PyUFunc_FromFuncAndData(ufunc_fdtr_loops, ufunc_fdtr_data, ufunc_fdtr_types, 2, 3, 1, 0, "fdtr", ufunc_fdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtrc_loops[2]
+cdef void *ufunc_fdtrc_ptr[4]
+cdef void *ufunc_fdtrc_data[2]
+cdef char ufunc_fdtrc_types[8]
+cdef char *ufunc_fdtrc_doc = (
+    "fdtrc(dfn, dfd, x, out=None)\n"
+    "\n"
+    "F survival function.\n"
+    "\n"
+    "Returns the complemented F-distribution function (the integral of the\n"
+    "density from `x` to infinity).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    The complemented F-distribution function with parameters `dfn` and\n"
+    "    `dfd` at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtri : F distribution inverse cumulative distribution function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The regularized incomplete beta function is used, according to the\n"
+    "formula,\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d; x) = I_{d_d/(d_d + xd_n)}(d_d/2, d_n/2).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtrc`. The F distribution is also\n"
+    "available as `scipy.stats.f`. Calling `fdtrc` directly can improve\n"
+    "performance compared to the ``sf`` method of `scipy.stats.f` (see last\n"
+    "example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtrc\n"
+    ">>> fdtrc(1, 2, 1)\n"
+    "0.42264973081037427\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.5, 2., 3.])\n"
+    ">>> fdtrc(1, 2, x)\n"
+    "array([0.5527864 , 0.29289322, 0.22540333])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [1, 5, 10, 50]\n"
+    ">>> dfd_parameters = [1, 1, 2, 3]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtrc_vals = fdtrc(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtrc_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"F distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtrc`\n"
+    "directly can be much faster than calling the ``sf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).sf(x)=fdtrc(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 1\n"
+    ">>> fdtrc_res = fdtrc(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).sf(x)\n"
+    ">>> f_dist_res == fdtrc_res  # test that results are equal\n"
+    "True")
+ufunc_fdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtrc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtrc_types[0] = NPY_FLOAT
+ufunc_fdtrc_types[1] = NPY_FLOAT
+ufunc_fdtrc_types[2] = NPY_FLOAT
+ufunc_fdtrc_types[3] = NPY_FLOAT
+ufunc_fdtrc_types[4] = NPY_DOUBLE
+ufunc_fdtrc_types[5] = NPY_DOUBLE
+ufunc_fdtrc_types[6] = NPY_DOUBLE
+ufunc_fdtrc_types[7] = NPY_DOUBLE
+ufunc_fdtrc_ptr[2*0] = _func_xsf_fdtrc
+ufunc_fdtrc_ptr[2*0+1] = ("fdtrc")
+ufunc_fdtrc_ptr[2*1] = _func_xsf_fdtrc
+ufunc_fdtrc_ptr[2*1+1] = ("fdtrc")
+ufunc_fdtrc_data[0] = &ufunc_fdtrc_ptr[2*0]
+ufunc_fdtrc_data[1] = &ufunc_fdtrc_ptr[2*1]
+fdtrc = np.PyUFunc_FromFuncAndData(ufunc_fdtrc_loops, ufunc_fdtrc_data, ufunc_fdtrc_types, 2, 3, 1, 0, "fdtrc", ufunc_fdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtri_loops[2]
+cdef void *ufunc_fdtri_ptr[4]
+cdef void *ufunc_fdtri_data[2]
+cdef char ufunc_fdtri_types[8]
+cdef char *ufunc_fdtri_doc = (
+    "fdtri(dfn, dfd, p, out=None)\n"
+    "\n"
+    "The `p`-th quantile of the F-distribution.\n"
+    "\n"
+    "This function is the inverse of the F-distribution CDF, `fdtr`, returning\n"
+    "the `x` such that `fdtr(dfn, dfd, x) = p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    The quantile corresponding to `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtrc : F distribution survival function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The computation is carried out using the relation to the inverse\n"
+    "regularized beta function, :math:`I^{-1}_x(a, b)`.  Let\n"
+    ":math:`z = I^{-1}_p(d_d/2, d_n/2).`  Then,\n"
+    "\n"
+    ".. math::\n"
+    "    x = \\frac{d_d (1 - z)}{d_n z}.\n"
+    "\n"
+    "If `p` is such that :math:`x < 0.5`, the following relation is used\n"
+    "instead for improved stability: let\n"
+    ":math:`z' = I^{-1}_{1 - p}(d_n/2, d_d/2).` Then,\n"
+    "\n"
+    ".. math::\n"
+    "    x = \\frac{d_d z'}{d_n (1 - z')}.\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtri`.\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Calling\n"
+    "`fdtri` directly can improve performance compared to the ``ppf``\n"
+    "method of `scipy.stats.f` (see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`fdtri` represents the inverse of the F distribution CDF which is\n"
+    "available as `fdtr`. Here, we calculate the CDF for ``df1=1``, ``df2=2``\n"
+    "at ``x=3``. `fdtri` then returns ``3`` given the same values for `df1`,\n"
+    "`df2` and the computed CDF value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtri, fdtr\n"
+    ">>> df1, df2 = 1, 2\n"
+    ">>> x = 3\n"
+    ">>> cdf_value =  fdtr(df1, df2, x)\n"
+    ">>> fdtri(df1, df2, cdf_value)\n"
+    "3.000000000000006\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.1, 0.4, 0.7])\n"
+    ">>> fdtri(1, 2, x)\n"
+    "array([0.02020202, 0.38095238, 1.92156863])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [50, 10, 1, 50]\n"
+    ">>> dfd_parameters = [0.5, 1, 1, 5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtri_vals = fdtri(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtri_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> title = \"F distribution inverse cumulative distribution function\"\n"
+    ">>> ax.set_title(title)\n"
+    ">>> ax.set_ylim(0, 30)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtri`\n"
+    "directly can be much faster than calling the ``ppf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).ppf(x)=fdtri(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 0.7\n"
+    ">>> fdtri_res = fdtri(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).ppf(x)\n"
+    ">>> f_dist_res == fdtri_res  # test that results are equal\n"
+    "True")
+ufunc_fdtri_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtri_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtri_types[0] = NPY_FLOAT
+ufunc_fdtri_types[1] = NPY_FLOAT
+ufunc_fdtri_types[2] = NPY_FLOAT
+ufunc_fdtri_types[3] = NPY_FLOAT
+ufunc_fdtri_types[4] = NPY_DOUBLE
+ufunc_fdtri_types[5] = NPY_DOUBLE
+ufunc_fdtri_types[6] = NPY_DOUBLE
+ufunc_fdtri_types[7] = NPY_DOUBLE
+ufunc_fdtri_ptr[2*0] = _func_xsf_fdtri
+ufunc_fdtri_ptr[2*0+1] = ("fdtri")
+ufunc_fdtri_ptr[2*1] = _func_xsf_fdtri
+ufunc_fdtri_ptr[2*1+1] = ("fdtri")
+ufunc_fdtri_data[0] = &ufunc_fdtri_ptr[2*0]
+ufunc_fdtri_data[1] = &ufunc_fdtri_ptr[2*1]
+fdtri = np.PyUFunc_FromFuncAndData(ufunc_fdtri_loops, ufunc_fdtri_data, ufunc_fdtri_types, 2, 3, 1, 0, "fdtri", ufunc_fdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtridfd_loops[2]
+cdef void *ufunc_fdtridfd_ptr[4]
+cdef void *ufunc_fdtridfd_data[2]
+cdef char ufunc_fdtridfd_types[8]
+cdef char *ufunc_fdtridfd_doc = (
+    "fdtridfd(dfn, p, x, out=None)\n"
+    "\n"
+    "Inverse to `fdtr` vs dfd\n"
+    "\n"
+    "Finds the F density argument dfd such that ``fdtr(dfn, dfd, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfd : scalar or ndarray\n"
+    "    `dfd` such that ``fdtr(dfn, dfd, x) == p``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtrc : F distribution survival function\n"
+    "fdtri : F distribution quantile function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the F distribution cumulative distribution function for one\n"
+    "parameter set.\n"
+    "\n"
+    ">>> from scipy.special import fdtridfd, fdtr\n"
+    ">>> dfn, dfd, x = 10, 5, 2\n"
+    ">>> cdf_value = fdtr(dfn, dfd, x)\n"
+    ">>> cdf_value\n"
+    "0.7700248806501017\n"
+    "\n"
+    "Verify that `fdtridfd` recovers the original value for `dfd`:\n"
+    "\n"
+    ">>> fdtridfd(dfn, cdf_value, x)\n"
+    "5.0")
+ufunc_fdtridfd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtridfd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtridfd_types[0] = NPY_FLOAT
+ufunc_fdtridfd_types[1] = NPY_FLOAT
+ufunc_fdtridfd_types[2] = NPY_FLOAT
+ufunc_fdtridfd_types[3] = NPY_FLOAT
+ufunc_fdtridfd_types[4] = NPY_DOUBLE
+ufunc_fdtridfd_types[5] = NPY_DOUBLE
+ufunc_fdtridfd_types[6] = NPY_DOUBLE
+ufunc_fdtridfd_types[7] = NPY_DOUBLE
+ufunc_fdtridfd_ptr[2*0] = _func_fdtridfd
+ufunc_fdtridfd_ptr[2*0+1] = ("fdtridfd")
+ufunc_fdtridfd_ptr[2*1] = _func_fdtridfd
+ufunc_fdtridfd_ptr[2*1+1] = ("fdtridfd")
+ufunc_fdtridfd_data[0] = &ufunc_fdtridfd_ptr[2*0]
+ufunc_fdtridfd_data[1] = &ufunc_fdtridfd_ptr[2*1]
+fdtridfd = np.PyUFunc_FromFuncAndData(ufunc_fdtridfd_loops, ufunc_fdtridfd_data, ufunc_fdtridfd_types, 2, 3, 1, 0, "fdtridfd", ufunc_fdtridfd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtr_loops[2]
+cdef void *ufunc_gdtr_ptr[4]
+cdef void *ufunc_gdtr_data[2]
+cdef char ufunc_gdtr_types[8]
+cdef char *ufunc_gdtr_doc = (
+    "gdtr(a, b, x, out=None)\n"
+    "\n"
+    "Gamma distribution cumulative distribution function.\n"
+    "\n"
+    "Returns the integral from zero to `x` of the gamma probability density\n"
+    "function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\int_0^x \\frac{a^b}{\\Gamma(b)} t^{b-1} e^{-at}\\,dt,\n"
+    "\n"
+    "where :math:`\\Gamma` is the gamma function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    The rate parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\beta` (float).  It is also the reciprocal of the scale\n"
+    "    parameter :math:`\\theta`.\n"
+    "b : array_like\n"
+    "    The shape parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\alpha` (float).\n"
+    "x : array_like\n"
+    "    The quantile (upper limit of integration; float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The CDF of the gamma distribution with parameters `a` and `b`\n"
+    "    evaluated at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtrc : 1 - CDF of the gamma distribution.\n"
+    "scipy.stats.gamma: Gamma distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The evaluation is carried out using the relation to the incomplete gamma\n"
+    "integral (regularized gamma function).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `gdtr`. Calling `gdtr` directly can\n"
+    "improve performance compared to the ``cdf`` method of `scipy.stats.gamma`\n"
+    "(see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``a=1``, ``b=2`` at ``x=5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import gdtr\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> gdtr(1., 2., 5.)\n"
+    "0.9595723180054873\n"
+    "\n"
+    "Compute the function for ``a=1`` and ``b=2`` at several points by\n"
+    "providing a NumPy array for `x`.\n"
+    "\n"
+    ">>> xvalues = np.array([1., 2., 3., 4])\n"
+    ">>> gdtr(1., 1., xvalues)\n"
+    "array([0.63212056, 0.86466472, 0.95021293, 0.98168436])\n"
+    "\n"
+    "`gdtr` can evaluate different parameter sets by providing arrays with\n"
+    "broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the\n"
+    "function for three different `a` at four positions `x` and ``b=3``,\n"
+    "resulting in a 3x4 array.\n"
+    "\n"
+    ">>> a = np.array([[0.5], [1.5], [2.5]])\n"
+    ">>> x = np.array([1., 2., 3., 4])\n"
+    ">>> a.shape, x.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> gdtr(a, 3., x)\n"
+    "array([[0.01438768, 0.0803014 , 0.19115317, 0.32332358],\n"
+    "       [0.19115317, 0.57680992, 0.82642193, 0.9380312 ],\n"
+    "       [0.45618688, 0.87534798, 0.97974328, 0.9972306 ]])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> a_parameters = [0.3, 1, 2, 6]\n"
+    ">>> b_parameters = [2, 10, 15, 20]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     a, b, style = parameter_set\n"
+    "...     gdtr_vals = gdtr(a, b, x)\n"
+    "...     ax.plot(x, gdtr_vals, label=fr\"$a= {a},\\, b={b}$\", ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"Gamma distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The gamma distribution is also available as `scipy.stats.gamma`. Using\n"
+    "`gdtr` directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.gamma`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.gamma(b, scale=1/a).cdf(x)=gdtr(a, b, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import gamma\n"
+    ">>> a = 2.\n"
+    ">>> b = 3\n"
+    ">>> x = 1.\n"
+    ">>> gdtr_result = gdtr(a, b, x)  # this will often be faster than below\n"
+    ">>> gamma_dist_result = gamma(b, scale=1/a).cdf(x)\n"
+    ">>> gdtr_result == gamma_dist_result  # test that results are equal\n"
+    "True")
+ufunc_gdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtr_types[0] = NPY_FLOAT
+ufunc_gdtr_types[1] = NPY_FLOAT
+ufunc_gdtr_types[2] = NPY_FLOAT
+ufunc_gdtr_types[3] = NPY_FLOAT
+ufunc_gdtr_types[4] = NPY_DOUBLE
+ufunc_gdtr_types[5] = NPY_DOUBLE
+ufunc_gdtr_types[6] = NPY_DOUBLE
+ufunc_gdtr_types[7] = NPY_DOUBLE
+ufunc_gdtr_ptr[2*0] = _func_xsf_gdtr
+ufunc_gdtr_ptr[2*0+1] = ("gdtr")
+ufunc_gdtr_ptr[2*1] = _func_xsf_gdtr
+ufunc_gdtr_ptr[2*1+1] = ("gdtr")
+ufunc_gdtr_data[0] = &ufunc_gdtr_ptr[2*0]
+ufunc_gdtr_data[1] = &ufunc_gdtr_ptr[2*1]
+gdtr = np.PyUFunc_FromFuncAndData(ufunc_gdtr_loops, ufunc_gdtr_data, ufunc_gdtr_types, 2, 3, 1, 0, "gdtr", ufunc_gdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrc_loops[2]
+cdef void *ufunc_gdtrc_ptr[4]
+cdef void *ufunc_gdtrc_data[2]
+cdef char ufunc_gdtrc_types[8]
+cdef char *ufunc_gdtrc_doc = (
+    "gdtrc(a, b, x, out=None)\n"
+    "\n"
+    "Gamma distribution survival function.\n"
+    "\n"
+    "Integral from `x` to infinity of the gamma probability density function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\int_x^\\infty \\frac{a^b}{\\Gamma(b)} t^{b-1} e^{-at}\\,dt,\n"
+    "\n"
+    "where :math:`\\Gamma` is the gamma function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    The rate parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\beta` (float). It is also the reciprocal of the scale\n"
+    "    parameter :math:`\\theta`.\n"
+    "b : array_like\n"
+    "    The shape parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\alpha` (float).\n"
+    "x : array_like\n"
+    "    The quantile (lower limit of integration; float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The survival function of the gamma distribution with parameters `a`\n"
+    "    and `b` evaluated at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr: Gamma distribution cumulative distribution function\n"
+    "scipy.stats.gamma: Gamma distribution\n"
+    "gdtrix\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The evaluation is carried out using the relation to the incomplete gamma\n"
+    "integral (regularized gamma function).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `gdtrc`. Calling `gdtrc` directly can\n"
+    "improve performance compared to the ``sf`` method of `scipy.stats.gamma`\n"
+    "(see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``a=1`` and ``b=2`` at ``x=5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import gdtrc\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> gdtrc(1., 2., 5.)\n"
+    "0.04042768199451279\n"
+    "\n"
+    "Compute the function for ``a=1``, ``b=2`` at several points by providing\n"
+    "a NumPy array for `x`.\n"
+    "\n"
+    ">>> xvalues = np.array([1., 2., 3., 4])\n"
+    ">>> gdtrc(1., 1., xvalues)\n"
+    "array([0.36787944, 0.13533528, 0.04978707, 0.01831564])\n"
+    "\n"
+    "`gdtrc` can evaluate different parameter sets by providing arrays with\n"
+    "broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the\n"
+    "function for three different `a` at four positions `x` and ``b=3``,\n"
+    "resulting in a 3x4 array.\n"
+    "\n"
+    ">>> a = np.array([[0.5], [1.5], [2.5]])\n"
+    ">>> x = np.array([1., 2., 3., 4])\n"
+    ">>> a.shape, x.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> gdtrc(a, 3., x)\n"
+    "array([[0.98561232, 0.9196986 , 0.80884683, 0.67667642],\n"
+    "       [0.80884683, 0.42319008, 0.17357807, 0.0619688 ],\n"
+    "       [0.54381312, 0.12465202, 0.02025672, 0.0027694 ]])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> a_parameters = [0.3, 1, 2, 6]\n"
+    ">>> b_parameters = [2, 10, 15, 20]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     a, b, style = parameter_set\n"
+    "...     gdtrc_vals = gdtrc(a, b, x)\n"
+    "...     ax.plot(x, gdtrc_vals, label=fr\"$a= {a},\\, b={b}$\", ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"Gamma distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The gamma distribution is also available as `scipy.stats.gamma`.\n"
+    "Using `gdtrc` directly can be much faster than calling the ``sf`` method\n"
+    "of `scipy.stats.gamma`, especially for small arrays or individual\n"
+    "values. To get the same results one must use the following parametrization:\n"
+    "``stats.gamma(b, scale=1/a).sf(x)=gdtrc(a, b, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import gamma\n"
+    ">>> a = 2\n"
+    ">>> b = 3\n"
+    ">>> x = 1.\n"
+    ">>> gdtrc_result = gdtrc(a, b, x)  # this will often be faster than below\n"
+    ">>> gamma_dist_result = gamma(b, scale=1/a).sf(x)\n"
+    ">>> gdtrc_result == gamma_dist_result  # test that results are equal\n"
+    "True")
+ufunc_gdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrc_types[0] = NPY_FLOAT
+ufunc_gdtrc_types[1] = NPY_FLOAT
+ufunc_gdtrc_types[2] = NPY_FLOAT
+ufunc_gdtrc_types[3] = NPY_FLOAT
+ufunc_gdtrc_types[4] = NPY_DOUBLE
+ufunc_gdtrc_types[5] = NPY_DOUBLE
+ufunc_gdtrc_types[6] = NPY_DOUBLE
+ufunc_gdtrc_types[7] = NPY_DOUBLE
+ufunc_gdtrc_ptr[2*0] = _func_xsf_gdtrc
+ufunc_gdtrc_ptr[2*0+1] = ("gdtrc")
+ufunc_gdtrc_ptr[2*1] = _func_xsf_gdtrc
+ufunc_gdtrc_ptr[2*1+1] = ("gdtrc")
+ufunc_gdtrc_data[0] = &ufunc_gdtrc_ptr[2*0]
+ufunc_gdtrc_data[1] = &ufunc_gdtrc_ptr[2*1]
+gdtrc = np.PyUFunc_FromFuncAndData(ufunc_gdtrc_loops, ufunc_gdtrc_data, ufunc_gdtrc_types, 2, 3, 1, 0, "gdtrc", ufunc_gdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtria_loops[2]
+cdef void *ufunc_gdtria_ptr[4]
+cdef void *ufunc_gdtria_data[2]
+cdef char ufunc_gdtria_types[8]
+cdef char *ufunc_gdtria_doc = (
+    "gdtria(p, b, x, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs a.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `a` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "b : array_like\n"
+    "    `b` parameter values of `gdtr(a, b, x)`. `b` is the \"shape\" parameter\n"
+    "    of the gamma distribution.\n"
+    "x : array_like\n"
+    "    Nonnegative real values, from the domain of the gamma distribution.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`.  `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "a : scalar or ndarray\n"
+    "    Values of the `a` parameter such that ``p = gdtr(a, b, x)`.  ``1/a``\n"
+    "    is the \"scale\" parameter of the gamma distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtrib : Inverse with respect to `b` of `gdtr(a, b, x)`.\n"
+    "gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `a` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `a`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Computation of the incomplete gamma function ratios and their\n"
+    "       inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtria\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtria(p, 3.4, 5.6)\n"
+    "1.2")
+ufunc_gdtria_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtria_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtria_types[0] = NPY_FLOAT
+ufunc_gdtria_types[1] = NPY_FLOAT
+ufunc_gdtria_types[2] = NPY_FLOAT
+ufunc_gdtria_types[3] = NPY_FLOAT
+ufunc_gdtria_types[4] = NPY_DOUBLE
+ufunc_gdtria_types[5] = NPY_DOUBLE
+ufunc_gdtria_types[6] = NPY_DOUBLE
+ufunc_gdtria_types[7] = NPY_DOUBLE
+ufunc_gdtria_ptr[2*0] = _func_gdtria
+ufunc_gdtria_ptr[2*0+1] = ("gdtria")
+ufunc_gdtria_ptr[2*1] = _func_gdtria
+ufunc_gdtria_ptr[2*1+1] = ("gdtria")
+ufunc_gdtria_data[0] = &ufunc_gdtria_ptr[2*0]
+ufunc_gdtria_data[1] = &ufunc_gdtria_ptr[2*1]
+gdtria = np.PyUFunc_FromFuncAndData(ufunc_gdtria_loops, ufunc_gdtria_data, ufunc_gdtria_types, 2, 3, 1, 0, "gdtria", ufunc_gdtria_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrib_loops[2]
+cdef void *ufunc_gdtrib_ptr[4]
+cdef void *ufunc_gdtrib_data[2]
+cdef char ufunc_gdtrib_types[8]
+cdef char *ufunc_gdtrib_doc = (
+    "gdtrib(a, p, x, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs b.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `b` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    `a` parameter values of ``gdtr(a, b, x)`. ``1/a`` is the \"scale\"\n"
+    "    parameter of the gamma distribution.\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "x : array_like\n"
+    "    Nonnegative real values, from the domain of the gamma distribution.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`.  `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "b : scalar or ndarray\n"
+    "    Values of the `b` parameter such that `p = gdtr(a, b, x)`.  `b` is\n"
+    "    the \"shape\" parameter of the gamma distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtria : Inverse with respect to `a` of `gdtr(a, b, x)`.\n"
+    "gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using the Cephes [1]_\n"
+    "routines `igam` and `igamc`. Computation of `b` involves a search for a value\n"
+    "that produces the desired value of `p` using Chandrupatla's bracketing\n"
+    "root finding algorithm [2]_.\n"
+    "\n"
+    "Note that there are some edge cases where `gdtrib` is extended by taking\n"
+    "limits where they are uniquely defined. In particular\n"
+    "``x == 0`` with ``p > 0`` and ``p == 0`` with ``x > 0``.\n"
+    "For these edge cases, a numerical result will be returned for\n"
+    "``gdtrib(a, p, x)`` even though ``gdtr(a, gdtrib(a, p, x), x)`` is\n"
+    "undefined.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [2] Chandrupatla, Tirupathi R.\n"
+    "       \"A new hybrid quadratic/bisection algorithm for finding the zero of a\n"
+    "       nonlinear function without using derivatives\".\n"
+    "       Advances in Engineering Software, 28(3), 145-149.\n"
+    "       https://doi.org/10.1016/s0965-9978(96)00051-8\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtrib\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtrib(1.2, p, 5.6)\n"
+    "3.3999999999999995")
+ufunc_gdtrib_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrib_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrib_types[0] = NPY_FLOAT
+ufunc_gdtrib_types[1] = NPY_FLOAT
+ufunc_gdtrib_types[2] = NPY_FLOAT
+ufunc_gdtrib_types[3] = NPY_FLOAT
+ufunc_gdtrib_types[4] = NPY_DOUBLE
+ufunc_gdtrib_types[5] = NPY_DOUBLE
+ufunc_gdtrib_types[6] = NPY_DOUBLE
+ufunc_gdtrib_types[7] = NPY_DOUBLE
+ufunc_gdtrib_ptr[2*0] = _func_xsf_gdtrib
+ufunc_gdtrib_ptr[2*0+1] = ("gdtrib")
+ufunc_gdtrib_ptr[2*1] = _func_xsf_gdtrib
+ufunc_gdtrib_ptr[2*1+1] = ("gdtrib")
+ufunc_gdtrib_data[0] = &ufunc_gdtrib_ptr[2*0]
+ufunc_gdtrib_data[1] = &ufunc_gdtrib_ptr[2*1]
+gdtrib = np.PyUFunc_FromFuncAndData(ufunc_gdtrib_loops, ufunc_gdtrib_data, ufunc_gdtrib_types, 2, 3, 1, 0, "gdtrib", ufunc_gdtrib_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrix_loops[2]
+cdef void *ufunc_gdtrix_ptr[4]
+cdef void *ufunc_gdtrix_data[2]
+cdef char ufunc_gdtrix_types[8]
+cdef char *ufunc_gdtrix_doc = (
+    "gdtrix(a, b, p, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs x.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `x` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution. This is also known as the pth quantile of the\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    `a` parameter values of ``gdtr(a, b, x)``. ``1/a`` is the \"scale\"\n"
+    "    parameter of the gamma distribution.\n"
+    "b : array_like\n"
+    "    `b` parameter values of ``gdtr(a, b, x)``. `b` is the \"shape\" parameter\n"
+    "    of the gamma distribution.\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`. `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Values of the `x` parameter such that `p = gdtr(a, b, x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.\n"
+    "gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `x` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `x`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Computation of the incomplete gamma function ratios and their\n"
+    "       inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtrix\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtrix(1.2, 3.4, p)\n"
+    "5.5999999999999996")
+ufunc_gdtrix_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrix_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrix_types[0] = NPY_FLOAT
+ufunc_gdtrix_types[1] = NPY_FLOAT
+ufunc_gdtrix_types[2] = NPY_FLOAT
+ufunc_gdtrix_types[3] = NPY_FLOAT
+ufunc_gdtrix_types[4] = NPY_DOUBLE
+ufunc_gdtrix_types[5] = NPY_DOUBLE
+ufunc_gdtrix_types[6] = NPY_DOUBLE
+ufunc_gdtrix_types[7] = NPY_DOUBLE
+ufunc_gdtrix_ptr[2*0] = _func_gdtrix
+ufunc_gdtrix_ptr[2*0+1] = ("gdtrix")
+ufunc_gdtrix_ptr[2*1] = _func_gdtrix
+ufunc_gdtrix_ptr[2*1+1] = ("gdtrix")
+ufunc_gdtrix_data[0] = &ufunc_gdtrix_ptr[2*0]
+ufunc_gdtrix_data[1] = &ufunc_gdtrix_ptr[2*1]
+gdtrix = np.PyUFunc_FromFuncAndData(ufunc_gdtrix_loops, ufunc_gdtrix_data, ufunc_gdtrix_types, 2, 3, 1, 0, "gdtrix", ufunc_gdtrix_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_huber_loops[2]
+cdef void *ufunc_huber_ptr[4]
+cdef void *ufunc_huber_data[2]
+cdef char ufunc_huber_types[6]
+cdef char *ufunc_huber_doc = (
+    "huber(delta, r, out=None)\n"
+    "\n"
+    "Huber loss function.\n"
+    "\n"
+    ".. math:: \\text{huber}(\\delta, r) = \\begin{cases} \\infty & \\delta < 0  \\\\\n"
+    "          \\frac{1}{2}r^2 & 0 \\le \\delta, | r | \\le \\delta \\\\\n"
+    "          \\delta ( |r| - \\frac{1}{2}\\delta ) & \\text{otherwise} \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "delta : ndarray\n"
+    "    Input array, indicating the quadratic vs. linear loss changepoint.\n"
+    "r : ndarray\n"
+    "    Input array, possibly representing residuals.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The computed Huber loss function values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pseudo_huber : smooth approximation of this function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`huber` is useful as a loss function in robust statistics or machine\n"
+    "learning to reduce the influence of outliers as compared to the common\n"
+    "squared error loss, residuals with a magnitude higher than `delta` are\n"
+    "not squared [1]_.\n"
+    "\n"
+    "Typically, `r` represents residuals, the difference\n"
+    "between a model prediction and data. Then, for :math:`|r|\\leq\\delta`,\n"
+    "`huber` resembles the squared error and for :math:`|r|>\\delta` the\n"
+    "absolute error. This way, the Huber loss often achieves\n"
+    "a fast convergence in model fitting for small residuals like the squared\n"
+    "error loss function and still reduces the influence of outliers\n"
+    "(:math:`|r|>\\delta`) like the absolute error loss. As :math:`\\delta` is\n"
+    "the cutoff between squared and absolute error regimes, it has\n"
+    "to be tuned carefully for each problem. `huber` is also\n"
+    "convex, making it suitable for gradient based optimization.\n"
+    "\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Peter Huber. \"Robust Estimation of a Location Parameter\",\n"
+    "       1964. Annals of Statistics. 53 (1): 73 - 101.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Import all necessary modules.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import huber\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Compute the function for ``delta=1`` at ``r=2``\n"
+    "\n"
+    ">>> huber(1., 2.)\n"
+    "1.5\n"
+    "\n"
+    "Compute the function for different `delta` by providing a NumPy array or\n"
+    "list for `delta`.\n"
+    "\n"
+    ">>> huber([1., 3., 5.], 4.)\n"
+    "array([3.5, 7.5, 8. ])\n"
+    "\n"
+    "Compute the function at different points by providing a NumPy array or\n"
+    "list for `r`.\n"
+    "\n"
+    ">>> huber(2., np.array([1., 1.5, 3.]))\n"
+    "array([0.5  , 1.125, 4.   ])\n"
+    "\n"
+    "The function can be calculated for different `delta` and `r` by\n"
+    "providing arrays for both with compatible shapes for broadcasting.\n"
+    "\n"
+    ">>> r = np.array([1., 2.5, 8., 10.])\n"
+    ">>> deltas = np.array([[1.], [5.], [9.]])\n"
+    ">>> print(r.shape, deltas.shape)\n"
+    "(4,) (3, 1)\n"
+    "\n"
+    ">>> huber(deltas, r)\n"
+    "array([[ 0.5  ,  2.   ,  7.5  ,  9.5  ],\n"
+    "       [ 0.5  ,  3.125, 27.5  , 37.5  ],\n"
+    "       [ 0.5  ,  3.125, 32.   , 49.5  ]])\n"
+    "\n"
+    "Plot the function for different `delta`.\n"
+    "\n"
+    ">>> x = np.linspace(-4, 4, 500)\n"
+    ">>> deltas = [1, 2, 3]\n"
+    ">>> linestyles = [\"dashed\", \"dotted\", \"dashdot\"]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> combined_plot_parameters = list(zip(deltas, linestyles))\n"
+    ">>> for delta, style in combined_plot_parameters:\n"
+    "...     ax.plot(x, huber(delta, x), label=fr\"$\\delta={delta}$\", ls=style)\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(r\"Huber loss function $h_{\\delta}(x)$\")\n"
+    ">>> ax.set_xlim(-4, 4)\n"
+    ">>> ax.set_ylim(0, 8)\n"
+    ">>> plt.show()")
+ufunc_huber_loops[0] = loop_d_dd__As_ff_f
+ufunc_huber_loops[1] = loop_d_dd__As_dd_d
+ufunc_huber_types[0] = NPY_FLOAT
+ufunc_huber_types[1] = NPY_FLOAT
+ufunc_huber_types[2] = NPY_FLOAT
+ufunc_huber_types[3] = NPY_DOUBLE
+ufunc_huber_types[4] = NPY_DOUBLE
+ufunc_huber_types[5] = NPY_DOUBLE
+ufunc_huber_ptr[2*0] = _func_huber
+ufunc_huber_ptr[2*0+1] = ("huber")
+ufunc_huber_ptr[2*1] = _func_huber
+ufunc_huber_ptr[2*1+1] = ("huber")
+ufunc_huber_data[0] = &ufunc_huber_ptr[2*0]
+ufunc_huber_data[1] = &ufunc_huber_ptr[2*1]
+huber = np.PyUFunc_FromFuncAndData(ufunc_huber_loops, ufunc_huber_data, ufunc_huber_types, 2, 2, 1, 0, "huber", ufunc_huber_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyp0f1_loops[4]
+cdef void *ufunc_hyp0f1_ptr[8]
+cdef void *ufunc_hyp0f1_data[4]
+cdef char ufunc_hyp0f1_types[12]
+cdef char *ufunc_hyp0f1_doc = (
+    "hyp0f1(v, z, out=None)\n"
+    "\n"
+    "Confluent hypergeometric limit function 0F1.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Real-valued parameter\n"
+    "z : array_like\n"
+    "    Real- or complex-valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The confluent hypergeometric limit function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function is defined as:\n"
+    "\n"
+    ".. math:: _0F_1(v, z) = \\sum_{k=0}^{\\infty}\\frac{z^k}{(v)_k k!}.\n"
+    "\n"
+    "It's also the limit as :math:`q \\to \\infty` of :math:`_1F_1(q; v; z/q)`,\n"
+    "and satisfies the differential equation :math:`f''(z) + vf'(z) =\n"
+    "f(z)`. See [1]_ for more information.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Wolfram MathWorld, \"Confluent Hypergeometric Limit Function\",\n"
+    "       http://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is one when `z` is zero.\n"
+    "\n"
+    ">>> sc.hyp0f1(1, 0)\n"
+    "1.0\n"
+    "\n"
+    "It is the limit of the confluent hypergeometric function as `q`\n"
+    "goes to infinity.\n"
+    "\n"
+    ">>> q = np.array([1, 10, 100, 1000])\n"
+    ">>> v = 1\n"
+    ">>> z = 1\n"
+    ">>> sc.hyp1f1(q, v, z / q)\n"
+    "array([2.71828183, 2.31481985, 2.28303778, 2.27992985])\n"
+    ">>> sc.hyp0f1(v, z)\n"
+    "2.2795853023360673\n"
+    "\n"
+    "It is related to Bessel functions.\n"
+    "\n"
+    ">>> n = 1\n"
+    ">>> x = np.linspace(0, 1, 5)\n"
+    ">>> sc.jv(n, x)\n"
+    "array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])\n"
+    ">>> (0.5 * x)**n / sc.factorial(n) * sc.hyp0f1(n + 1, -0.25 * x**2)\n"
+    "array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])")
+ufunc_hyp0f1_loops[0] = loop_d_dd__As_ff_f
+ufunc_hyp0f1_loops[1] = loop_D_dD__As_fF_F
+ufunc_hyp0f1_loops[2] = loop_d_dd__As_dd_d
+ufunc_hyp0f1_loops[3] = loop_D_dD__As_dD_D
+ufunc_hyp0f1_types[0] = NPY_FLOAT
+ufunc_hyp0f1_types[1] = NPY_FLOAT
+ufunc_hyp0f1_types[2] = NPY_FLOAT
+ufunc_hyp0f1_types[3] = NPY_FLOAT
+ufunc_hyp0f1_types[4] = NPY_CFLOAT
+ufunc_hyp0f1_types[5] = NPY_CFLOAT
+ufunc_hyp0f1_types[6] = NPY_DOUBLE
+ufunc_hyp0f1_types[7] = NPY_DOUBLE
+ufunc_hyp0f1_types[8] = NPY_DOUBLE
+ufunc_hyp0f1_types[9] = NPY_DOUBLE
+ufunc_hyp0f1_types[10] = NPY_CDOUBLE
+ufunc_hyp0f1_types[11] = NPY_CDOUBLE
+ufunc_hyp0f1_ptr[2*0] = _func__hyp0f1_real
+ufunc_hyp0f1_ptr[2*0+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*1] = _func__hyp0f1_cmplx
+ufunc_hyp0f1_ptr[2*1+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*2] = _func__hyp0f1_real
+ufunc_hyp0f1_ptr[2*2+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*3] = _func__hyp0f1_cmplx
+ufunc_hyp0f1_ptr[2*3+1] = ("hyp0f1")
+ufunc_hyp0f1_data[0] = &ufunc_hyp0f1_ptr[2*0]
+ufunc_hyp0f1_data[1] = &ufunc_hyp0f1_ptr[2*1]
+ufunc_hyp0f1_data[2] = &ufunc_hyp0f1_ptr[2*2]
+ufunc_hyp0f1_data[3] = &ufunc_hyp0f1_ptr[2*3]
+hyp0f1 = np.PyUFunc_FromFuncAndData(ufunc_hyp0f1_loops, ufunc_hyp0f1_data, ufunc_hyp0f1_types, 4, 2, 1, 0, "hyp0f1", ufunc_hyp0f1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyp1f1_loops[4]
+cdef void *ufunc_hyp1f1_ptr[8]
+cdef void *ufunc_hyp1f1_data[4]
+cdef char ufunc_hyp1f1_types[16]
+cdef char *ufunc_hyp1f1_doc = (
+    "hyp1f1(a, b, x, out=None)\n"
+    "\n"
+    "Confluent hypergeometric function 1F1.\n"
+    "\n"
+    "The confluent hypergeometric function is defined by the series\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   {}_1F_1(a; b; x) = \\sum_{k = 0}^\\infty \\frac{(a)_k}{(b)_k k!} x^k.\n"
+    "\n"
+    "See [dlmf]_ for more details. Here :math:`(\\cdot)_k` is the\n"
+    "Pochhammer symbol; see `poch`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real parameters\n"
+    "x : array_like\n"
+    "    Real or complex argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the confluent hypergeometric function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "hyperu : another confluent hypergeometric function\n"
+    "hyp0f1 : confluent hypergeometric limit function\n"
+    "hyp2f1 : Gaussian hypergeometric function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real values, this function uses the ``hyp1f1`` routine from the C++ Boost\n"
+    "library [2]_, for complex values a C translation of the specfun\n"
+    "Fortran library [3]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] NIST Digital Library of Mathematical Functions\n"
+    "          https://dlmf.nist.gov/13.2#E2\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    ".. [3] Zhang, Jin, \"Computation of Special Functions\", John Wiley\n"
+    "       and Sons, Inc, 1996.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is one when `x` is zero:\n"
+    "\n"
+    ">>> sc.hyp1f1(0.5, 0.5, 0)\n"
+    "1.0\n"
+    "\n"
+    "It is singular when `b` is a nonpositive integer.\n"
+    "\n"
+    ">>> sc.hyp1f1(0.5, -1, 0)\n"
+    "inf\n"
+    "\n"
+    "It is a polynomial when `a` is a nonpositive integer.\n"
+    "\n"
+    ">>> a, b, x = -1, 0.5, np.array([1.0, 2.0, 3.0, 4.0])\n"
+    ">>> sc.hyp1f1(a, b, x)\n"
+    "array([-1., -3., -5., -7.])\n"
+    ">>> 1 + (a / b) * x\n"
+    "array([-1., -3., -5., -7.])\n"
+    "\n"
+    "It reduces to the exponential function when ``a = b``.\n"
+    "\n"
+    ">>> sc.hyp1f1(2, 2, [1, 2, 3, 4])\n"
+    "array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])\n"
+    ">>> np.exp([1, 2, 3, 4])\n"
+    "array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])")
+ufunc_hyp1f1_loops[0] = loop_d_ddd__As_fff_f
+ufunc_hyp1f1_loops[1] = loop_D_ddD__As_ffF_F
+ufunc_hyp1f1_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_hyp1f1_loops[3] = loop_D_ddD__As_ddD_D
+ufunc_hyp1f1_types[0] = NPY_FLOAT
+ufunc_hyp1f1_types[1] = NPY_FLOAT
+ufunc_hyp1f1_types[2] = NPY_FLOAT
+ufunc_hyp1f1_types[3] = NPY_FLOAT
+ufunc_hyp1f1_types[4] = NPY_FLOAT
+ufunc_hyp1f1_types[5] = NPY_FLOAT
+ufunc_hyp1f1_types[6] = NPY_CFLOAT
+ufunc_hyp1f1_types[7] = NPY_CFLOAT
+ufunc_hyp1f1_types[8] = NPY_DOUBLE
+ufunc_hyp1f1_types[9] = NPY_DOUBLE
+ufunc_hyp1f1_types[10] = NPY_DOUBLE
+ufunc_hyp1f1_types[11] = NPY_DOUBLE
+ufunc_hyp1f1_types[12] = NPY_DOUBLE
+ufunc_hyp1f1_types[13] = NPY_DOUBLE
+ufunc_hyp1f1_types[14] = NPY_CDOUBLE
+ufunc_hyp1f1_types[15] = NPY_CDOUBLE
+ufunc_hyp1f1_ptr[2*0] = scipy.special._ufuncs_cxx._export_hyp1f1_double
+ufunc_hyp1f1_ptr[2*0+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*1] = _func_chyp1f1_wrap
+ufunc_hyp1f1_ptr[2*1+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*2] = scipy.special._ufuncs_cxx._export_hyp1f1_double
+ufunc_hyp1f1_ptr[2*2+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*3] = _func_chyp1f1_wrap
+ufunc_hyp1f1_ptr[2*3+1] = ("hyp1f1")
+ufunc_hyp1f1_data[0] = &ufunc_hyp1f1_ptr[2*0]
+ufunc_hyp1f1_data[1] = &ufunc_hyp1f1_ptr[2*1]
+ufunc_hyp1f1_data[2] = &ufunc_hyp1f1_ptr[2*2]
+ufunc_hyp1f1_data[3] = &ufunc_hyp1f1_ptr[2*3]
+hyp1f1 = np.PyUFunc_FromFuncAndData(ufunc_hyp1f1_loops, ufunc_hyp1f1_data, ufunc_hyp1f1_types, 4, 3, 1, 0, "hyp1f1", ufunc_hyp1f1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyperu_loops[2]
+cdef void *ufunc_hyperu_ptr[4]
+cdef void *ufunc_hyperu_data[2]
+cdef char ufunc_hyperu_types[8]
+cdef char *ufunc_hyperu_doc = (
+    "hyperu(a, b, x, out=None)\n"
+    "\n"
+    "Confluent hypergeometric function U\n"
+    "\n"
+    "It is defined as the solution to the equation\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   x \\frac{d^2w}{dx^2} + (b - x) \\frac{dw}{dx} - aw = 0\n"
+    "\n"
+    "which satisfies the property\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   U(a, b, x) \\sim x^{-a}\n"
+    "\n"
+    "as :math:`x \\to \\infty`. See [dlmf]_ for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of `U`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] NIST Digital Library of Mathematics Functions\n"
+    "          https://dlmf.nist.gov/13.2#E6\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It has a branch cut along the negative `x` axis.\n"
+    "\n"
+    ">>> x = np.linspace(-0.1, -10, 5)\n"
+    ">>> sc.hyperu(1, 1, x)\n"
+    "array([nan, nan, nan, nan, nan])\n"
+    "\n"
+    "It approaches zero as `x` goes to infinity.\n"
+    "\n"
+    ">>> x = np.array([1, 10, 100])\n"
+    ">>> sc.hyperu(1, 1, x)\n"
+    "array([0.59634736, 0.09156333, 0.00990194])\n"
+    "\n"
+    "It satisfies Kummer's transformation.\n"
+    "\n"
+    ">>> a, b, x = 2, 1, 1\n"
+    ">>> sc.hyperu(a, b, x)\n"
+    "0.1926947246463881\n"
+    ">>> x**(1 - b) * sc.hyperu(a - b + 1, 2 - b, x)\n"
+    "0.1926947246463881")
+ufunc_hyperu_loops[0] = loop_d_ddd__As_fff_f
+ufunc_hyperu_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_hyperu_types[0] = NPY_FLOAT
+ufunc_hyperu_types[1] = NPY_FLOAT
+ufunc_hyperu_types[2] = NPY_FLOAT
+ufunc_hyperu_types[3] = NPY_FLOAT
+ufunc_hyperu_types[4] = NPY_DOUBLE
+ufunc_hyperu_types[5] = NPY_DOUBLE
+ufunc_hyperu_types[6] = NPY_DOUBLE
+ufunc_hyperu_types[7] = NPY_DOUBLE
+ufunc_hyperu_ptr[2*0] = _func_hyperu
+ufunc_hyperu_ptr[2*0+1] = ("hyperu")
+ufunc_hyperu_ptr[2*1] = _func_hyperu
+ufunc_hyperu_ptr[2*1+1] = ("hyperu")
+ufunc_hyperu_data[0] = &ufunc_hyperu_ptr[2*0]
+ufunc_hyperu_data[1] = &ufunc_hyperu_ptr[2*1]
+hyperu = np.PyUFunc_FromFuncAndData(ufunc_hyperu_loops, ufunc_hyperu_data, ufunc_hyperu_types, 2, 3, 1, 0, "hyperu", ufunc_hyperu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_inv_boxcox_loops[2]
+cdef void *ufunc_inv_boxcox_ptr[4]
+cdef void *ufunc_inv_boxcox_data[2]
+cdef char ufunc_inv_boxcox_types[6]
+cdef char *ufunc_inv_boxcox_doc = (
+    "inv_boxcox(y, lmbda, out=None)\n"
+    "\n"
+    "Compute the inverse of the Box-Cox transformation.\n"
+    "\n"
+    "Find ``x`` such that::\n"
+    "\n"
+    "    y = (x**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(x)                  if lmbda == 0\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.16.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox, inv_boxcox\n"
+    ">>> y = boxcox([1, 4, 10], 2.5)\n"
+    ">>> inv_boxcox(y, 2.5)\n"
+    "array([1., 4., 10.])")
+ufunc_inv_boxcox_loops[0] = loop_d_dd__As_ff_f
+ufunc_inv_boxcox_loops[1] = loop_d_dd__As_dd_d
+ufunc_inv_boxcox_types[0] = NPY_FLOAT
+ufunc_inv_boxcox_types[1] = NPY_FLOAT
+ufunc_inv_boxcox_types[2] = NPY_FLOAT
+ufunc_inv_boxcox_types[3] = NPY_DOUBLE
+ufunc_inv_boxcox_types[4] = NPY_DOUBLE
+ufunc_inv_boxcox_types[5] = NPY_DOUBLE
+ufunc_inv_boxcox_ptr[2*0] = _func_inv_boxcox
+ufunc_inv_boxcox_ptr[2*0+1] = ("inv_boxcox")
+ufunc_inv_boxcox_ptr[2*1] = _func_inv_boxcox
+ufunc_inv_boxcox_ptr[2*1+1] = ("inv_boxcox")
+ufunc_inv_boxcox_data[0] = &ufunc_inv_boxcox_ptr[2*0]
+ufunc_inv_boxcox_data[1] = &ufunc_inv_boxcox_ptr[2*1]
+inv_boxcox = np.PyUFunc_FromFuncAndData(ufunc_inv_boxcox_loops, ufunc_inv_boxcox_data, ufunc_inv_boxcox_types, 2, 2, 1, 0, "inv_boxcox", ufunc_inv_boxcox_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_inv_boxcox1p_loops[2]
+cdef void *ufunc_inv_boxcox1p_ptr[4]
+cdef void *ufunc_inv_boxcox1p_data[2]
+cdef char ufunc_inv_boxcox1p_types[6]
+cdef char *ufunc_inv_boxcox1p_doc = (
+    "inv_boxcox1p(y, lmbda, out=None)\n"
+    "\n"
+    "Compute the inverse of the Box-Cox transformation.\n"
+    "\n"
+    "Find ``x`` such that::\n"
+    "\n"
+    "    y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(1+x)                    if lmbda == 0\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.16.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox1p, inv_boxcox1p\n"
+    ">>> y = boxcox1p([1, 4, 10], 2.5)\n"
+    ">>> inv_boxcox1p(y, 2.5)\n"
+    "array([1., 4., 10.])")
+ufunc_inv_boxcox1p_loops[0] = loop_d_dd__As_ff_f
+ufunc_inv_boxcox1p_loops[1] = loop_d_dd__As_dd_d
+ufunc_inv_boxcox1p_types[0] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[1] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[2] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[3] = NPY_DOUBLE
+ufunc_inv_boxcox1p_types[4] = NPY_DOUBLE
+ufunc_inv_boxcox1p_types[5] = NPY_DOUBLE
+ufunc_inv_boxcox1p_ptr[2*0] = _func_inv_boxcox1p
+ufunc_inv_boxcox1p_ptr[2*0+1] = ("inv_boxcox1p")
+ufunc_inv_boxcox1p_ptr[2*1] = _func_inv_boxcox1p
+ufunc_inv_boxcox1p_ptr[2*1+1] = ("inv_boxcox1p")
+ufunc_inv_boxcox1p_data[0] = &ufunc_inv_boxcox1p_ptr[2*0]
+ufunc_inv_boxcox1p_data[1] = &ufunc_inv_boxcox1p_ptr[2*1]
+inv_boxcox1p = np.PyUFunc_FromFuncAndData(ufunc_inv_boxcox1p_loops, ufunc_inv_boxcox1p_data, ufunc_inv_boxcox1p_types, 2, 2, 1, 0, "inv_boxcox1p", ufunc_inv_boxcox1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kl_div_loops[2]
+cdef void *ufunc_kl_div_ptr[4]
+cdef void *ufunc_kl_div_data[2]
+cdef char ufunc_kl_div_types[6]
+cdef char *ufunc_kl_div_doc = (
+    "kl_div(x, y, out=None)\n"
+    "\n"
+    "Elementwise function for computing Kullback-Leibler divergence.\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\mathrm{kl\\_div}(x, y) =\n"
+    "      \\begin{cases}\n"
+    "        x \\log(x / y) - x + y & x > 0, y > 0 \\\\\n"
+    "        y & x = 0, y \\ge 0 \\\\\n"
+    "        \\infty & \\text{otherwise}\n"
+    "      \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Real arguments\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Kullback-Liebler divergence.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "entr, rel_entr, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is non-negative and is jointly convex in `x` and `y`.\n"
+    "\n"
+    "The origin of this function is in convex programming; see [1]_ for\n"
+    "details. This is why the function contains the extra :math:`-x\n"
+    "+ y` terms over what might be expected from the Kullback-Leibler\n"
+    "divergence. For a version of the function without the extra terms,\n"
+    "see `rel_entr`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`")
+ufunc_kl_div_loops[0] = loop_d_dd__As_ff_f
+ufunc_kl_div_loops[1] = loop_d_dd__As_dd_d
+ufunc_kl_div_types[0] = NPY_FLOAT
+ufunc_kl_div_types[1] = NPY_FLOAT
+ufunc_kl_div_types[2] = NPY_FLOAT
+ufunc_kl_div_types[3] = NPY_DOUBLE
+ufunc_kl_div_types[4] = NPY_DOUBLE
+ufunc_kl_div_types[5] = NPY_DOUBLE
+ufunc_kl_div_ptr[2*0] = _func_kl_div
+ufunc_kl_div_ptr[2*0+1] = ("kl_div")
+ufunc_kl_div_ptr[2*1] = _func_kl_div
+ufunc_kl_div_ptr[2*1+1] = ("kl_div")
+ufunc_kl_div_data[0] = &ufunc_kl_div_ptr[2*0]
+ufunc_kl_div_data[1] = &ufunc_kl_div_ptr[2*1]
+kl_div = np.PyUFunc_FromFuncAndData(ufunc_kl_div_loops, ufunc_kl_div_data, ufunc_kl_div_types, 2, 2, 1, 0, "kl_div", ufunc_kl_div_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kn_loops[3]
+cdef void *ufunc_kn_ptr[6]
+cdef void *ufunc_kn_data[3]
+cdef char ufunc_kn_types[9]
+cdef char *ufunc_kn_doc = (
+    "kn(n, x, out=None)\n"
+    "\n"
+    "Modified Bessel function of the second kind of integer order `n`\n"
+    "\n"
+    "Returns the modified Bessel function of the second kind for integer order\n"
+    "`n` at real `z`.\n"
+    "\n"
+    "These are also sometimes called functions of the third kind, Basset\n"
+    "functions, or Macdonald functions.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like of int\n"
+    "    Order of Bessel functions (floats will truncate with a warning)\n"
+    "x : array_like of float\n"
+    "    Argument at which to evaluate the Bessel functions\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Modified Bessel function of the second kind,\n"
+    "    :math:`K_n(x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kv : Same function, but accepts real order and complex argument\n"
+    "kvp : Derivative of this function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the\n"
+    "algorithm used, see [2]_ and the references therein.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Donald E. Amos, \"AMOS, A Portable Package for Bessel Functions\n"
+    "       of a Complex Argument and Nonnegative Order\",\n"
+    "       http://netlib.org/amos/\n"
+    ".. [2] Donald E. Amos, \"Algorithm 644: A portable package for Bessel\n"
+    "       functions of a complex argument and nonnegative order\", ACM\n"
+    "       TOMS Vol. 12 Issue 3, Sept. 1986, p. 265\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Plot the function of several orders for real input:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import kn\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(0, 5, 1000)\n"
+    ">>> for N in range(6):\n"
+    "...     plt.plot(x, kn(N, x), label='$K_{}(x)$'.format(N))\n"
+    ">>> plt.ylim(0, 10)\n"
+    ">>> plt.legend()\n"
+    ">>> plt.title(r'Modified Bessel function of the second kind $K_n(x)$')\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Calculate for a single value at multiple orders:\n"
+    "\n"
+    ">>> kn([4, 5, 6], 1)\n"
+    "array([   44.23241585,   360.9605896 ,  3653.83831186])")
+ufunc_kn_loops[0] = loop_d_pd__As_pd_d
+ufunc_kn_loops[1] = loop_d_dd__As_ff_f
+ufunc_kn_loops[2] = loop_d_dd__As_dd_d
+ufunc_kn_types[0] = NPY_INTP
+ufunc_kn_types[1] = NPY_DOUBLE
+ufunc_kn_types[2] = NPY_DOUBLE
+ufunc_kn_types[3] = NPY_FLOAT
+ufunc_kn_types[4] = NPY_FLOAT
+ufunc_kn_types[5] = NPY_FLOAT
+ufunc_kn_types[6] = NPY_DOUBLE
+ufunc_kn_types[7] = NPY_DOUBLE
+ufunc_kn_types[8] = NPY_DOUBLE
+ufunc_kn_ptr[2*0] = _func_special_cyl_bessel_k_int
+ufunc_kn_ptr[2*0+1] = ("kn")
+ufunc_kn_ptr[2*1] = _func_kn_unsafe
+ufunc_kn_ptr[2*1+1] = ("kn")
+ufunc_kn_ptr[2*2] = _func_kn_unsafe
+ufunc_kn_ptr[2*2+1] = ("kn")
+ufunc_kn_data[0] = &ufunc_kn_ptr[2*0]
+ufunc_kn_data[1] = &ufunc_kn_ptr[2*1]
+ufunc_kn_data[2] = &ufunc_kn_ptr[2*2]
+kn = np.PyUFunc_FromFuncAndData(ufunc_kn_loops, ufunc_kn_data, ufunc_kn_types, 3, 2, 1, 0, "kn", ufunc_kn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kolmogi_loops[2]
+cdef void *ufunc_kolmogi_ptr[4]
+cdef void *ufunc_kolmogi_data[2]
+cdef char ufunc_kolmogi_types[4]
+cdef char *ufunc_kolmogi_doc = (
+    "kolmogi(p, out=None)\n"
+    "\n"
+    "Inverse Survival Function of Kolmogorov distribution\n"
+    "\n"
+    "It is the inverse function to `kolmogorov`.\n"
+    "Returns y such that ``kolmogorov(y) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : float array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of kolmogi(p)\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kolmogorov : The Survival Function for the distribution\n"
+    "scipy.stats.kstwobign : Provides the functionality as a continuous distribution\n"
+    "smirnov, smirnovi : Functions for the one-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`kolmogorov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.kstwobign` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import kolmogi\n"
+    ">>> kolmogi([0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0])\n"
+    "array([        inf,  1.22384787,  1.01918472,  0.82757356,  0.67644769,\n"
+    "        0.57117327,  0.        ])")
+ufunc_kolmogi_loops[0] = loop_d_d__As_f_f
+ufunc_kolmogi_loops[1] = loop_d_d__As_d_d
+ufunc_kolmogi_types[0] = NPY_FLOAT
+ufunc_kolmogi_types[1] = NPY_FLOAT
+ufunc_kolmogi_types[2] = NPY_DOUBLE
+ufunc_kolmogi_types[3] = NPY_DOUBLE
+ufunc_kolmogi_ptr[2*0] = _func_xsf_kolmogi
+ufunc_kolmogi_ptr[2*0+1] = ("kolmogi")
+ufunc_kolmogi_ptr[2*1] = _func_xsf_kolmogi
+ufunc_kolmogi_ptr[2*1+1] = ("kolmogi")
+ufunc_kolmogi_data[0] = &ufunc_kolmogi_ptr[2*0]
+ufunc_kolmogi_data[1] = &ufunc_kolmogi_ptr[2*1]
+kolmogi = np.PyUFunc_FromFuncAndData(ufunc_kolmogi_loops, ufunc_kolmogi_data, ufunc_kolmogi_types, 2, 1, 1, 0, "kolmogi", ufunc_kolmogi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kolmogorov_loops[2]
+cdef void *ufunc_kolmogorov_ptr[4]
+cdef void *ufunc_kolmogorov_data[2]
+cdef char ufunc_kolmogorov_types[4]
+cdef char *ufunc_kolmogorov_doc = (
+    "kolmogorov(y, out=None)\n"
+    "\n"
+    "Complementary cumulative distribution (Survival Function) function of\n"
+    "Kolmogorov distribution.\n"
+    "\n"
+    "Returns the complementary cumulative distribution function of\n"
+    "Kolmogorov's limiting distribution (``D_n*\\sqrt(n)`` as n goes to infinity)\n"
+    "of a two-sided test for equality between an empirical and a theoretical\n"
+    "distribution. It is equal to the (limit as n->infinity of the)\n"
+    "probability that ``sqrt(n) * max absolute deviation > y``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : float array_like\n"
+    "  Absolute deviation between the Empirical CDF (ECDF) and the target CDF,\n"
+    "  multiplied by sqrt(n).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of kolmogorov(y)\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kolmogi : The Inverse Survival Function for the distribution\n"
+    "scipy.stats.kstwobign : Provides the functionality as a continuous distribution\n"
+    "smirnov, smirnovi : Functions for the one-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`kolmogorov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.kstwobign` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Show the probability of a gap at least as big as 0, 0.5 and 1.0.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import kolmogorov\n"
+    ">>> from scipy.stats import kstwobign\n"
+    ">>> kolmogorov([0, 0.5, 1.0])\n"
+    "array([ 1.        ,  0.96394524,  0.26999967])\n"
+    "\n"
+    "Compare a sample of size 1000 drawn from a Laplace(0, 1) distribution against\n"
+    "the target distribution, a Normal(0, 1) distribution.\n"
+    "\n"
+    ">>> from scipy.stats import norm, laplace\n"
+    ">>> rng = np.random.default_rng()\n"
+    ">>> n = 1000\n"
+    ">>> lap01 = laplace(0, 1)\n"
+    ">>> x = np.sort(lap01.rvs(n, random_state=rng))\n"
+    ">>> np.mean(x), np.std(x)\n"
+    "(-0.05841730131499543, 1.3968109101997568)\n"
+    "\n"
+    "Construct the Empirical CDF and the K-S statistic Dn.\n"
+    "\n"
+    ">>> target = norm(0,1)  # Normal mean 0, stddev 1\n"
+    ">>> cdfs = target.cdf(x)\n"
+    ">>> ecdfs = np.arange(n+1, dtype=float)/n\n"
+    ">>> gaps = np.column_stack([cdfs - ecdfs[:n], ecdfs[1:] - cdfs])\n"
+    ">>> Dn = np.max(gaps)\n"
+    ">>> Kn = np.sqrt(n) * Dn\n"
+    ">>> print('Dn=%f, sqrt(n)*Dn=%f' % (Dn, Kn))\n"
+    "Dn=0.043363, sqrt(n)*Dn=1.371265\n"
+    ">>> print(chr(10).join(['For a sample of size n drawn from a N(0, 1) distribution:',\n"
+    "...   ' the approximate Kolmogorov probability that sqrt(n)*Dn>=%f is %f' %\n"
+    "...    (Kn, kolmogorov(Kn)),\n"
+    "...   ' the approximate Kolmogorov probability that sqrt(n)*Dn<=%f is %f' %\n"
+    "...    (Kn, kstwobign.cdf(Kn))]))\n"
+    "For a sample of size n drawn from a N(0, 1) distribution:\n"
+    " the approximate Kolmogorov probability that sqrt(n)*Dn>=1.371265 is 0.046533\n"
+    " the approximate Kolmogorov probability that sqrt(n)*Dn<=1.371265 is 0.953467\n"
+    "\n"
+    "Plot the Empirical CDF against the target N(0, 1) CDF.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> plt.step(np.concatenate([[-3], x]), ecdfs, where='post', label='Empirical CDF')\n"
+    ">>> x3 = np.linspace(-3, 3, 100)\n"
+    ">>> plt.plot(x3, target.cdf(x3), label='CDF for N(0, 1)')\n"
+    ">>> plt.ylim([0, 1]); plt.grid(True); plt.legend();\n"
+    ">>> # Add vertical lines marking Dn+ and Dn-\n"
+    ">>> iminus, iplus = np.argmax(gaps, axis=0)\n"
+    ">>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus],\n"
+    "...            color='r', linestyle='dashed', lw=4)\n"
+    ">>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1],\n"
+    "...            color='r', linestyle='dashed', lw=4)\n"
+    ">>> plt.show()")
+ufunc_kolmogorov_loops[0] = loop_d_d__As_f_f
+ufunc_kolmogorov_loops[1] = loop_d_d__As_d_d
+ufunc_kolmogorov_types[0] = NPY_FLOAT
+ufunc_kolmogorov_types[1] = NPY_FLOAT
+ufunc_kolmogorov_types[2] = NPY_DOUBLE
+ufunc_kolmogorov_types[3] = NPY_DOUBLE
+ufunc_kolmogorov_ptr[2*0] = _func_xsf_kolmogorov
+ufunc_kolmogorov_ptr[2*0+1] = ("kolmogorov")
+ufunc_kolmogorov_ptr[2*1] = _func_xsf_kolmogorov
+ufunc_kolmogorov_ptr[2*1+1] = ("kolmogorov")
+ufunc_kolmogorov_data[0] = &ufunc_kolmogorov_ptr[2*0]
+ufunc_kolmogorov_data[1] = &ufunc_kolmogorov_ptr[2*1]
+kolmogorov = np.PyUFunc_FromFuncAndData(ufunc_kolmogorov_loops, ufunc_kolmogorov_data, ufunc_kolmogorov_types, 2, 1, 1, 0, "kolmogorov", ufunc_kolmogorov_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_log1p_loops[4]
+cdef void *ufunc_log1p_ptr[8]
+cdef void *ufunc_log1p_data[4]
+cdef char ufunc_log1p_types[8]
+cdef char *ufunc_log1p_doc = (
+    "log1p(x, out=None)\n"
+    "\n"
+    "Calculates log(1 + x) for use when `x` is near zero.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of ``log(1 + x)``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "expm1, cosm1\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is more accurate than using ``log(1 + x)`` directly for ``x``\n"
+    "near 0. Note that in the below example ``1 + 1e-17 == 1`` to\n"
+    "double precision.\n"
+    "\n"
+    ">>> sc.log1p(1e-17)\n"
+    "1e-17\n"
+    ">>> np.log(1 + 1e-17)\n"
+    "0.0")
+ufunc_log1p_loops[0] = loop_d_d__As_f_f
+ufunc_log1p_loops[1] = loop_d_d__As_d_d
+ufunc_log1p_loops[2] = loop_D_D__As_F_F
+ufunc_log1p_loops[3] = loop_D_D__As_D_D
+ufunc_log1p_types[0] = NPY_FLOAT
+ufunc_log1p_types[1] = NPY_FLOAT
+ufunc_log1p_types[2] = NPY_DOUBLE
+ufunc_log1p_types[3] = NPY_DOUBLE
+ufunc_log1p_types[4] = NPY_CFLOAT
+ufunc_log1p_types[5] = NPY_CFLOAT
+ufunc_log1p_types[6] = NPY_CDOUBLE
+ufunc_log1p_types[7] = NPY_CDOUBLE
+ufunc_log1p_ptr[2*0] = _func_cephes_log1p
+ufunc_log1p_ptr[2*0+1] = ("log1p")
+ufunc_log1p_ptr[2*1] = _func_cephes_log1p
+ufunc_log1p_ptr[2*1+1] = ("log1p")
+ufunc_log1p_ptr[2*2] = _func_clog1p
+ufunc_log1p_ptr[2*2+1] = ("log1p")
+ufunc_log1p_ptr[2*3] = _func_clog1p
+ufunc_log1p_ptr[2*3+1] = ("log1p")
+ufunc_log1p_data[0] = &ufunc_log1p_ptr[2*0]
+ufunc_log1p_data[1] = &ufunc_log1p_ptr[2*1]
+ufunc_log1p_data[2] = &ufunc_log1p_ptr[2*2]
+ufunc_log1p_data[3] = &ufunc_log1p_ptr[2*3]
+log1p = np.PyUFunc_FromFuncAndData(ufunc_log1p_loops, ufunc_log1p_data, ufunc_log1p_types, 4, 1, 1, 0, "log1p", ufunc_log1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_log_ndtr_loops[4]
+cdef void *ufunc_log_ndtr_ptr[8]
+cdef void *ufunc_log_ndtr_data[4]
+cdef char ufunc_log_ndtr_types[8]
+cdef char *ufunc_log_ndtr_doc = (
+    "log_ndtr(x, out=None)\n"
+    "\n"
+    "Logarithm of Gaussian cumulative distribution function.\n"
+    "\n"
+    "Returns the log of the area under the standard Gaussian probability\n"
+    "density function, integrated from minus infinity to `x`::\n"
+    "\n"
+    "    log(1/sqrt(2*pi) * integral(exp(-t**2 / 2), t=-inf..x))\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like, real or complex\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the log of the normal CDF evaluated at `x`\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf\n"
+    "erfc\n"
+    "scipy.stats.norm\n"
+    "ndtr\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import log_ndtr, ndtr\n"
+    "\n"
+    "The benefit of ``log_ndtr(x)`` over the naive implementation\n"
+    "``np.log(ndtr(x))`` is most evident with moderate to large positive\n"
+    "values of ``x``:\n"
+    "\n"
+    ">>> x = np.array([6, 7, 9, 12, 15, 25])\n"
+    ">>> log_ndtr(x)\n"
+    "array([-9.86587646e-010, -1.27981254e-012, -1.12858841e-019,\n"
+    "       -1.77648211e-033, -3.67096620e-051, -3.05669671e-138])\n"
+    "\n"
+    "The results of the naive calculation for the moderate ``x`` values\n"
+    "have only 5 or 6 correct significant digits. For values of ``x``\n"
+    "greater than approximately 8.3, the naive expression returns 0:\n"
+    "\n"
+    ">>> np.log(ndtr(x))\n"
+    "array([-9.86587701e-10, -1.27986510e-12,  0.00000000e+00,\n"
+    "        0.00000000e+00,  0.00000000e+00,  0.00000000e+00])")
+ufunc_log_ndtr_loops[0] = loop_d_d__As_f_f
+ufunc_log_ndtr_loops[1] = loop_d_d__As_d_d
+ufunc_log_ndtr_loops[2] = loop_D_D__As_F_F
+ufunc_log_ndtr_loops[3] = loop_D_D__As_D_D
+ufunc_log_ndtr_types[0] = NPY_FLOAT
+ufunc_log_ndtr_types[1] = NPY_FLOAT
+ufunc_log_ndtr_types[2] = NPY_DOUBLE
+ufunc_log_ndtr_types[3] = NPY_DOUBLE
+ufunc_log_ndtr_types[4] = NPY_CFLOAT
+ufunc_log_ndtr_types[5] = NPY_CFLOAT
+ufunc_log_ndtr_types[6] = NPY_CDOUBLE
+ufunc_log_ndtr_types[7] = NPY_CDOUBLE
+ufunc_log_ndtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr
+ufunc_log_ndtr_ptr[2*0+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr
+ufunc_log_ndtr_ptr[2*1+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr_complex
+ufunc_log_ndtr_ptr[2*2+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr_complex
+ufunc_log_ndtr_ptr[2*3+1] = ("log_ndtr")
+ufunc_log_ndtr_data[0] = &ufunc_log_ndtr_ptr[2*0]
+ufunc_log_ndtr_data[1] = &ufunc_log_ndtr_ptr[2*1]
+ufunc_log_ndtr_data[2] = &ufunc_log_ndtr_ptr[2*2]
+ufunc_log_ndtr_data[3] = &ufunc_log_ndtr_ptr[2*3]
+log_ndtr = np.PyUFunc_FromFuncAndData(ufunc_log_ndtr_loops, ufunc_log_ndtr_data, ufunc_log_ndtr_types, 4, 1, 1, 0, "log_ndtr", ufunc_log_ndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_lpmv_loops[2]
+cdef void *ufunc_lpmv_ptr[4]
+cdef void *ufunc_lpmv_data[2]
+cdef char ufunc_lpmv_types[8]
+cdef char *ufunc_lpmv_doc = (
+    "lpmv(m, v, x, out=None)\n"
+    "\n"
+    "Associated Legendre function of integer order and real degree.\n"
+    "\n"
+    "Defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_v^m = (-1)^m (1 - x^2)^{m/2} \\frac{d^m}{dx^m} P_v(x)\n"
+    "\n"
+    "where\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_v = \\sum_{k = 0}^\\infty \\frac{(-v)_k (v + 1)_k}{(k!)^2}\n"
+    "            \\left(\\frac{1 - x}{2}\\right)^k\n"
+    "\n"
+    "is the Legendre function of the first kind. Here :math:`(\\cdot)_k`\n"
+    "is the Pochhammer symbol; see `poch`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "m : array_like\n"
+    "    Order (int or float). If passed a float not equal to an\n"
+    "    integer the function returns NaN.\n"
+    "v : array_like\n"
+    "    Degree (float).\n"
+    "x : array_like\n"
+    "    Argument (float). Must have ``|x| <= 1``.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "pmv : scalar or ndarray\n"
+    "    Value of the associated Legendre function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "lpmn : Compute the associated Legendre function for all orders\n"
+    "       ``0, ..., m`` and degrees ``0, ..., n``.\n"
+    "clpmn : Compute the associated Legendre function at complex\n"
+    "        arguments.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Note that this implementation includes the Condon-Shortley phase.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Zhang, Jin, \"Computation of Special Functions\", John Wiley\n"
+    "       and Sons, Inc, 1996.")
+ufunc_lpmv_loops[0] = loop_d_ddd__As_fff_f
+ufunc_lpmv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_lpmv_types[0] = NPY_FLOAT
+ufunc_lpmv_types[1] = NPY_FLOAT
+ufunc_lpmv_types[2] = NPY_FLOAT
+ufunc_lpmv_types[3] = NPY_FLOAT
+ufunc_lpmv_types[4] = NPY_DOUBLE
+ufunc_lpmv_types[5] = NPY_DOUBLE
+ufunc_lpmv_types[6] = NPY_DOUBLE
+ufunc_lpmv_types[7] = NPY_DOUBLE
+ufunc_lpmv_ptr[2*0] = _func_pmv_wrap
+ufunc_lpmv_ptr[2*0+1] = ("lpmv")
+ufunc_lpmv_ptr[2*1] = _func_pmv_wrap
+ufunc_lpmv_ptr[2*1+1] = ("lpmv")
+ufunc_lpmv_data[0] = &ufunc_lpmv_ptr[2*0]
+ufunc_lpmv_data[1] = &ufunc_lpmv_ptr[2*1]
+lpmv = np.PyUFunc_FromFuncAndData(ufunc_lpmv_loops, ufunc_lpmv_data, ufunc_lpmv_types, 2, 3, 1, 0, "lpmv", ufunc_lpmv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtr_loops[3]
+cdef void *ufunc_nbdtr_ptr[6]
+cdef void *ufunc_nbdtr_data[3]
+cdef char ufunc_nbdtr_types[12]
+cdef char *ufunc_nbdtr_doc = (
+    "nbdtr(k, n, p, out=None)\n"
+    "\n"
+    "Negative binomial cumulative distribution function.\n"
+    "\n"
+    "Returns the sum of the terms 0 through `k` of the negative binomial\n"
+    "distribution probability mass function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\sum_{j=0}^k {{n + j - 1}\\choose{j}} p^n (1 - p)^j.\n"
+    "\n"
+    "In a sequence of Bernoulli trials with individual success probabilities\n"
+    "`p`, this is the probability that `k` or fewer failures precede the nth\n"
+    "success.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The probability of `k` or fewer failures before `n` successes in a\n"
+    "    sequence of events with individual success probability `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtrc : Negative binomial survival function\n"
+    "nbdtrik : Negative binomial quantile function\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "If floating point values are passed for `k` or `n`, they will be truncated\n"
+    "to integers.\n"
+    "\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{nbdtr}(k, n, p) = I_{p}(n, k + 1).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtr`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtr` directly can improve performance\n"
+    "compared to the ``cdf`` method of `scipy.stats.nbinom` (see last example).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtr\n"
+    ">>> nbdtr(10, 5, 0.5)\n"
+    "0.940765380859375\n"
+    "\n"
+    "Compute the function for ``n=10`` and ``p=0.5`` at several points by\n"
+    "providing a NumPy array or list for `k`.\n"
+    "\n"
+    ">>> nbdtr([5, 10, 15], 10, 0.5)\n"
+    "array([0.15087891, 0.58809853, 0.88523853])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> k = np.arange(130)\n"
+    ">>> n_parameters = [20, 20, 20, 80]\n"
+    ">>> p_parameters = [0.2, 0.5, 0.8, 0.5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtr_vals = nbdtr(k, n, p)\n"
+    "...     ax.plot(k, nbdtr_vals, label=rf\"$n={n},\\, p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$k$\")\n"
+    ">>> ax.set_title(\"Negative binomial cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtr` directly can be much faster than\n"
+    "calling the ``cdf`` method of `scipy.stats.nbinom`, especially for small\n"
+    "arrays or individual values. To get the same results one must use the\n"
+    "following parametrization: ``nbinom(n, p).cdf(k)=nbdtr(k, n, p)``.\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> k, n, p = 5, 3, 0.5\n"
+    ">>> nbdtr_res = nbdtr(k, n, p)  # this will often be faster than below\n"
+    ">>> stats_res = nbinom(n, p).cdf(k)\n"
+    ">>> stats_res, nbdtr_res  # test that results are equal\n"
+    "(0.85546875, 0.85546875)\n"
+    "\n"
+    "`nbdtr` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> p = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtr(k, 5, p)\n"
+    "array([[0.15026833, 0.62304687, 0.95265101, 0.9998531 ],\n"
+    "       [0.48450894, 0.94076538, 0.99932777, 0.99999999],\n"
+    "       [0.76249222, 0.99409103, 0.99999445, 1.        ]])")
+ufunc_nbdtr_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtr_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtr_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtr_types[0] = NPY_INTP
+ufunc_nbdtr_types[1] = NPY_INTP
+ufunc_nbdtr_types[2] = NPY_DOUBLE
+ufunc_nbdtr_types[3] = NPY_DOUBLE
+ufunc_nbdtr_types[4] = NPY_FLOAT
+ufunc_nbdtr_types[5] = NPY_FLOAT
+ufunc_nbdtr_types[6] = NPY_FLOAT
+ufunc_nbdtr_types[7] = NPY_FLOAT
+ufunc_nbdtr_types[8] = NPY_DOUBLE
+ufunc_nbdtr_types[9] = NPY_DOUBLE
+ufunc_nbdtr_types[10] = NPY_DOUBLE
+ufunc_nbdtr_types[11] = NPY_DOUBLE
+ufunc_nbdtr_ptr[2*0] = _func_cephes_nbdtr_wrap
+ufunc_nbdtr_ptr[2*0+1] = ("nbdtr")
+ufunc_nbdtr_ptr[2*1] = _func_nbdtr_unsafe
+ufunc_nbdtr_ptr[2*1+1] = ("nbdtr")
+ufunc_nbdtr_ptr[2*2] = _func_nbdtr_unsafe
+ufunc_nbdtr_ptr[2*2+1] = ("nbdtr")
+ufunc_nbdtr_data[0] = &ufunc_nbdtr_ptr[2*0]
+ufunc_nbdtr_data[1] = &ufunc_nbdtr_ptr[2*1]
+ufunc_nbdtr_data[2] = &ufunc_nbdtr_ptr[2*2]
+nbdtr = np.PyUFunc_FromFuncAndData(ufunc_nbdtr_loops, ufunc_nbdtr_data, ufunc_nbdtr_types, 3, 3, 1, 0, "nbdtr", ufunc_nbdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrc_loops[3]
+cdef void *ufunc_nbdtrc_ptr[6]
+cdef void *ufunc_nbdtrc_data[3]
+cdef char ufunc_nbdtrc_types[12]
+cdef char *ufunc_nbdtrc_doc = (
+    "nbdtrc(k, n, p, out=None)\n"
+    "\n"
+    "Negative binomial survival function.\n"
+    "\n"
+    "Returns the sum of the terms `k + 1` to infinity of the negative binomial\n"
+    "distribution probability mass function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\sum_{j=k + 1}^\\infty {{n + j - 1}\\choose{j}} p^n (1 - p)^j.\n"
+    "\n"
+    "In a sequence of Bernoulli trials with individual success probabilities\n"
+    "`p`, this is the probability that more than `k` failures precede the nth\n"
+    "success.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The probability of `k + 1` or more failures before `n` successes in a\n"
+    "    sequence of events with individual success probability `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Negative binomial cumulative distribution function\n"
+    "nbdtrik : Negative binomial percentile function\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "If floating point values are passed for `k` or `n`, they will be truncated\n"
+    "to integers.\n"
+    "\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{nbdtrc}(k, n, p) = I_{1 - p}(k + 1, n).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtrc`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtrc` directly can improve performance\n"
+    "compared to the ``sf`` method of `scipy.stats.nbinom` (see last example).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtrc\n"
+    ">>> nbdtrc(10, 5, 0.5)\n"
+    "0.059234619140624986\n"
+    "\n"
+    "Compute the function for ``n=10`` and ``p=0.5`` at several points by\n"
+    "providing a NumPy array or list for `k`.\n"
+    "\n"
+    ">>> nbdtrc([5, 10, 15], 10, 0.5)\n"
+    "array([0.84912109, 0.41190147, 0.11476147])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> k = np.arange(130)\n"
+    ">>> n_parameters = [20, 20, 20, 80]\n"
+    ">>> p_parameters = [0.2, 0.5, 0.8, 0.5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtrc_vals = nbdtrc(k, n, p)\n"
+    "...     ax.plot(k, nbdtrc_vals, label=rf\"$n={n},\\, p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$k$\")\n"
+    ">>> ax.set_title(\"Negative binomial distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtrc` directly can be much faster than\n"
+    "calling the ``sf`` method of `scipy.stats.nbinom`, especially for small\n"
+    "arrays or individual values. To get the same results one must use the\n"
+    "following parametrization: ``nbinom(n, p).sf(k)=nbdtrc(k, n, p)``.\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> k, n, p = 3, 5, 0.5\n"
+    ">>> nbdtr_res = nbdtrc(k, n, p)  # this will often be faster than below\n"
+    ">>> stats_res = nbinom(n, p).sf(k)\n"
+    ">>> stats_res, nbdtr_res  # test that results are equal\n"
+    "(0.6367187499999999, 0.6367187499999999)\n"
+    "\n"
+    "`nbdtrc` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> p = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtrc(k, 5, p)\n"
+    "array([[8.49731667e-01, 3.76953125e-01, 4.73489874e-02, 1.46902600e-04],\n"
+    "       [5.15491059e-01, 5.92346191e-02, 6.72234070e-04, 9.29610100e-09],\n"
+    "       [2.37507779e-01, 5.90896606e-03, 5.55025308e-06, 3.26346760e-13]])")
+ufunc_nbdtrc_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtrc_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtrc_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrc_types[0] = NPY_INTP
+ufunc_nbdtrc_types[1] = NPY_INTP
+ufunc_nbdtrc_types[2] = NPY_DOUBLE
+ufunc_nbdtrc_types[3] = NPY_DOUBLE
+ufunc_nbdtrc_types[4] = NPY_FLOAT
+ufunc_nbdtrc_types[5] = NPY_FLOAT
+ufunc_nbdtrc_types[6] = NPY_FLOAT
+ufunc_nbdtrc_types[7] = NPY_FLOAT
+ufunc_nbdtrc_types[8] = NPY_DOUBLE
+ufunc_nbdtrc_types[9] = NPY_DOUBLE
+ufunc_nbdtrc_types[10] = NPY_DOUBLE
+ufunc_nbdtrc_types[11] = NPY_DOUBLE
+ufunc_nbdtrc_ptr[2*0] = _func_cephes_nbdtrc_wrap
+ufunc_nbdtrc_ptr[2*0+1] = ("nbdtrc")
+ufunc_nbdtrc_ptr[2*1] = _func_nbdtrc_unsafe
+ufunc_nbdtrc_ptr[2*1+1] = ("nbdtrc")
+ufunc_nbdtrc_ptr[2*2] = _func_nbdtrc_unsafe
+ufunc_nbdtrc_ptr[2*2+1] = ("nbdtrc")
+ufunc_nbdtrc_data[0] = &ufunc_nbdtrc_ptr[2*0]
+ufunc_nbdtrc_data[1] = &ufunc_nbdtrc_ptr[2*1]
+ufunc_nbdtrc_data[2] = &ufunc_nbdtrc_ptr[2*2]
+nbdtrc = np.PyUFunc_FromFuncAndData(ufunc_nbdtrc_loops, ufunc_nbdtrc_data, ufunc_nbdtrc_types, 3, 3, 1, 0, "nbdtrc", ufunc_nbdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtri_loops[3]
+cdef void *ufunc_nbdtri_ptr[6]
+cdef void *ufunc_nbdtri_data[3]
+cdef char ufunc_nbdtri_types[12]
+cdef char *ufunc_nbdtri_doc = (
+    "nbdtri(k, n, y, out=None)\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `p` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "p : scalar or ndarray\n"
+    "    Probability of success in a single event (float) such that\n"
+    "    `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtrc : Negative binomial survival function.\n"
+    "scipy.stats.nbinom : negative binomial distribution.\n"
+    "nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.\n"
+    "nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtri`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtri` directly can improve performance\n"
+    "compared to the ``ppf`` method of `scipy.stats.nbinom`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nbdtri` is the inverse of `nbdtr` with respect to `p`.\n"
+    "Up to floating point errors the following holds:\n"
+    "``nbdtri(k, n, nbdtr(k, n, p))=p``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtri, nbdtr\n"
+    ">>> k, n, y = 5, 10, 0.2\n"
+    ">>> cdf_val = nbdtr(k, n, y)\n"
+    ">>> nbdtri(k, n, cdf_val)\n"
+    "0.20000000000000004\n"
+    "\n"
+    "Compute the function for ``k=10`` and ``n=5`` at several points by\n"
+    "providing a NumPy array or list for `y`.\n"
+    "\n"
+    ">>> y = np.array([0.1, 0.4, 0.8])\n"
+    ">>> nbdtri(3, 5, y)\n"
+    "array([0.34462319, 0.51653095, 0.69677416])\n"
+    "\n"
+    "Plot the function for three different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> n_parameters = [5, 20, 30, 30]\n"
+    ">>> k_parameters = [20, 20, 60, 80]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(n_parameters, k_parameters, linestyles))\n"
+    ">>> cdf_vals = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     n, k, style = parameter_set\n"
+    "...     nbdtri_vals = nbdtri(k, n, cdf_vals)\n"
+    "...     ax.plot(cdf_vals, nbdtri_vals, label=rf\"$k={k},\\ n={n}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylabel(\"$p$\")\n"
+    ">>> ax.set_xlabel(\"$CDF$\")\n"
+    ">>> title = \"nbdtri: inverse of negative binomial CDF with respect to $p$\"\n"
+    ">>> ax.set_title(title)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "`nbdtri` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> y = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, y.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtri(k, 5, y)\n"
+    "array([[0.37258157, 0.45169416, 0.53249956, 0.64578407],\n"
+    "       [0.24588501, 0.30451981, 0.36778453, 0.46397088],\n"
+    "       [0.18362101, 0.22966758, 0.28054743, 0.36066188]])")
+ufunc_nbdtri_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtri_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtri_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtri_types[0] = NPY_INTP
+ufunc_nbdtri_types[1] = NPY_INTP
+ufunc_nbdtri_types[2] = NPY_DOUBLE
+ufunc_nbdtri_types[3] = NPY_DOUBLE
+ufunc_nbdtri_types[4] = NPY_FLOAT
+ufunc_nbdtri_types[5] = NPY_FLOAT
+ufunc_nbdtri_types[6] = NPY_FLOAT
+ufunc_nbdtri_types[7] = NPY_FLOAT
+ufunc_nbdtri_types[8] = NPY_DOUBLE
+ufunc_nbdtri_types[9] = NPY_DOUBLE
+ufunc_nbdtri_types[10] = NPY_DOUBLE
+ufunc_nbdtri_types[11] = NPY_DOUBLE
+ufunc_nbdtri_ptr[2*0] = _func_cephes_nbdtri_wrap
+ufunc_nbdtri_ptr[2*0+1] = ("nbdtri")
+ufunc_nbdtri_ptr[2*1] = _func_nbdtri_unsafe
+ufunc_nbdtri_ptr[2*1+1] = ("nbdtri")
+ufunc_nbdtri_ptr[2*2] = _func_nbdtri_unsafe
+ufunc_nbdtri_ptr[2*2+1] = ("nbdtri")
+ufunc_nbdtri_data[0] = &ufunc_nbdtri_ptr[2*0]
+ufunc_nbdtri_data[1] = &ufunc_nbdtri_ptr[2*1]
+ufunc_nbdtri_data[2] = &ufunc_nbdtri_ptr[2*2]
+nbdtri = np.PyUFunc_FromFuncAndData(ufunc_nbdtri_loops, ufunc_nbdtri_data, ufunc_nbdtri_types, 3, 3, 1, 0, "nbdtri", ufunc_nbdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrik_loops[2]
+cdef void *ufunc_nbdtrik_ptr[4]
+cdef void *ufunc_nbdtrik_data[2]
+cdef char ufunc_nbdtrik_types[8]
+cdef char *ufunc_nbdtrik_doc = (
+    "nbdtrik(y, n, p, out=None)\n"
+    "\n"
+    "Negative binomial percentile function.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `k` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "k : scalar or ndarray\n"
+    "    The maximum number of allowed failures such that `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtrc : Survival function of the negative binomial.\n"
+    "nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.\n"
+    "nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.\n"
+    "\n"
+    "Formula 26.5.26 of [2]_,\n"
+    "\n"
+    ".. math::\n"
+    "    \\sum_{j=k + 1}^\\infty {{n + j - 1}\n"
+    "    \\choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),\n"
+    "\n"
+    "is used to reduce calculation of the cumulative distribution function to\n"
+    "that of a regularized incomplete beta :math:`I`.\n"
+    "\n"
+    "Computation of `k` involves a search for a value that produces the desired\n"
+    "value of `y`.  The search relies on the monotonicity of `y` with `k`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the negative binomial cumulative distribution function for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtr, nbdtrik\n"
+    ">>> k, n, p = 5, 2, 0.5\n"
+    ">>> cdf_value = nbdtr(k, n, p)\n"
+    ">>> cdf_value\n"
+    "0.9375\n"
+    "\n"
+    "Verify that `nbdtrik` recovers the original value for `k`.\n"
+    "\n"
+    ">>> nbdtrik(cdf_value, n, p)\n"
+    "5.0\n"
+    "\n"
+    "Plot the function for different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> p_parameters = [0.2, 0.5, 0.7, 0.5]\n"
+    ">>> n_parameters = [30, 30, 30, 80]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters, linestyles))\n"
+    ">>> cdf_vals = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtrik_vals = nbdtrik(cdf_vals, n, p)\n"
+    "...     ax.plot(cdf_vals, nbdtrik_vals, label=rf\"$n={n},\\ p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylabel(\"$k$\")\n"
+    ">>> ax.set_xlabel(\"$CDF$\")\n"
+    ">>> ax.set_title(\"Negative binomial percentile function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. The percentile function  method ``ppf``\n"
+    "returns the result of `nbdtrik` rounded up to integers:\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> q, n, p = 0.6, 5, 0.5\n"
+    ">>> nbinom.ppf(q, n, p), nbdtrik(q, n, p)\n"
+    "(5.0, 4.800428460273882)")
+ufunc_nbdtrik_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nbdtrik_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrik_types[0] = NPY_FLOAT
+ufunc_nbdtrik_types[1] = NPY_FLOAT
+ufunc_nbdtrik_types[2] = NPY_FLOAT
+ufunc_nbdtrik_types[3] = NPY_FLOAT
+ufunc_nbdtrik_types[4] = NPY_DOUBLE
+ufunc_nbdtrik_types[5] = NPY_DOUBLE
+ufunc_nbdtrik_types[6] = NPY_DOUBLE
+ufunc_nbdtrik_types[7] = NPY_DOUBLE
+ufunc_nbdtrik_ptr[2*0] = _func_nbdtrik
+ufunc_nbdtrik_ptr[2*0+1] = ("nbdtrik")
+ufunc_nbdtrik_ptr[2*1] = _func_nbdtrik
+ufunc_nbdtrik_ptr[2*1+1] = ("nbdtrik")
+ufunc_nbdtrik_data[0] = &ufunc_nbdtrik_ptr[2*0]
+ufunc_nbdtrik_data[1] = &ufunc_nbdtrik_ptr[2*1]
+nbdtrik = np.PyUFunc_FromFuncAndData(ufunc_nbdtrik_loops, ufunc_nbdtrik_data, ufunc_nbdtrik_types, 2, 3, 1, 0, "nbdtrik", ufunc_nbdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrin_loops[2]
+cdef void *ufunc_nbdtrin_ptr[4]
+cdef void *ufunc_nbdtrin_data[2]
+cdef char ufunc_nbdtrin_types[8]
+cdef char *ufunc_nbdtrin_doc = (
+    "nbdtrin(k, y, p, out=None)\n"
+    "\n"
+    "Inverse of `nbdtr` vs `n`.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `n` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "n : scalar or ndarray\n"
+    "    The number of successes `n` such that `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.\n"
+    "nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.\n"
+    "\n"
+    "Formula 26.5.26 of [2]_,\n"
+    "\n"
+    ".. math::\n"
+    "    \\sum_{j=k + 1}^\\infty {{n + j - 1}\n"
+    "    \\choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),\n"
+    "\n"
+    "is used to reduce calculation of the cumulative distribution function to\n"
+    "that of a regularized incomplete beta :math:`I`.\n"
+    "\n"
+    "Computation of `n` involves a search for a value that produces the desired\n"
+    "value of `y`.  The search relies on the monotonicity of `y` with `n`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the negative binomial cumulative distribution function for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.special import nbdtr, nbdtrin\n"
+    ">>> k, n, p = 5, 2, 0.5\n"
+    ">>> cdf_value = nbdtr(k, n, p)\n"
+    ">>> cdf_value\n"
+    "0.9375\n"
+    "\n"
+    "Verify that `nbdtrin` recovers the original value for `n` up to floating\n"
+    "point accuracy.\n"
+    "\n"
+    ">>> nbdtrin(k, cdf_value, p)\n"
+    "1.999999999998137")
+ufunc_nbdtrin_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nbdtrin_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrin_types[0] = NPY_FLOAT
+ufunc_nbdtrin_types[1] = NPY_FLOAT
+ufunc_nbdtrin_types[2] = NPY_FLOAT
+ufunc_nbdtrin_types[3] = NPY_FLOAT
+ufunc_nbdtrin_types[4] = NPY_DOUBLE
+ufunc_nbdtrin_types[5] = NPY_DOUBLE
+ufunc_nbdtrin_types[6] = NPY_DOUBLE
+ufunc_nbdtrin_types[7] = NPY_DOUBLE
+ufunc_nbdtrin_ptr[2*0] = _func_nbdtrin
+ufunc_nbdtrin_ptr[2*0+1] = ("nbdtrin")
+ufunc_nbdtrin_ptr[2*1] = _func_nbdtrin
+ufunc_nbdtrin_ptr[2*1+1] = ("nbdtrin")
+ufunc_nbdtrin_data[0] = &ufunc_nbdtrin_ptr[2*0]
+ufunc_nbdtrin_data[1] = &ufunc_nbdtrin_ptr[2*1]
+nbdtrin = np.PyUFunc_FromFuncAndData(ufunc_nbdtrin_loops, ufunc_nbdtrin_data, ufunc_nbdtrin_types, 2, 3, 1, 0, "nbdtrin", ufunc_nbdtrin_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtr_loops[2]
+cdef void *ufunc_ncfdtr_ptr[4]
+cdef void *ufunc_ncfdtr_data[2]
+cdef char ufunc_ncfdtr_types[10]
+cdef char *ufunc_ncfdtr_doc = (
+    "ncfdtr(dfn, dfd, nc, f, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the non-central F distribution.\n"
+    "\n"
+    "The non-central F describes the distribution of,\n"
+    "\n"
+    ".. math::\n"
+    "    Z = \\frac{X/d_n}{Y/d_d}\n"
+    "\n"
+    "where :math:`X` and :math:`Y` are independently distributed, with\n"
+    ":math:`X` distributed non-central :math:`\\chi^2` with noncentrality\n"
+    "parameter `nc` and :math:`d_n` degrees of freedom, and :math:`Y`\n"
+    "distributed :math:`\\chi^2` with :math:`d_d` degrees of freedom.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares.  Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Range [0, inf).\n"
+    "f : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    The calculated CDF.  If all inputs are scalar, the return will be a\n"
+    "    float.  Otherwise it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "scipy.stats.ncf : Non-central F distribution.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the CDF of the non-central f distribution using\n"
+    "the Boost Math C++ library [1]_.\n"
+    "\n"
+    "The cumulative distribution function is computed using Formula 26.6.20 of\n"
+    "[2]_:\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d, n_c, f) = \\sum_{j=0}^\\infty e^{-n_c/2}\n"
+    "    \\frac{(n_c/2)^j}{j!} I_{x}(\\frac{d_n}{2} + j, \\frac{d_d}{2}),\n"
+    "\n"
+    "where :math:`I` is the regularized incomplete beta function, and\n"
+    ":math:`x = f d_n/(f d_n + d_d)`.\n"
+    "\n"
+    "Note that argument order of `ncfdtr` is different from that of the\n"
+    "similar ``cdf`` method of `scipy.stats.ncf`: `f` is the last\n"
+    "parameter of `ncfdtr` but the first parameter of ``scipy.stats.ncf.cdf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> from scipy import stats\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Plot the CDF of the non-central F distribution, for nc=0.  Compare with the\n"
+    "F-distribution from scipy.stats:\n"
+    "\n"
+    ">>> x = np.linspace(-1, 8, num=500)\n"
+    ">>> dfn = 3\n"
+    ">>> dfd = 2\n"
+    ">>> ncf_stats = stats.f.cdf(x, dfn, dfd)\n"
+    ">>> ncf_special = special.ncfdtr(dfn, dfd, 0, x)\n"
+    "\n"
+    ">>> fig = plt.figure()\n"
+    ">>> ax = fig.add_subplot(111)\n"
+    ">>> ax.plot(x, ncf_stats, 'b-', lw=3)\n"
+    ">>> ax.plot(x, ncf_special, 'r-')\n"
+    ">>> plt.show()")
+ufunc_ncfdtr_loops[0] = loop_f_ffff__As_ffff_f
+ufunc_ncfdtr_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtr_types[0] = NPY_FLOAT
+ufunc_ncfdtr_types[1] = NPY_FLOAT
+ufunc_ncfdtr_types[2] = NPY_FLOAT
+ufunc_ncfdtr_types[3] = NPY_FLOAT
+ufunc_ncfdtr_types[4] = NPY_FLOAT
+ufunc_ncfdtr_types[5] = NPY_DOUBLE
+ufunc_ncfdtr_types[6] = NPY_DOUBLE
+ufunc_ncfdtr_types[7] = NPY_DOUBLE
+ufunc_ncfdtr_types[8] = NPY_DOUBLE
+ufunc_ncfdtr_types[9] = NPY_DOUBLE
+ufunc_ncfdtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_cdf_float
+ufunc_ncfdtr_ptr[2*0+1] = ("ncfdtr")
+ufunc_ncfdtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_cdf_double
+ufunc_ncfdtr_ptr[2*1+1] = ("ncfdtr")
+ufunc_ncfdtr_data[0] = &ufunc_ncfdtr_ptr[2*0]
+ufunc_ncfdtr_data[1] = &ufunc_ncfdtr_ptr[2*1]
+ncfdtr = np.PyUFunc_FromFuncAndData(ufunc_ncfdtr_loops, ufunc_ncfdtr_data, ufunc_ncfdtr_types, 2, 4, 1, 0, "ncfdtr", ufunc_ncfdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtri_loops[2]
+cdef void *ufunc_ncfdtri_ptr[4]
+cdef void *ufunc_ncfdtri_data[2]
+cdef char ufunc_ncfdtri_types[10]
+cdef char *ufunc_ncfdtri_doc = (
+    "ncfdtri(dfn, dfd, nc, p, out=None)\n"
+    "\n"
+    "Inverse with respect to `f` of the CDF of the non-central F distribution.\n"
+    "\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares.  Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Range [0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function.  Must be in the\n"
+    "    range [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "f : scalar or ndarray\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "scipy.stats.ncf : Non-central F distribution.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the Quantile of the non-central f distribution\n"
+    "using the Boost Math C++ library [1]_.\n"
+    "\n"
+    "Note that argument order of `ncfdtri` is different from that of the\n"
+    "similar ``ppf`` method of `scipy.stats.ncf`. `p` is the last parameter\n"
+    "of `ncfdtri` but the first parameter of ``scipy.stats.ncf.ppf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtri\n"
+    "\n"
+    "Compute the CDF for several values of `f`:\n"
+    "\n"
+    ">>> f = [0.5, 1, 1.5]\n"
+    ">>> p = ncfdtr(2, 3, 1.5, f)\n"
+    ">>> p\n"
+    "array([ 0.20782291,  0.36107392,  0.47345752])\n"
+    "\n"
+    "Compute the inverse.  We recover the values of `f`, as expected:\n"
+    "\n"
+    ">>> ncfdtri(2, 3, 1.5, p)\n"
+    "array([ 0.5,  1. ,  1.5])")
+ufunc_ncfdtri_loops[0] = loop_f_ffff__As_ffff_f
+ufunc_ncfdtri_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtri_types[0] = NPY_FLOAT
+ufunc_ncfdtri_types[1] = NPY_FLOAT
+ufunc_ncfdtri_types[2] = NPY_FLOAT
+ufunc_ncfdtri_types[3] = NPY_FLOAT
+ufunc_ncfdtri_types[4] = NPY_FLOAT
+ufunc_ncfdtri_types[5] = NPY_DOUBLE
+ufunc_ncfdtri_types[6] = NPY_DOUBLE
+ufunc_ncfdtri_types[7] = NPY_DOUBLE
+ufunc_ncfdtri_types[8] = NPY_DOUBLE
+ufunc_ncfdtri_types[9] = NPY_DOUBLE
+ufunc_ncfdtri_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_ppf_float
+ufunc_ncfdtri_ptr[2*0+1] = ("ncfdtri")
+ufunc_ncfdtri_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_ppf_double
+ufunc_ncfdtri_ptr[2*1+1] = ("ncfdtri")
+ufunc_ncfdtri_data[0] = &ufunc_ncfdtri_ptr[2*0]
+ufunc_ncfdtri_data[1] = &ufunc_ncfdtri_ptr[2*1]
+ncfdtri = np.PyUFunc_FromFuncAndData(ufunc_ncfdtri_loops, ufunc_ncfdtri_data, ufunc_ncfdtri_types, 2, 4, 1, 0, "ncfdtri", ufunc_ncfdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtridfd_loops[2]
+cdef void *ufunc_ncfdtridfd_ptr[4]
+cdef void *ufunc_ncfdtridfd_data[2]
+cdef char ufunc_ncfdtridfd_types[10]
+cdef char *ufunc_ncfdtridfd_doc = (
+    "ncfdtridfd(dfn, p, nc, f, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom (denominator) for the noncentral F-distribution.\n"
+    "\n"
+    "This is the inverse with respect to `dfd` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function.  Must be in the\n"
+    "    range [0, 1].\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Should be in range (0, 1e4).\n"
+    "f : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfd : scalar or ndarray\n"
+    "    Degrees of freedom of the denominator sum of squares.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The value of the cumulative noncentral F distribution is not necessarily\n"
+    "monotone in either degrees of freedom. There thus may be two values that\n"
+    "provide a given CDF value. This routine assumes monotonicity and will\n"
+    "find an arbitrary one of the two values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtridfd\n"
+    "\n"
+    "Compute the CDF for several values of `dfd`:\n"
+    "\n"
+    ">>> dfd = [1, 2, 3]\n"
+    ">>> p = ncfdtr(2, dfd, 0.25, 15)\n"
+    ">>> p\n"
+    "array([ 0.8097138 ,  0.93020416,  0.96787852])\n"
+    "\n"
+    "Compute the inverse.  We recover the values of `dfd`, as expected:\n"
+    "\n"
+    ">>> ncfdtridfd(2, p, 0.25, 15)\n"
+    "array([ 1.,  2.,  3.])")
+ufunc_ncfdtridfd_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtridfd_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtridfd_types[0] = NPY_FLOAT
+ufunc_ncfdtridfd_types[1] = NPY_FLOAT
+ufunc_ncfdtridfd_types[2] = NPY_FLOAT
+ufunc_ncfdtridfd_types[3] = NPY_FLOAT
+ufunc_ncfdtridfd_types[4] = NPY_FLOAT
+ufunc_ncfdtridfd_types[5] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[6] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[7] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[8] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[9] = NPY_DOUBLE
+ufunc_ncfdtridfd_ptr[2*0] = _func_ncfdtridfd
+ufunc_ncfdtridfd_ptr[2*0+1] = ("ncfdtridfd")
+ufunc_ncfdtridfd_ptr[2*1] = _func_ncfdtridfd
+ufunc_ncfdtridfd_ptr[2*1+1] = ("ncfdtridfd")
+ufunc_ncfdtridfd_data[0] = &ufunc_ncfdtridfd_ptr[2*0]
+ufunc_ncfdtridfd_data[1] = &ufunc_ncfdtridfd_ptr[2*1]
+ncfdtridfd = np.PyUFunc_FromFuncAndData(ufunc_ncfdtridfd_loops, ufunc_ncfdtridfd_data, ufunc_ncfdtridfd_types, 2, 4, 1, 0, "ncfdtridfd", ufunc_ncfdtridfd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtridfn_loops[2]
+cdef void *ufunc_ncfdtridfn_ptr[4]
+cdef void *ufunc_ncfdtridfn_data[2]
+cdef char ufunc_ncfdtridfn_types[10]
+cdef char *ufunc_ncfdtridfn_doc = (
+    "ncfdtridfn(p, dfd, nc, f, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom (numerator) for the noncentral F-distribution.\n"
+    "\n"
+    "This is the inverse with respect to `dfn` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function. Must be in the\n"
+    "    range [0, 1].\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares. Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Should be in range (0, 1e4).\n"
+    "f : float\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfn : scalar or ndarray\n"
+    "    Degrees of freedom of the numerator sum of squares.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The value of the cumulative noncentral F distribution is not necessarily\n"
+    "monotone in either degrees of freedom. There thus may be two values that\n"
+    "provide a given CDF value. This routine assumes monotonicity and will\n"
+    "find an arbitrary one of the two values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtridfn\n"
+    "\n"
+    "Compute the CDF for several values of `dfn`:\n"
+    "\n"
+    ">>> dfn = [1, 2, 3]\n"
+    ">>> p = ncfdtr(dfn, 2, 0.25, 15)\n"
+    ">>> p\n"
+    "array([ 0.92562363,  0.93020416,  0.93188394])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `dfn`, as expected:\n"
+    "\n"
+    ">>> ncfdtridfn(p, 2, 0.25, 15)\n"
+    "array([ 1.,  2.,  3.])")
+ufunc_ncfdtridfn_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtridfn_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtridfn_types[0] = NPY_FLOAT
+ufunc_ncfdtridfn_types[1] = NPY_FLOAT
+ufunc_ncfdtridfn_types[2] = NPY_FLOAT
+ufunc_ncfdtridfn_types[3] = NPY_FLOAT
+ufunc_ncfdtridfn_types[4] = NPY_FLOAT
+ufunc_ncfdtridfn_types[5] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[6] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[7] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[8] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[9] = NPY_DOUBLE
+ufunc_ncfdtridfn_ptr[2*0] = _func_ncfdtridfn
+ufunc_ncfdtridfn_ptr[2*0+1] = ("ncfdtridfn")
+ufunc_ncfdtridfn_ptr[2*1] = _func_ncfdtridfn
+ufunc_ncfdtridfn_ptr[2*1+1] = ("ncfdtridfn")
+ufunc_ncfdtridfn_data[0] = &ufunc_ncfdtridfn_ptr[2*0]
+ufunc_ncfdtridfn_data[1] = &ufunc_ncfdtridfn_ptr[2*1]
+ncfdtridfn = np.PyUFunc_FromFuncAndData(ufunc_ncfdtridfn_loops, ufunc_ncfdtridfn_data, ufunc_ncfdtridfn_types, 2, 4, 1, 0, "ncfdtridfn", ufunc_ncfdtridfn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtrinc_loops[2]
+cdef void *ufunc_ncfdtrinc_ptr[4]
+cdef void *ufunc_ncfdtrinc_data[2]
+cdef char ufunc_ncfdtrinc_types[10]
+cdef char *ufunc_ncfdtrinc_doc = (
+    "ncfdtrinc(dfn, dfd, p, f, out=None)\n"
+    "\n"
+    "Calculate non-centrality parameter for non-central F distribution.\n"
+    "\n"
+    "This is the inverse with respect to `nc` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares. Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares. Range (0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function. Must be in the\n"
+    "    range [0, 1].\n"
+    "f : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Noncentrality parameter.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtrinc\n"
+    "\n"
+    "Compute the CDF for several values of `nc`:\n"
+    "\n"
+    ">>> nc = [0.5, 1.5, 2.0]\n"
+    ">>> p = ncfdtr(2, 3, nc, 15)\n"
+    ">>> p\n"
+    "array([ 0.96309246,  0.94327955,  0.93304098])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `nc`, as expected:\n"
+    "\n"
+    ">>> ncfdtrinc(2, 3, p, 15)\n"
+    "array([ 0.5,  1.5,  2. ])")
+ufunc_ncfdtrinc_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtrinc_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtrinc_types[0] = NPY_FLOAT
+ufunc_ncfdtrinc_types[1] = NPY_FLOAT
+ufunc_ncfdtrinc_types[2] = NPY_FLOAT
+ufunc_ncfdtrinc_types[3] = NPY_FLOAT
+ufunc_ncfdtrinc_types[4] = NPY_FLOAT
+ufunc_ncfdtrinc_types[5] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[6] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[7] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[8] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[9] = NPY_DOUBLE
+ufunc_ncfdtrinc_ptr[2*0] = _func_ncfdtrinc
+ufunc_ncfdtrinc_ptr[2*0+1] = ("ncfdtrinc")
+ufunc_ncfdtrinc_ptr[2*1] = _func_ncfdtrinc
+ufunc_ncfdtrinc_ptr[2*1+1] = ("ncfdtrinc")
+ufunc_ncfdtrinc_data[0] = &ufunc_ncfdtrinc_ptr[2*0]
+ufunc_ncfdtrinc_data[1] = &ufunc_ncfdtrinc_ptr[2*1]
+ncfdtrinc = np.PyUFunc_FromFuncAndData(ufunc_ncfdtrinc_loops, ufunc_ncfdtrinc_data, ufunc_ncfdtrinc_types, 2, 4, 1, 0, "ncfdtrinc", ufunc_ncfdtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtr_loops[2]
+cdef void *ufunc_nctdtr_ptr[4]
+cdef void *ufunc_nctdtr_data[2]
+cdef char ufunc_nctdtr_types[8]
+cdef char *ufunc_nctdtr_doc = (
+    "nctdtr(df, nc, t, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the non-central `t` distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    The calculated CDF. If all inputs are scalar, the return will be a\n"
+    "    float. Otherwise, it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the CDF of the non-central t distribution using\n"
+    "the Boost Math C++ library [1]_.\n"
+    "\n"
+    "Note that the argument order of `nctdtr` is different from that of the\n"
+    "similar ``cdf`` method of `scipy.stats.nct`: `t` is the last\n"
+    "parameter of `nctdtr` but the first parameter of ``scipy.stats.nct.cdf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> from scipy import stats\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Plot the CDF of the non-central t distribution, for nc=0. Compare with the\n"
+    "t-distribution from scipy.stats:\n"
+    "\n"
+    ">>> x = np.linspace(-5, 5, num=500)\n"
+    ">>> df = 3\n"
+    ">>> nct_stats = stats.t.cdf(x, df)\n"
+    ">>> nct_special = special.nctdtr(df, 0, x)\n"
+    "\n"
+    ">>> fig = plt.figure()\n"
+    ">>> ax = fig.add_subplot(111)\n"
+    ">>> ax.plot(x, nct_stats, 'b-', lw=3)\n"
+    ">>> ax.plot(x, nct_special, 'r-')\n"
+    ">>> plt.show()")
+ufunc_nctdtr_loops[0] = loop_f_fff__As_fff_f
+ufunc_nctdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtr_types[0] = NPY_FLOAT
+ufunc_nctdtr_types[1] = NPY_FLOAT
+ufunc_nctdtr_types[2] = NPY_FLOAT
+ufunc_nctdtr_types[3] = NPY_FLOAT
+ufunc_nctdtr_types[4] = NPY_DOUBLE
+ufunc_nctdtr_types[5] = NPY_DOUBLE
+ufunc_nctdtr_types[6] = NPY_DOUBLE
+ufunc_nctdtr_types[7] = NPY_DOUBLE
+ufunc_nctdtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_cdf_float
+ufunc_nctdtr_ptr[2*0+1] = ("nctdtr")
+ufunc_nctdtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_cdf_double
+ufunc_nctdtr_ptr[2*1+1] = ("nctdtr")
+ufunc_nctdtr_data[0] = &ufunc_nctdtr_ptr[2*0]
+ufunc_nctdtr_data[1] = &ufunc_nctdtr_ptr[2*1]
+nctdtr = np.PyUFunc_FromFuncAndData(ufunc_nctdtr_loops, ufunc_nctdtr_data, ufunc_nctdtr_types, 2, 3, 1, 0, "nctdtr", ufunc_nctdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtridf_loops[2]
+cdef void *ufunc_nctdtridf_ptr[4]
+cdef void *ufunc_nctdtridf_data[2]
+cdef char ufunc_nctdtridf_types[8]
+cdef char *ufunc_nctdtridf_doc = (
+    "nctdtridf(p, nc, t, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom for non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter. Should be in range (-1e6, 1e6).\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    The degrees of freedom. If all inputs are scalar, the return will be a\n"
+    "    float. Otherwise, it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtridf\n"
+    "\n"
+    "Compute the CDF for several values of `df`:\n"
+    "\n"
+    ">>> df = [1, 2, 3]\n"
+    ">>> p = nctdtr(df, 0.25, 1)\n"
+    ">>> p\n"
+    "array([0.67491974, 0.716464  , 0.73349456])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `df`, as expected:\n"
+    "\n"
+    ">>> nctdtridf(p, 0.25, 1)\n"
+    "array([1., 2., 3.])")
+ufunc_nctdtridf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtridf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtridf_types[0] = NPY_FLOAT
+ufunc_nctdtridf_types[1] = NPY_FLOAT
+ufunc_nctdtridf_types[2] = NPY_FLOAT
+ufunc_nctdtridf_types[3] = NPY_FLOAT
+ufunc_nctdtridf_types[4] = NPY_DOUBLE
+ufunc_nctdtridf_types[5] = NPY_DOUBLE
+ufunc_nctdtridf_types[6] = NPY_DOUBLE
+ufunc_nctdtridf_types[7] = NPY_DOUBLE
+ufunc_nctdtridf_ptr[2*0] = _func_nctdtridf
+ufunc_nctdtridf_ptr[2*0+1] = ("nctdtridf")
+ufunc_nctdtridf_ptr[2*1] = _func_nctdtridf
+ufunc_nctdtridf_ptr[2*1+1] = ("nctdtridf")
+ufunc_nctdtridf_data[0] = &ufunc_nctdtridf_ptr[2*0]
+ufunc_nctdtridf_data[1] = &ufunc_nctdtridf_ptr[2*1]
+nctdtridf = np.PyUFunc_FromFuncAndData(ufunc_nctdtridf_loops, ufunc_nctdtridf_data, ufunc_nctdtridf_types, 2, 3, 1, 0, "nctdtridf", ufunc_nctdtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtrinc_loops[2]
+cdef void *ufunc_nctdtrinc_ptr[4]
+cdef void *ufunc_nctdtrinc_data[2]
+cdef char ufunc_nctdtrinc_types[8]
+cdef char *ufunc_nctdtrinc_doc = (
+    "nctdtrinc(df, p, t, out=None)\n"
+    "\n"
+    "Calculate non-centrality parameter for non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Noncentrality parameter\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtrinc\n"
+    "\n"
+    "Compute the CDF for several values of `nc`:\n"
+    "\n"
+    ">>> nc = [0.5, 1.5, 2.5]\n"
+    ">>> p = nctdtr(3, nc, 1.5)\n"
+    ">>> p\n"
+    "array([0.77569497, 0.45524533, 0.1668691 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `nc`, as expected:\n"
+    "\n"
+    ">>> nctdtrinc(3, p, 1.5)\n"
+    "array([0.5, 1.5, 2.5])")
+ufunc_nctdtrinc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtrinc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtrinc_types[0] = NPY_FLOAT
+ufunc_nctdtrinc_types[1] = NPY_FLOAT
+ufunc_nctdtrinc_types[2] = NPY_FLOAT
+ufunc_nctdtrinc_types[3] = NPY_FLOAT
+ufunc_nctdtrinc_types[4] = NPY_DOUBLE
+ufunc_nctdtrinc_types[5] = NPY_DOUBLE
+ufunc_nctdtrinc_types[6] = NPY_DOUBLE
+ufunc_nctdtrinc_types[7] = NPY_DOUBLE
+ufunc_nctdtrinc_ptr[2*0] = _func_nctdtrinc
+ufunc_nctdtrinc_ptr[2*0+1] = ("nctdtrinc")
+ufunc_nctdtrinc_ptr[2*1] = _func_nctdtrinc
+ufunc_nctdtrinc_ptr[2*1+1] = ("nctdtrinc")
+ufunc_nctdtrinc_data[0] = &ufunc_nctdtrinc_ptr[2*0]
+ufunc_nctdtrinc_data[1] = &ufunc_nctdtrinc_ptr[2*1]
+nctdtrinc = np.PyUFunc_FromFuncAndData(ufunc_nctdtrinc_loops, ufunc_nctdtrinc_data, ufunc_nctdtrinc_types, 2, 3, 1, 0, "nctdtrinc", ufunc_nctdtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtrit_loops[2]
+cdef void *ufunc_nctdtrit_ptr[4]
+cdef void *ufunc_nctdtrit_data[2]
+cdef char ufunc_nctdtrit_types[8]
+cdef char *ufunc_nctdtrit_doc = (
+    "nctdtrit(df, nc, p, out=None)\n"
+    "\n"
+    "Inverse cumulative distribution function of the non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter. Should be in range (-1e6, 1e6).\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t : scalar or ndarray\n"
+    "    Quantiles\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtrit\n"
+    "\n"
+    "Compute the CDF for several values of `t`:\n"
+    "\n"
+    ">>> t = [0.5, 1, 1.5]\n"
+    ">>> p = nctdtr(3, 1, t)\n"
+    ">>> p\n"
+    "array([0.29811049, 0.46922687, 0.6257559 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `t`, as expected:\n"
+    "\n"
+    ">>> nctdtrit(3, 1, p)\n"
+    "array([0.5, 1. , 1.5])")
+ufunc_nctdtrit_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtrit_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtrit_types[0] = NPY_FLOAT
+ufunc_nctdtrit_types[1] = NPY_FLOAT
+ufunc_nctdtrit_types[2] = NPY_FLOAT
+ufunc_nctdtrit_types[3] = NPY_FLOAT
+ufunc_nctdtrit_types[4] = NPY_DOUBLE
+ufunc_nctdtrit_types[5] = NPY_DOUBLE
+ufunc_nctdtrit_types[6] = NPY_DOUBLE
+ufunc_nctdtrit_types[7] = NPY_DOUBLE
+ufunc_nctdtrit_ptr[2*0] = _func_nctdtrit
+ufunc_nctdtrit_ptr[2*0+1] = ("nctdtrit")
+ufunc_nctdtrit_ptr[2*1] = _func_nctdtrit
+ufunc_nctdtrit_ptr[2*1+1] = ("nctdtrit")
+ufunc_nctdtrit_data[0] = &ufunc_nctdtrit_ptr[2*0]
+ufunc_nctdtrit_data[1] = &ufunc_nctdtrit_ptr[2*1]
+nctdtrit = np.PyUFunc_FromFuncAndData(ufunc_nctdtrit_loops, ufunc_nctdtrit_data, ufunc_nctdtrit_types, 2, 3, 1, 0, "nctdtrit", ufunc_nctdtrit_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtr_loops[4]
+cdef void *ufunc_ndtr_ptr[8]
+cdef void *ufunc_ndtr_data[4]
+cdef char ufunc_ndtr_types[8]
+cdef char *ufunc_ndtr_doc = (
+    "ndtr(x, out=None)\n"
+    "\n"
+    "Cumulative distribution of the standard normal distribution.\n"
+    "\n"
+    "Returns the area under the standard Gaussian probability\n"
+    "density function, integrated from minus infinity to `x`\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   \\frac{1}{\\sqrt{2\\pi}} \\int_{-\\infty}^x \\exp(-t^2/2) dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like, real or complex\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the normal CDF evaluated at `x`\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "log_ndtr : Logarithm of ndtr\n"
+    "ndtri : Inverse of ndtr, standard normal percentile function\n"
+    "erf : Error function\n"
+    "erfc : 1 - erf\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Evaluate `ndtr` at one point.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import ndtr\n"
+    ">>> ndtr(0.5)\n"
+    "0.6914624612740131\n"
+    "\n"
+    "Evaluate the function at several points by providing a NumPy array\n"
+    "or list for `x`.\n"
+    "\n"
+    ">>> ndtr([0, 0.5, 2])\n"
+    "array([0.5       , 0.69146246, 0.97724987])\n"
+    "\n"
+    "Plot the function.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-5, 5, 100)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, ndtr(x))\n"
+    ">>> ax.set_title(r\"Standard normal cumulative distribution function $\\Phi$\")\n"
+    ">>> plt.show()")
+ufunc_ndtr_loops[0] = loop_d_d__As_f_f
+ufunc_ndtr_loops[1] = loop_d_d__As_d_d
+ufunc_ndtr_loops[2] = loop_D_D__As_F_F
+ufunc_ndtr_loops[3] = loop_D_D__As_D_D
+ufunc_ndtr_types[0] = NPY_FLOAT
+ufunc_ndtr_types[1] = NPY_FLOAT
+ufunc_ndtr_types[2] = NPY_DOUBLE
+ufunc_ndtr_types[3] = NPY_DOUBLE
+ufunc_ndtr_types[4] = NPY_CFLOAT
+ufunc_ndtr_types[5] = NPY_CFLOAT
+ufunc_ndtr_types[6] = NPY_CDOUBLE
+ufunc_ndtr_types[7] = NPY_CDOUBLE
+ufunc_ndtr_ptr[2*0] = _func_xsf_ndtr
+ufunc_ndtr_ptr[2*0+1] = ("ndtr")
+ufunc_ndtr_ptr[2*1] = _func_xsf_ndtr
+ufunc_ndtr_ptr[2*1+1] = ("ndtr")
+ufunc_ndtr_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_ndtr
+ufunc_ndtr_ptr[2*2+1] = ("ndtr")
+ufunc_ndtr_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_ndtr
+ufunc_ndtr_ptr[2*3+1] = ("ndtr")
+ufunc_ndtr_data[0] = &ufunc_ndtr_ptr[2*0]
+ufunc_ndtr_data[1] = &ufunc_ndtr_ptr[2*1]
+ufunc_ndtr_data[2] = &ufunc_ndtr_ptr[2*2]
+ufunc_ndtr_data[3] = &ufunc_ndtr_ptr[2*3]
+ndtr = np.PyUFunc_FromFuncAndData(ufunc_ndtr_loops, ufunc_ndtr_data, ufunc_ndtr_types, 4, 1, 1, 0, "ndtr", ufunc_ndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtri_loops[2]
+cdef void *ufunc_ndtri_ptr[4]
+cdef void *ufunc_ndtri_data[2]
+cdef char ufunc_ndtri_types[4]
+cdef char *ufunc_ndtri_doc = (
+    "ndtri(y, out=None)\n"
+    "\n"
+    "Inverse of `ndtr` vs x\n"
+    "\n"
+    "Returns the argument x for which the area under the standard normal\n"
+    "probability density function (integrated from minus infinity to `x`)\n"
+    "is equal to y.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value of x such that ``ndtr(x) == p``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri_exp : Inverse of log_ndtr\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`ndtri` is the percentile function of the standard normal distribution.\n"
+    "This means it returns the inverse of the cumulative density `ndtr`. First,\n"
+    "let us compute a cumulative density value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import ndtri, ndtr\n"
+    ">>> cdf_val = ndtr(2)\n"
+    ">>> cdf_val\n"
+    "0.9772498680518208\n"
+    "\n"
+    "Verify that `ndtri` yields the original value for `x` up to floating point\n"
+    "errors.\n"
+    "\n"
+    ">>> ndtri(cdf_val)\n"
+    "2.0000000000000004\n"
+    "\n"
+    "Plot the function. For that purpose, we provide a NumPy array as argument.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(0.01, 1, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, ndtri(x))\n"
+    ">>> ax.set_title(\"Standard normal percentile function\")\n"
+    ">>> plt.show()")
+ufunc_ndtri_loops[0] = loop_d_d__As_f_f
+ufunc_ndtri_loops[1] = loop_d_d__As_d_d
+ufunc_ndtri_types[0] = NPY_FLOAT
+ufunc_ndtri_types[1] = NPY_FLOAT
+ufunc_ndtri_types[2] = NPY_DOUBLE
+ufunc_ndtri_types[3] = NPY_DOUBLE
+ufunc_ndtri_ptr[2*0] = _func_xsf_ndtri
+ufunc_ndtri_ptr[2*0+1] = ("ndtri")
+ufunc_ndtri_ptr[2*1] = _func_xsf_ndtri
+ufunc_ndtri_ptr[2*1+1] = ("ndtri")
+ufunc_ndtri_data[0] = &ufunc_ndtri_ptr[2*0]
+ufunc_ndtri_data[1] = &ufunc_ndtri_ptr[2*1]
+ndtri = np.PyUFunc_FromFuncAndData(ufunc_ndtri_loops, ufunc_ndtri_data, ufunc_ndtri_types, 2, 1, 1, 0, "ndtri", ufunc_ndtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtri_exp_loops[2]
+cdef void *ufunc_ndtri_exp_ptr[4]
+cdef void *ufunc_ndtri_exp_data[2]
+cdef char ufunc_ndtri_exp_types[4]
+cdef char *ufunc_ndtri_exp_doc = (
+    "ndtri_exp(y, out=None)\n"
+    "\n"
+    "Inverse of `log_ndtr` vs x. Allows for greater precision than\n"
+    "`ndtri` composed with `numpy.exp` for very small values of y and for\n"
+    "y close to 0.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like of float\n"
+    "    Function argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Inverse of the log CDF of the standard normal distribution, evaluated\n"
+    "    at y.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "log_ndtr : log of the standard normal cumulative distribution function\n"
+    "ndtr : standard normal cumulative distribution function\n"
+    "ndtri : standard normal percentile function\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "`ndtri_exp` agrees with the naive implementation when the latter does\n"
+    "not suffer from underflow.\n"
+    "\n"
+    ">>> sc.ndtri_exp(-1)\n"
+    "-0.33747496376420244\n"
+    ">>> sc.ndtri(np.exp(-1))\n"
+    "-0.33747496376420244\n"
+    "\n"
+    "For extreme values of y, the naive approach fails\n"
+    "\n"
+    ">>> sc.ndtri(np.exp(-800))\n"
+    "-inf\n"
+    ">>> sc.ndtri(np.exp(-1e-20))\n"
+    "inf\n"
+    "\n"
+    "whereas `ndtri_exp` is still able to compute the result to high precision.\n"
+    "\n"
+    ">>> sc.ndtri_exp(-800)\n"
+    "-39.88469483825668\n"
+    ">>> sc.ndtri_exp(-1e-20)\n"
+    "9.262340089798409")
+ufunc_ndtri_exp_loops[0] = loop_d_d__As_f_f
+ufunc_ndtri_exp_loops[1] = loop_d_d__As_d_d
+ufunc_ndtri_exp_types[0] = NPY_FLOAT
+ufunc_ndtri_exp_types[1] = NPY_FLOAT
+ufunc_ndtri_exp_types[2] = NPY_DOUBLE
+ufunc_ndtri_exp_types[3] = NPY_DOUBLE
+ufunc_ndtri_exp_ptr[2*0] = _func_ndtri_exp
+ufunc_ndtri_exp_ptr[2*0+1] = ("ndtri_exp")
+ufunc_ndtri_exp_ptr[2*1] = _func_ndtri_exp
+ufunc_ndtri_exp_ptr[2*1+1] = ("ndtri_exp")
+ufunc_ndtri_exp_data[0] = &ufunc_ndtri_exp_ptr[2*0]
+ufunc_ndtri_exp_data[1] = &ufunc_ndtri_exp_ptr[2*1]
+ndtri_exp = np.PyUFunc_FromFuncAndData(ufunc_ndtri_exp_loops, ufunc_ndtri_exp_data, ufunc_ndtri_exp_types, 2, 1, 1, 0, "ndtri_exp", ufunc_ndtri_exp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nrdtrimn_loops[2]
+cdef void *ufunc_nrdtrimn_ptr[4]
+cdef void *ufunc_nrdtrimn_data[2]
+cdef char ufunc_nrdtrimn_types[8]
+cdef char *ufunc_nrdtrimn_doc = (
+    "nrdtrimn(p, std, x, out=None)\n"
+    "\n"
+    "Calculate mean of normal distribution given other params.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "std : array_like\n"
+    "    Standard deviation.\n"
+    "x : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "mn : scalar or ndarray\n"
+    "    The mean of the normal distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri : Inverse of standard normal CDF with respect to quantile\n"
+    "nrdtrisd : Inverse of normal distribution CDF with respect to\n"
+    "           standard deviation\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nrdtrimn` can be used to recover the mean of a normal distribution\n"
+    "if we know the CDF value `p` for a given quantile `x` and the\n"
+    "standard deviation `std`. First, we calculate\n"
+    "the normal distribution CDF for an exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.stats import norm\n"
+    ">>> mean = 3.\n"
+    ">>> std = 2.\n"
+    ">>> x = 6.\n"
+    ">>> p = norm.cdf(x, loc=mean, scale=std)\n"
+    ">>> p\n"
+    "0.9331927987311419\n"
+    "\n"
+    "Verify that `nrdtrimn` returns the original value for `mean`.\n"
+    "\n"
+    ">>> from scipy.special import nrdtrimn\n"
+    ">>> nrdtrimn(p, std, x)\n"
+    "3.0000000000000004")
+ufunc_nrdtrimn_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nrdtrimn_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nrdtrimn_types[0] = NPY_FLOAT
+ufunc_nrdtrimn_types[1] = NPY_FLOAT
+ufunc_nrdtrimn_types[2] = NPY_FLOAT
+ufunc_nrdtrimn_types[3] = NPY_FLOAT
+ufunc_nrdtrimn_types[4] = NPY_DOUBLE
+ufunc_nrdtrimn_types[5] = NPY_DOUBLE
+ufunc_nrdtrimn_types[6] = NPY_DOUBLE
+ufunc_nrdtrimn_types[7] = NPY_DOUBLE
+ufunc_nrdtrimn_ptr[2*0] = _func_nrdtrimn
+ufunc_nrdtrimn_ptr[2*0+1] = ("nrdtrimn")
+ufunc_nrdtrimn_ptr[2*1] = _func_nrdtrimn
+ufunc_nrdtrimn_ptr[2*1+1] = ("nrdtrimn")
+ufunc_nrdtrimn_data[0] = &ufunc_nrdtrimn_ptr[2*0]
+ufunc_nrdtrimn_data[1] = &ufunc_nrdtrimn_ptr[2*1]
+nrdtrimn = np.PyUFunc_FromFuncAndData(ufunc_nrdtrimn_loops, ufunc_nrdtrimn_data, ufunc_nrdtrimn_types, 2, 3, 1, 0, "nrdtrimn", ufunc_nrdtrimn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nrdtrisd_loops[2]
+cdef void *ufunc_nrdtrisd_ptr[4]
+cdef void *ufunc_nrdtrisd_data[2]
+cdef char ufunc_nrdtrisd_types[8]
+cdef char *ufunc_nrdtrisd_doc = (
+    "nrdtrisd(mn, p, x, out=None)\n"
+    "\n"
+    "Calculate standard deviation of normal distribution given other params.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "mn : scalar or ndarray\n"
+    "    The mean of the normal distribution.\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "x : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "std : scalar or ndarray\n"
+    "    Standard deviation.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri : Inverse of standard normal CDF with respect to quantile\n"
+    "nrdtrimn : Inverse of normal distribution CDF with respect to\n"
+    "           mean\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nrdtrisd` can be used to recover the standard deviation of a normal\n"
+    "distribution if we know the CDF value `p` for a given quantile `x` and\n"
+    "the mean `mn`. First, we calculate the normal distribution CDF for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.stats import norm\n"
+    ">>> mean = 3.\n"
+    ">>> std = 2.\n"
+    ">>> x = 6.\n"
+    ">>> p = norm.cdf(x, loc=mean, scale=std)\n"
+    ">>> p\n"
+    "0.9331927987311419\n"
+    "\n"
+    "Verify that `nrdtrisd` returns the original value for `std`.\n"
+    "\n"
+    ">>> from scipy.special import nrdtrisd\n"
+    ">>> nrdtrisd(mean, p, x)\n"
+    "2.0000000000000004")
+ufunc_nrdtrisd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nrdtrisd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nrdtrisd_types[0] = NPY_FLOAT
+ufunc_nrdtrisd_types[1] = NPY_FLOAT
+ufunc_nrdtrisd_types[2] = NPY_FLOAT
+ufunc_nrdtrisd_types[3] = NPY_FLOAT
+ufunc_nrdtrisd_types[4] = NPY_DOUBLE
+ufunc_nrdtrisd_types[5] = NPY_DOUBLE
+ufunc_nrdtrisd_types[6] = NPY_DOUBLE
+ufunc_nrdtrisd_types[7] = NPY_DOUBLE
+ufunc_nrdtrisd_ptr[2*0] = _func_nrdtrisd
+ufunc_nrdtrisd_ptr[2*0+1] = ("nrdtrisd")
+ufunc_nrdtrisd_ptr[2*1] = _func_nrdtrisd
+ufunc_nrdtrisd_ptr[2*1+1] = ("nrdtrisd")
+ufunc_nrdtrisd_data[0] = &ufunc_nrdtrisd_ptr[2*0]
+ufunc_nrdtrisd_data[1] = &ufunc_nrdtrisd_ptr[2*1]
+nrdtrisd = np.PyUFunc_FromFuncAndData(ufunc_nrdtrisd_loops, ufunc_nrdtrisd_data, ufunc_nrdtrisd_types, 2, 3, 1, 0, "nrdtrisd", ufunc_nrdtrisd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_owens_t_loops[2]
+cdef void *ufunc_owens_t_ptr[4]
+cdef void *ufunc_owens_t_data[2]
+cdef char ufunc_owens_t_types[6]
+cdef char *ufunc_owens_t_doc = (
+    "owens_t(h, a, out=None)\n"
+    "\n"
+    "Owen's T Function.\n"
+    "\n"
+    "The function T(h, a) gives the probability of the event\n"
+    "(X > h and 0 < Y < a * X) where X and Y are independent\n"
+    "standard normal random variables.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "h: array_like\n"
+    "    Input value.\n"
+    "a: array_like\n"
+    "    Input value.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t: scalar or ndarray\n"
+    "    Probability of the event (X > h and 0 < Y < a * X),\n"
+    "    where X and Y are independent standard normal random variables.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] M. Patefield and D. Tandy, \"Fast and accurate calculation of\n"
+    "       Owen's T Function\", Statistical Software vol. 5, pp. 1-25, 2000.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy import special\n"
+    ">>> a = 3.5\n"
+    ">>> h = 0.78\n"
+    ">>> special.owens_t(h, a)\n"
+    "0.10877216734852274")
+ufunc_owens_t_loops[0] = loop_d_dd__As_ff_f
+ufunc_owens_t_loops[1] = loop_d_dd__As_dd_d
+ufunc_owens_t_types[0] = NPY_FLOAT
+ufunc_owens_t_types[1] = NPY_FLOAT
+ufunc_owens_t_types[2] = NPY_FLOAT
+ufunc_owens_t_types[3] = NPY_DOUBLE
+ufunc_owens_t_types[4] = NPY_DOUBLE
+ufunc_owens_t_types[5] = NPY_DOUBLE
+ufunc_owens_t_ptr[2*0] = _func_xsf_owens_t
+ufunc_owens_t_ptr[2*0+1] = ("owens_t")
+ufunc_owens_t_ptr[2*1] = _func_xsf_owens_t
+ufunc_owens_t_ptr[2*1+1] = ("owens_t")
+ufunc_owens_t_data[0] = &ufunc_owens_t_ptr[2*0]
+ufunc_owens_t_data[1] = &ufunc_owens_t_ptr[2*1]
+owens_t = np.PyUFunc_FromFuncAndData(ufunc_owens_t_loops, ufunc_owens_t_data, ufunc_owens_t_types, 2, 2, 1, 0, "owens_t", ufunc_owens_t_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtr_loops[2]
+cdef void *ufunc_pdtr_ptr[4]
+cdef void *ufunc_pdtr_data[2]
+cdef char ufunc_pdtr_types[6]
+cdef char *ufunc_pdtr_doc = (
+    "pdtr(k, m, out=None)\n"
+    "\n"
+    "Poisson cumulative distribution function.\n"
+    "\n"
+    "Defined as the probability that a Poisson-distributed random\n"
+    "variable with event rate :math:`m` is less than or equal to\n"
+    ":math:`k`. More concretely, this works out to be [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   \\exp(-m) \\sum_{j = 0}^{\\lfloor{k}\\rfloor} \\frac{m^j}{j!}.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Poisson cumulative distribution function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Poisson_distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is a cumulative distribution function, so it converges to 1\n"
+    "monotonically as `k` goes to infinity.\n"
+    "\n"
+    ">>> sc.pdtr([1, 10, 100, np.inf], 1)\n"
+    "array([0.73575888, 0.99999999, 1.        , 1.        ])\n"
+    "\n"
+    "It is discontinuous at integers and constant between integers.\n"
+    "\n"
+    ">>> sc.pdtr([1, 1.5, 1.9, 2], 1)\n"
+    "array([0.73575888, 0.73575888, 0.73575888, 0.9196986 ])")
+ufunc_pdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtr_types[0] = NPY_FLOAT
+ufunc_pdtr_types[1] = NPY_FLOAT
+ufunc_pdtr_types[2] = NPY_FLOAT
+ufunc_pdtr_types[3] = NPY_DOUBLE
+ufunc_pdtr_types[4] = NPY_DOUBLE
+ufunc_pdtr_types[5] = NPY_DOUBLE
+ufunc_pdtr_ptr[2*0] = _func_xsf_pdtr
+ufunc_pdtr_ptr[2*0+1] = ("pdtr")
+ufunc_pdtr_ptr[2*1] = _func_xsf_pdtr
+ufunc_pdtr_ptr[2*1+1] = ("pdtr")
+ufunc_pdtr_data[0] = &ufunc_pdtr_ptr[2*0]
+ufunc_pdtr_data[1] = &ufunc_pdtr_ptr[2*1]
+pdtr = np.PyUFunc_FromFuncAndData(ufunc_pdtr_loops, ufunc_pdtr_data, ufunc_pdtr_types, 2, 2, 1, 0, "pdtr", ufunc_pdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtrc_loops[2]
+cdef void *ufunc_pdtrc_ptr[4]
+cdef void *ufunc_pdtrc_data[2]
+cdef char ufunc_pdtrc_types[6]
+cdef char *ufunc_pdtrc_doc = (
+    "pdtrc(k, m, out=None)\n"
+    "\n"
+    "Poisson survival function\n"
+    "\n"
+    "Returns the sum of the terms from k+1 to infinity of the Poisson\n"
+    "distribution: sum(exp(-m) * m**j / j!, j=k+1..inf) = gammainc(\n"
+    "k+1, m). Arguments must both be non-negative doubles.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Poisson survival function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is a survival function, so it decreases to 0\n"
+    "monotonically as `k` goes to infinity.\n"
+    "\n"
+    ">>> k = np.array([1, 10, 100, np.inf])\n"
+    ">>> sc.pdtrc(k, 1)\n"
+    "array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])\n"
+    "\n"
+    "It can be expressed in terms of the lower incomplete gamma\n"
+    "function `gammainc`.\n"
+    "\n"
+    ">>> sc.gammainc(k + 1, 1)\n"
+    "array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])")
+ufunc_pdtrc_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtrc_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtrc_types[0] = NPY_FLOAT
+ufunc_pdtrc_types[1] = NPY_FLOAT
+ufunc_pdtrc_types[2] = NPY_FLOAT
+ufunc_pdtrc_types[3] = NPY_DOUBLE
+ufunc_pdtrc_types[4] = NPY_DOUBLE
+ufunc_pdtrc_types[5] = NPY_DOUBLE
+ufunc_pdtrc_ptr[2*0] = _func_xsf_pdtrc
+ufunc_pdtrc_ptr[2*0+1] = ("pdtrc")
+ufunc_pdtrc_ptr[2*1] = _func_xsf_pdtrc
+ufunc_pdtrc_ptr[2*1+1] = ("pdtrc")
+ufunc_pdtrc_data[0] = &ufunc_pdtrc_ptr[2*0]
+ufunc_pdtrc_data[1] = &ufunc_pdtrc_ptr[2*1]
+pdtrc = np.PyUFunc_FromFuncAndData(ufunc_pdtrc_loops, ufunc_pdtrc_data, ufunc_pdtrc_types, 2, 2, 1, 0, "pdtrc", ufunc_pdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtri_loops[3]
+cdef void *ufunc_pdtri_ptr[6]
+cdef void *ufunc_pdtri_data[3]
+cdef char ufunc_pdtri_types[9]
+cdef char *ufunc_pdtri_doc = (
+    "pdtri(k, y, out=None)\n"
+    "\n"
+    "Inverse to `pdtr` vs m\n"
+    "\n"
+    "Returns the Poisson variable `m` such that the sum from 0 to `k` of\n"
+    "the Poisson density is equal to the given probability `y`:\n"
+    "calculated by ``gammaincinv(k + 1, y)``. `k` must be a nonnegative\n"
+    "integer and `y` between 0 and 1.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "y : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the shape parameter `m` such that ``pdtr(k, m) = p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Compute the CDF for several values of `m`:\n"
+    "\n"
+    ">>> m = [0.5, 1, 1.5]\n"
+    ">>> p = sc.pdtr(1, m)\n"
+    ">>> p\n"
+    "array([0.90979599, 0.73575888, 0.5578254 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `m`, as expected:\n"
+    "\n"
+    ">>> sc.pdtri(1, p)\n"
+    "array([0.5, 1. , 1.5])")
+ufunc_pdtri_loops[0] = loop_d_pd__As_pd_d
+ufunc_pdtri_loops[1] = loop_d_dd__As_ff_f
+ufunc_pdtri_loops[2] = loop_d_dd__As_dd_d
+ufunc_pdtri_types[0] = NPY_INTP
+ufunc_pdtri_types[1] = NPY_DOUBLE
+ufunc_pdtri_types[2] = NPY_DOUBLE
+ufunc_pdtri_types[3] = NPY_FLOAT
+ufunc_pdtri_types[4] = NPY_FLOAT
+ufunc_pdtri_types[5] = NPY_FLOAT
+ufunc_pdtri_types[6] = NPY_DOUBLE
+ufunc_pdtri_types[7] = NPY_DOUBLE
+ufunc_pdtri_types[8] = NPY_DOUBLE
+ufunc_pdtri_ptr[2*0] = _func_cephes_pdtri_wrap
+ufunc_pdtri_ptr[2*0+1] = ("pdtri")
+ufunc_pdtri_ptr[2*1] = _func_pdtri_unsafe
+ufunc_pdtri_ptr[2*1+1] = ("pdtri")
+ufunc_pdtri_ptr[2*2] = _func_pdtri_unsafe
+ufunc_pdtri_ptr[2*2+1] = ("pdtri")
+ufunc_pdtri_data[0] = &ufunc_pdtri_ptr[2*0]
+ufunc_pdtri_data[1] = &ufunc_pdtri_ptr[2*1]
+ufunc_pdtri_data[2] = &ufunc_pdtri_ptr[2*2]
+pdtri = np.PyUFunc_FromFuncAndData(ufunc_pdtri_loops, ufunc_pdtri_data, ufunc_pdtri_types, 3, 2, 1, 0, "pdtri", ufunc_pdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtrik_loops[2]
+cdef void *ufunc_pdtrik_ptr[4]
+cdef void *ufunc_pdtrik_data[2]
+cdef char ufunc_pdtrik_types[6]
+cdef char *ufunc_pdtrik_doc = (
+    "pdtrik(p, m, out=None)\n"
+    "\n"
+    "Inverse to `pdtr` vs `k`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The number of occurrences `k` such that ``pdtr(k, m) = p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Compute the CDF for several values of `k`:\n"
+    "\n"
+    ">>> k = [1, 2, 3]\n"
+    ">>> p = sc.pdtr(k, 2)\n"
+    ">>> p\n"
+    "array([0.40600585, 0.67667642, 0.85712346])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `k`, as expected:\n"
+    "\n"
+    ">>> sc.pdtrik(p, 2)\n"
+    "array([1., 2., 3.])")
+ufunc_pdtrik_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtrik_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtrik_types[0] = NPY_FLOAT
+ufunc_pdtrik_types[1] = NPY_FLOAT
+ufunc_pdtrik_types[2] = NPY_FLOAT
+ufunc_pdtrik_types[3] = NPY_DOUBLE
+ufunc_pdtrik_types[4] = NPY_DOUBLE
+ufunc_pdtrik_types[5] = NPY_DOUBLE
+ufunc_pdtrik_ptr[2*0] = _func_pdtrik
+ufunc_pdtrik_ptr[2*0+1] = ("pdtrik")
+ufunc_pdtrik_ptr[2*1] = _func_pdtrik
+ufunc_pdtrik_ptr[2*1+1] = ("pdtrik")
+ufunc_pdtrik_data[0] = &ufunc_pdtrik_ptr[2*0]
+ufunc_pdtrik_data[1] = &ufunc_pdtrik_ptr[2*1]
+pdtrik = np.PyUFunc_FromFuncAndData(ufunc_pdtrik_loops, ufunc_pdtrik_data, ufunc_pdtrik_types, 2, 2, 1, 0, "pdtrik", ufunc_pdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_poch_loops[2]
+cdef void *ufunc_poch_ptr[4]
+cdef void *ufunc_poch_data[2]
+cdef char ufunc_poch_types[6]
+cdef char *ufunc_poch_doc = (
+    "poch(z, m, out=None)\n"
+    "\n"
+    "Pochhammer symbol.\n"
+    "\n"
+    "The Pochhammer symbol (rising factorial) is defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    (z)_m = \\frac{\\Gamma(z + m)}{\\Gamma(z)}\n"
+    "\n"
+    "For positive integer `m` it reads\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    (z)_m = z (z + 1) ... (z + m - 1)\n"
+    "\n"
+    "See [dlmf]_ for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z, m : array_like\n"
+    "    Real-valued arguments.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the function.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] Nist, Digital Library of Mathematical Functions\n"
+    "    https://dlmf.nist.gov/5.2#iii\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is 1 when m is 0.\n"
+    "\n"
+    ">>> sc.poch([1, 2, 3, 4], 0)\n"
+    "array([1., 1., 1., 1.])\n"
+    "\n"
+    "For z equal to 1 it reduces to the factorial function.\n"
+    "\n"
+    ">>> sc.poch(1, 5)\n"
+    "120.0\n"
+    ">>> 1 * 2 * 3 * 4 * 5\n"
+    "120\n"
+    "\n"
+    "It can be expressed in terms of the gamma function.\n"
+    "\n"
+    ">>> z, m = 3.7, 2.1\n"
+    ">>> sc.poch(z, m)\n"
+    "20.529581933776953\n"
+    ">>> sc.gamma(z + m) / sc.gamma(z)\n"
+    "20.52958193377696")
+ufunc_poch_loops[0] = loop_d_dd__As_ff_f
+ufunc_poch_loops[1] = loop_d_dd__As_dd_d
+ufunc_poch_types[0] = NPY_FLOAT
+ufunc_poch_types[1] = NPY_FLOAT
+ufunc_poch_types[2] = NPY_FLOAT
+ufunc_poch_types[3] = NPY_DOUBLE
+ufunc_poch_types[4] = NPY_DOUBLE
+ufunc_poch_types[5] = NPY_DOUBLE
+ufunc_poch_ptr[2*0] = _func_cephes_poch
+ufunc_poch_ptr[2*0+1] = ("poch")
+ufunc_poch_ptr[2*1] = _func_cephes_poch
+ufunc_poch_ptr[2*1+1] = ("poch")
+ufunc_poch_data[0] = &ufunc_poch_ptr[2*0]
+ufunc_poch_data[1] = &ufunc_poch_ptr[2*1]
+poch = np.PyUFunc_FromFuncAndData(ufunc_poch_loops, ufunc_poch_data, ufunc_poch_types, 2, 2, 1, 0, "poch", ufunc_poch_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_powm1_loops[2]
+cdef void *ufunc_powm1_ptr[4]
+cdef void *ufunc_powm1_data[2]
+cdef char ufunc_powm1_types[6]
+cdef char *ufunc_powm1_doc = (
+    "powm1(x, y, out=None)\n"
+    "\n"
+    "Computes ``x**y - 1``.\n"
+    "\n"
+    "This function is useful when `y` is near 0, or when `x` is near 1.\n"
+    "\n"
+    "The function is implemented for real types only (unlike ``numpy.power``,\n"
+    "which accepts complex inputs).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    The base. Must be a real type (i.e. integer or float, not complex).\n"
+    "y : array_like\n"
+    "    The exponent. Must be a real type (i.e. integer or float, not complex).\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "array_like\n"
+    "    Result of the calculation\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.10.0\n"
+    "\n"
+    "The underlying code is implemented for single precision and double\n"
+    "precision floats only.  Unlike `numpy.power`, integer inputs to\n"
+    "`powm1` are converted to floating point, and complex inputs are\n"
+    "not accepted.\n"
+    "\n"
+    "Note the following edge cases:\n"
+    "\n"
+    "* ``powm1(x, 0)`` returns 0 for any ``x``, including 0, ``inf``\n"
+    "  and ``nan``.\n"
+    "* ``powm1(1, y)`` returns 0 for any ``y``, including ``nan``\n"
+    "  and ``inf``.\n"
+    "\n"
+    "This function wraps the ``powm1`` routine from the\n"
+    "Boost Math C++ library [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import powm1\n"
+    "\n"
+    ">>> x = np.array([1.2, 10.0, 0.9999999975])\n"
+    ">>> y = np.array([1e-9, 1e-11, 0.1875])\n"
+    ">>> powm1(x, y)\n"
+    "array([ 1.82321557e-10,  2.30258509e-11, -4.68749998e-10])\n"
+    "\n"
+    "It can be verified that the relative errors in those results\n"
+    "are less than 2.5e-16.\n"
+    "\n"
+    "Compare that to the result of ``x**y - 1``, where the\n"
+    "relative errors are all larger than 8e-8:\n"
+    "\n"
+    ">>> x**y - 1\n"
+    "array([ 1.82321491e-10,  2.30258035e-11, -4.68750039e-10])")
+ufunc_powm1_loops[0] = loop_f_ff__As_ff_f
+ufunc_powm1_loops[1] = loop_d_dd__As_dd_d
+ufunc_powm1_types[0] = NPY_FLOAT
+ufunc_powm1_types[1] = NPY_FLOAT
+ufunc_powm1_types[2] = NPY_FLOAT
+ufunc_powm1_types[3] = NPY_DOUBLE
+ufunc_powm1_types[4] = NPY_DOUBLE
+ufunc_powm1_types[5] = NPY_DOUBLE
+ufunc_powm1_ptr[2*0] = scipy.special._ufuncs_cxx._export_powm1_float
+ufunc_powm1_ptr[2*0+1] = ("powm1")
+ufunc_powm1_ptr[2*1] = scipy.special._ufuncs_cxx._export_powm1_double
+ufunc_powm1_ptr[2*1+1] = ("powm1")
+ufunc_powm1_data[0] = &ufunc_powm1_ptr[2*0]
+ufunc_powm1_data[1] = &ufunc_powm1_ptr[2*1]
+powm1 = np.PyUFunc_FromFuncAndData(ufunc_powm1_loops, ufunc_powm1_data, ufunc_powm1_types, 2, 2, 1, 0, "powm1", ufunc_powm1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pseudo_huber_loops[2]
+cdef void *ufunc_pseudo_huber_ptr[4]
+cdef void *ufunc_pseudo_huber_data[2]
+cdef char ufunc_pseudo_huber_types[6]
+cdef char *ufunc_pseudo_huber_doc = (
+    "pseudo_huber(delta, r, out=None)\n"
+    "\n"
+    "Pseudo-Huber loss function.\n"
+    "\n"
+    ".. math:: \\mathrm{pseudo\\_huber}(\\delta, r) =\n"
+    "          \\delta^2 \\left( \\sqrt{ 1 + \\left( \\frac{r}{\\delta} \\right)^2 } - 1 \\right)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "delta : array_like\n"
+    "    Input array, indicating the soft quadratic vs. linear loss changepoint.\n"
+    "r : array_like\n"
+    "    Input array, possibly representing residuals.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The computed Pseudo-Huber loss function values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "huber: Similar function which this function approximates\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Like `huber`, `pseudo_huber` often serves as a robust loss function\n"
+    "in statistics or machine learning to reduce the influence of outliers.\n"
+    "Unlike `huber`, `pseudo_huber` is smooth.\n"
+    "\n"
+    "Typically, `r` represents residuals, the difference\n"
+    "between a model prediction and data. Then, for :math:`|r|\\leq\\delta`,\n"
+    "`pseudo_huber` resembles the squared error and for :math:`|r|>\\delta` the\n"
+    "absolute error. This way, the Pseudo-Huber loss often achieves\n"
+    "a fast convergence in model fitting for small residuals like the squared\n"
+    "error loss function and still reduces the influence of outliers\n"
+    "(:math:`|r|>\\delta`) like the absolute error loss. As :math:`\\delta` is\n"
+    "the cutoff between squared and absolute error regimes, it has\n"
+    "to be tuned carefully for each problem. `pseudo_huber` is also\n"
+    "convex, making it suitable for gradient based optimization. [1]_ [2]_\n"
+    "\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Hartley, Zisserman, \"Multiple View Geometry in Computer Vision\".\n"
+    "       2003. Cambridge University Press. p. 619\n"
+    ".. [2] Charbonnier et al. \"Deterministic edge-preserving regularization\n"
+    "       in computed imaging\". 1997. IEEE Trans. Image Processing.\n"
+    "       6 (2): 298 - 311.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Import all necessary modules.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import pseudo_huber, huber\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Calculate the function for ``delta=1`` at ``r=2``.\n"
+    "\n"
+    ">>> pseudo_huber(1., 2.)\n"
+    "1.2360679774997898\n"
+    "\n"
+    "Calculate the function at ``r=2`` for different `delta` by providing\n"
+    "a list or NumPy array for `delta`.\n"
+    "\n"
+    ">>> pseudo_huber([1., 2., 4.], 3.)\n"
+    "array([2.16227766, 3.21110255, 4.        ])\n"
+    "\n"
+    "Calculate the function for ``delta=1`` at several points by providing\n"
+    "a list or NumPy array for `r`.\n"
+    "\n"
+    ">>> pseudo_huber(2., np.array([1., 1.5, 3., 4.]))\n"
+    "array([0.47213595, 1.        , 3.21110255, 4.94427191])\n"
+    "\n"
+    "The function can be calculated for different `delta` and `r` by\n"
+    "providing arrays for both with compatible shapes for broadcasting.\n"
+    "\n"
+    ">>> r = np.array([1., 2.5, 8., 10.])\n"
+    ">>> deltas = np.array([[1.], [5.], [9.]])\n"
+    ">>> print(r.shape, deltas.shape)\n"
+    "(4,) (3, 1)\n"
+    "\n"
+    ">>> pseudo_huber(deltas, r)\n"
+    "array([[ 0.41421356,  1.6925824 ,  7.06225775,  9.04987562],\n"
+    "       [ 0.49509757,  2.95084972, 22.16990566, 30.90169944],\n"
+    "       [ 0.49846624,  3.06693762, 27.37435121, 40.08261642]])\n"
+    "\n"
+    "Plot the function for different `delta`.\n"
+    "\n"
+    ">>> x = np.linspace(-4, 4, 500)\n"
+    ">>> deltas = [1, 2, 3]\n"
+    ">>> linestyles = [\"dashed\", \"dotted\", \"dashdot\"]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> combined_plot_parameters = list(zip(deltas, linestyles))\n"
+    ">>> for delta, style in combined_plot_parameters:\n"
+    "...     ax.plot(x, pseudo_huber(delta, x), label=rf\"$\\delta={delta}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(r\"Pseudo-Huber loss function $h_{\\delta}(x)$\")\n"
+    ">>> ax.set_xlim(-4, 4)\n"
+    ">>> ax.set_ylim(0, 8)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Finally, illustrate the difference between `huber` and `pseudo_huber` by\n"
+    "plotting them and their gradients with respect to `r`. The plot shows\n"
+    "that `pseudo_huber` is continuously differentiable while `huber` is not\n"
+    "at the points :math:`\\pm\\delta`.\n"
+    "\n"
+    ">>> def huber_grad(delta, x):\n"
+    "...     grad = np.copy(x)\n"
+    "...     linear_area = np.argwhere(np.abs(x) > delta)\n"
+    "...     grad[linear_area]=delta*np.sign(x[linear_area])\n"
+    "...     return grad\n"
+    ">>> def pseudo_huber_grad(delta, x):\n"
+    "...     return x* (1+(x/delta)**2)**(-0.5)\n"
+    ">>> x=np.linspace(-3, 3, 500)\n"
+    ">>> delta = 1.\n"
+    ">>> fig, ax = plt.subplots(figsize=(7, 7))\n"
+    ">>> ax.plot(x, huber(delta, x), label=\"Huber\", ls=\"dashed\")\n"
+    ">>> ax.plot(x, huber_grad(delta, x), label=\"Huber Gradient\", ls=\"dashdot\")\n"
+    ">>> ax.plot(x, pseudo_huber(delta, x), label=\"Pseudo-Huber\", ls=\"dotted\")\n"
+    ">>> ax.plot(x, pseudo_huber_grad(delta, x), label=\"Pseudo-Huber Gradient\",\n"
+    "...         ls=\"solid\")\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> plt.show()")
+ufunc_pseudo_huber_loops[0] = loop_d_dd__As_ff_f
+ufunc_pseudo_huber_loops[1] = loop_d_dd__As_dd_d
+ufunc_pseudo_huber_types[0] = NPY_FLOAT
+ufunc_pseudo_huber_types[1] = NPY_FLOAT
+ufunc_pseudo_huber_types[2] = NPY_FLOAT
+ufunc_pseudo_huber_types[3] = NPY_DOUBLE
+ufunc_pseudo_huber_types[4] = NPY_DOUBLE
+ufunc_pseudo_huber_types[5] = NPY_DOUBLE
+ufunc_pseudo_huber_ptr[2*0] = _func_pseudo_huber
+ufunc_pseudo_huber_ptr[2*0+1] = ("pseudo_huber")
+ufunc_pseudo_huber_ptr[2*1] = _func_pseudo_huber
+ufunc_pseudo_huber_ptr[2*1+1] = ("pseudo_huber")
+ufunc_pseudo_huber_data[0] = &ufunc_pseudo_huber_ptr[2*0]
+ufunc_pseudo_huber_data[1] = &ufunc_pseudo_huber_ptr[2*1]
+pseudo_huber = np.PyUFunc_FromFuncAndData(ufunc_pseudo_huber_loops, ufunc_pseudo_huber_data, ufunc_pseudo_huber_types, 2, 2, 1, 0, "pseudo_huber", ufunc_pseudo_huber_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_rel_entr_loops[2]
+cdef void *ufunc_rel_entr_ptr[4]
+cdef void *ufunc_rel_entr_data[2]
+cdef char ufunc_rel_entr_types[6]
+cdef char *ufunc_rel_entr_doc = (
+    "rel_entr(x, y, out=None)\n"
+    "\n"
+    "Elementwise function for computing relative entropy.\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\mathrm{rel\\_entr}(x, y) =\n"
+    "        \\begin{cases}\n"
+    "            x \\log(x / y) & x > 0, y > 0 \\\\\n"
+    "            0 & x = 0, y \\ge 0 \\\\\n"
+    "            \\infty & \\text{otherwise}\n"
+    "        \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Input arrays\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Relative entropy of the inputs\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "entr, kl_div, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is jointly convex in x and y.\n"
+    "\n"
+    "The origin of this function is in convex programming; see\n"
+    "[1]_. Given two discrete probability distributions :math:`p_1,\n"
+    "\\ldots, p_n` and :math:`q_1, \\ldots, q_n`, the definition of relative\n"
+    "entropy in the context of *information theory* is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\sum_{i = 1}^n \\mathrm{rel\\_entr}(p_i, q_i).\n"
+    "\n"
+    "To compute the latter quantity, use `scipy.stats.entropy`.\n"
+    "\n"
+    "See [2]_ for details.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`\n"
+    ".. [2] Kullback-Leibler divergence,\n"
+    "       https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence")
+ufunc_rel_entr_loops[0] = loop_d_dd__As_ff_f
+ufunc_rel_entr_loops[1] = loop_d_dd__As_dd_d
+ufunc_rel_entr_types[0] = NPY_FLOAT
+ufunc_rel_entr_types[1] = NPY_FLOAT
+ufunc_rel_entr_types[2] = NPY_FLOAT
+ufunc_rel_entr_types[3] = NPY_DOUBLE
+ufunc_rel_entr_types[4] = NPY_DOUBLE
+ufunc_rel_entr_types[5] = NPY_DOUBLE
+ufunc_rel_entr_ptr[2*0] = _func_rel_entr
+ufunc_rel_entr_ptr[2*0+1] = ("rel_entr")
+ufunc_rel_entr_ptr[2*1] = _func_rel_entr
+ufunc_rel_entr_ptr[2*1+1] = ("rel_entr")
+ufunc_rel_entr_data[0] = &ufunc_rel_entr_ptr[2*0]
+ufunc_rel_entr_data[1] = &ufunc_rel_entr_ptr[2*1]
+rel_entr = np.PyUFunc_FromFuncAndData(ufunc_rel_entr_loops, ufunc_rel_entr_data, ufunc_rel_entr_types, 2, 2, 1, 0, "rel_entr", ufunc_rel_entr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_round_loops[2]
+cdef void *ufunc_round_ptr[4]
+cdef void *ufunc_round_data[2]
+cdef char ufunc_round_types[4]
+cdef char *ufunc_round_doc = (
+    "round(x, out=None)\n"
+    "\n"
+    "Round to the nearest integer.\n"
+    "\n"
+    "Returns the nearest integer to `x`.  If `x` ends in 0.5 exactly,\n"
+    "the nearest even integer is chosen.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real valued input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The nearest integers to the elements of `x`. The result is of\n"
+    "    floating type, not integer type.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It rounds to even.\n"
+    "\n"
+    ">>> sc.round([0.5, 1.5])\n"
+    "array([0., 2.])")
+ufunc_round_loops[0] = loop_d_d__As_f_f
+ufunc_round_loops[1] = loop_d_d__As_d_d
+ufunc_round_types[0] = NPY_FLOAT
+ufunc_round_types[1] = NPY_FLOAT
+ufunc_round_types[2] = NPY_DOUBLE
+ufunc_round_types[3] = NPY_DOUBLE
+ufunc_round_ptr[2*0] = _func_cephes_round
+ufunc_round_ptr[2*0+1] = ("round")
+ufunc_round_ptr[2*1] = _func_cephes_round
+ufunc_round_ptr[2*1+1] = ("round")
+ufunc_round_data[0] = &ufunc_round_ptr[2*0]
+ufunc_round_data[1] = &ufunc_round_ptr[2*1]
+round = np.PyUFunc_FromFuncAndData(ufunc_round_loops, ufunc_round_data, ufunc_round_types, 2, 1, 1, 0, "round", ufunc_round_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_shichi_loops[4]
+cdef void *ufunc_shichi_ptr[8]
+cdef void *ufunc_shichi_data[4]
+cdef char ufunc_shichi_types[12]
+cdef char *ufunc_shichi_doc = (
+    "shichi(x, out=None)\n"
+    "\n"
+    "Hyperbolic sine and cosine integrals.\n"
+    "\n"
+    "The hyperbolic sine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\int_0^x \\frac{\\sinh{t}}{t}dt\n"
+    "\n"
+    "and the hyperbolic cosine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\gamma + \\log(x) + \\int_0^x \\frac{\\cosh{t} - 1}{t} dt\n"
+    "\n"
+    "where :math:`\\gamma` is Euler's constant and :math:`\\log` is the\n"
+    "principal branch of the logarithm [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex points at which to compute the hyperbolic sine\n"
+    "    and cosine integrals.\n"
+    "out : tuple of ndarray, optional\n"
+    "    Optional output arrays for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "si : scalar or ndarray\n"
+    "    Hyperbolic sine integral at ``x``\n"
+    "ci : scalar or ndarray\n"
+    "    Hyperbolic cosine integral at ``x``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "sici : Sine and cosine integrals.\n"
+    "exp1 : Exponential integral E1.\n"
+    "expi : Exponential integral Ei.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real arguments with ``x < 0``, ``chi`` is the real part of the\n"
+    "hyperbolic cosine integral. For such points ``chi(x)`` and ``chi(x\n"
+    "+ 0j)`` differ by a factor of ``1j*pi``.\n"
+    "\n"
+    "For real arguments the function is computed by calling Cephes'\n"
+    "[2]_ *shichi* routine. For complex arguments the algorithm is based\n"
+    "on Mpmath's [3]_ *shi* and *chi* routines.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "       (See Section 5.2.)\n"
+    ".. [2] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [3] Fredrik Johansson and others.\n"
+    "       \"mpmath: a Python library for arbitrary-precision floating-point\n"
+    "       arithmetic\" (Version 0.19) http://mpmath.org/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import shichi, sici\n"
+    "\n"
+    "`shichi` accepts real or complex input:\n"
+    "\n"
+    ">>> shichi(0.5)\n"
+    "(0.5069967498196671, -0.05277684495649357)\n"
+    ">>> shichi(0.5 + 2.5j)\n"
+    "((0.11772029666668238+1.831091777729851j),\n"
+    " (0.29912435887648825+1.7395351121166562j))\n"
+    "\n"
+    "The hyperbolic sine and cosine integrals Shi(z) and Chi(z) are\n"
+    "related to the sine and cosine integrals Si(z) and Ci(z) by\n"
+    "\n"
+    "* Shi(z) = -i*Si(i*z)\n"
+    "* Chi(z) = Ci(-i*z) + i*pi/2\n"
+    "\n"
+    ">>> z = 0.25 + 5j\n"
+    ">>> shi, chi = shichi(z)\n"
+    ">>> shi, -1j*sici(1j*z)[0]            # Should be the same.\n"
+    "((-0.04834719325101729+1.5469354086921228j),\n"
+    " (-0.04834719325101729+1.5469354086921228j))\n"
+    ">>> chi, sici(-1j*z)[1] + 1j*np.pi/2  # Should be the same.\n"
+    "((-0.19568708973868087+1.556276312103824j),\n"
+    " (-0.19568708973868087+1.556276312103824j))\n"
+    "\n"
+    "Plot the functions evaluated on the real axis:\n"
+    "\n"
+    ">>> xp = np.geomspace(1e-8, 4.0, 250)\n"
+    ">>> x = np.concatenate((-xp[::-1], xp))\n"
+    ">>> shi, chi = shichi(x)\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, shi, label='Shi(x)')\n"
+    ">>> ax.plot(x, chi, '--', label='Chi(x)')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('Hyperbolic Sine and Cosine Integrals')\n"
+    ">>> ax.legend(shadow=True, framealpha=1, loc='lower right')\n"
+    ">>> ax.grid(True)\n"
+    ">>> plt.show()")
+ufunc_shichi_loops[0] = loop_i_d_dd_As_f_ff
+ufunc_shichi_loops[1] = loop_i_d_dd_As_d_dd
+ufunc_shichi_loops[2] = loop_i_D_DD_As_F_FF
+ufunc_shichi_loops[3] = loop_i_D_DD_As_D_DD
+ufunc_shichi_types[0] = NPY_FLOAT
+ufunc_shichi_types[1] = NPY_FLOAT
+ufunc_shichi_types[2] = NPY_FLOAT
+ufunc_shichi_types[3] = NPY_DOUBLE
+ufunc_shichi_types[4] = NPY_DOUBLE
+ufunc_shichi_types[5] = NPY_DOUBLE
+ufunc_shichi_types[6] = NPY_CFLOAT
+ufunc_shichi_types[7] = NPY_CFLOAT
+ufunc_shichi_types[8] = NPY_CFLOAT
+ufunc_shichi_types[9] = NPY_CDOUBLE
+ufunc_shichi_types[10] = NPY_CDOUBLE
+ufunc_shichi_types[11] = NPY_CDOUBLE
+ufunc_shichi_ptr[2*0] = _func_xsf_shichi
+ufunc_shichi_ptr[2*0+1] = ("shichi")
+ufunc_shichi_ptr[2*1] = _func_xsf_shichi
+ufunc_shichi_ptr[2*1+1] = ("shichi")
+ufunc_shichi_ptr[2*2] = _func_xsf_cshichi
+ufunc_shichi_ptr[2*2+1] = ("shichi")
+ufunc_shichi_ptr[2*3] = _func_xsf_cshichi
+ufunc_shichi_ptr[2*3+1] = ("shichi")
+ufunc_shichi_data[0] = &ufunc_shichi_ptr[2*0]
+ufunc_shichi_data[1] = &ufunc_shichi_ptr[2*1]
+ufunc_shichi_data[2] = &ufunc_shichi_ptr[2*2]
+ufunc_shichi_data[3] = &ufunc_shichi_ptr[2*3]
+shichi = np.PyUFunc_FromFuncAndData(ufunc_shichi_loops, ufunc_shichi_data, ufunc_shichi_types, 4, 1, 2, 0, "shichi", ufunc_shichi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_sici_loops[4]
+cdef void *ufunc_sici_ptr[8]
+cdef void *ufunc_sici_data[4]
+cdef char ufunc_sici_types[12]
+cdef char *ufunc_sici_doc = (
+    "sici(x, out=None)\n"
+    "\n"
+    "Sine and cosine integrals.\n"
+    "\n"
+    "The sine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\int_0^x \\frac{\\sin{t}}{t}dt\n"
+    "\n"
+    "and the cosine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\gamma + \\log(x) + \\int_0^x \\frac{\\cos{t} - 1}{t}dt\n"
+    "\n"
+    "where :math:`\\gamma` is Euler's constant and :math:`\\log` is the\n"
+    "principal branch of the logarithm [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex points at which to compute the sine and cosine\n"
+    "    integrals.\n"
+    "out : tuple of ndarray, optional\n"
+    "    Optional output arrays for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "si : scalar or ndarray\n"
+    "    Sine integral at ``x``\n"
+    "ci : scalar or ndarray\n"
+    "    Cosine integral at ``x``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "shichi : Hyperbolic sine and cosine integrals.\n"
+    "exp1 : Exponential integral E1.\n"
+    "expi : Exponential integral Ei.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real arguments with ``x < 0``, ``ci`` is the real part of the\n"
+    "cosine integral. For such points ``ci(x)`` and ``ci(x + 0j)``\n"
+    "differ by a factor of ``1j*pi``.\n"
+    "\n"
+    "For real arguments the function is computed by calling Cephes'\n"
+    "[2]_ *sici* routine. For complex arguments the algorithm is based\n"
+    "on Mpmath's [3]_ *si* and *ci* routines.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "       (See Section 5.2.)\n"
+    ".. [2] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [3] Fredrik Johansson and others.\n"
+    "       \"mpmath: a Python library for arbitrary-precision floating-point\n"
+    "       arithmetic\" (Version 0.19) http://mpmath.org/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import sici, exp1\n"
+    "\n"
+    "`sici` accepts real or complex input:\n"
+    "\n"
+    ">>> sici(2.5)\n"
+    "(1.7785201734438267, 0.2858711963653835)\n"
+    ">>> sici(2.5 + 3j)\n"
+    "((4.505735874563953+0.06863305018999577j),\n"
+    "(0.0793644206906966-2.935510262937543j))\n"
+    "\n"
+    "For z in the right half plane, the sine and cosine integrals are\n"
+    "related to the exponential integral E1 (implemented in SciPy as\n"
+    "`scipy.special.exp1`) by\n"
+    "\n"
+    "* Si(z) = (E1(i*z) - E1(-i*z))/2i + pi/2\n"
+    "* Ci(z) = -(E1(i*z) + E1(-i*z))/2\n"
+    "\n"
+    "See [1]_ (equations 5.2.21 and 5.2.23).\n"
+    "\n"
+    "We can verify these relations:\n"
+    "\n"
+    ">>> z = 2 - 3j\n"
+    ">>> sici(z)\n"
+    "((4.54751388956229-1.3991965806460565j),\n"
+    "(1.408292501520851+2.9836177420296055j))\n"
+    "\n"
+    ">>> (exp1(1j*z) - exp1(-1j*z))/2j + np.pi/2  # Same as sine integral\n"
+    "(4.54751388956229-1.3991965806460565j)\n"
+    "\n"
+    ">>> -(exp1(1j*z) + exp1(-1j*z))/2            # Same as cosine integral\n"
+    "(1.408292501520851+2.9836177420296055j)\n"
+    "\n"
+    "Plot the functions evaluated on the real axis; the dotted horizontal\n"
+    "lines are at pi/2 and -pi/2:\n"
+    "\n"
+    ">>> x = np.linspace(-16, 16, 150)\n"
+    ">>> si, ci = sici(x)\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, si, label='Si(x)')\n"
+    ">>> ax.plot(x, ci, '--', label='Ci(x)')\n"
+    ">>> ax.legend(shadow=True, framealpha=1, loc='upper left')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('Sine and Cosine Integrals')\n"
+    ">>> ax.axhline(np.pi/2, linestyle=':', alpha=0.5, color='k')\n"
+    ">>> ax.axhline(-np.pi/2, linestyle=':', alpha=0.5, color='k')\n"
+    ">>> ax.grid(True)\n"
+    ">>> plt.show()")
+ufunc_sici_loops[0] = loop_i_d_dd_As_f_ff
+ufunc_sici_loops[1] = loop_i_d_dd_As_d_dd
+ufunc_sici_loops[2] = loop_i_D_DD_As_F_FF
+ufunc_sici_loops[3] = loop_i_D_DD_As_D_DD
+ufunc_sici_types[0] = NPY_FLOAT
+ufunc_sici_types[1] = NPY_FLOAT
+ufunc_sici_types[2] = NPY_FLOAT
+ufunc_sici_types[3] = NPY_DOUBLE
+ufunc_sici_types[4] = NPY_DOUBLE
+ufunc_sici_types[5] = NPY_DOUBLE
+ufunc_sici_types[6] = NPY_CFLOAT
+ufunc_sici_types[7] = NPY_CFLOAT
+ufunc_sici_types[8] = NPY_CFLOAT
+ufunc_sici_types[9] = NPY_CDOUBLE
+ufunc_sici_types[10] = NPY_CDOUBLE
+ufunc_sici_types[11] = NPY_CDOUBLE
+ufunc_sici_ptr[2*0] = _func_xsf_sici
+ufunc_sici_ptr[2*0+1] = ("sici")
+ufunc_sici_ptr[2*1] = _func_xsf_sici
+ufunc_sici_ptr[2*1+1] = ("sici")
+ufunc_sici_ptr[2*2] = _func_xsf_csici
+ufunc_sici_ptr[2*2+1] = ("sici")
+ufunc_sici_ptr[2*3] = _func_xsf_csici
+ufunc_sici_ptr[2*3+1] = ("sici")
+ufunc_sici_data[0] = &ufunc_sici_ptr[2*0]
+ufunc_sici_data[1] = &ufunc_sici_ptr[2*1]
+ufunc_sici_data[2] = &ufunc_sici_ptr[2*2]
+ufunc_sici_data[3] = &ufunc_sici_ptr[2*3]
+sici = np.PyUFunc_FromFuncAndData(ufunc_sici_loops, ufunc_sici_data, ufunc_sici_types, 4, 1, 2, 0, "sici", ufunc_sici_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_smirnov_loops[3]
+cdef void *ufunc_smirnov_ptr[6]
+cdef void *ufunc_smirnov_data[3]
+cdef char ufunc_smirnov_types[9]
+cdef char *ufunc_smirnov_doc = (
+    "smirnov(n, d, out=None)\n"
+    "\n"
+    "Kolmogorov-Smirnov complementary cumulative distribution function\n"
+    "\n"
+    "Returns the exact Kolmogorov-Smirnov complementary cumulative\n"
+    "distribution function,(aka the Survival Function) of Dn+ (or Dn-)\n"
+    "for a one-sided test of equality between an empirical and a\n"
+    "theoretical distribution. It is equal to the probability that the\n"
+    "maximum difference between a theoretical distribution and an empirical\n"
+    "one based on `n` samples is greater than d.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "  Number of samples\n"
+    "d : float array_like\n"
+    "  Deviation between the Empirical CDF (ECDF) and the target CDF.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of smirnov(n, d), Prob(Dn+ >= d) (Also Prob(Dn- >= d))\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "smirnovi : The Inverse Survival Function for the distribution\n"
+    "scipy.stats.ksone : Provides the functionality as a continuous distribution\n"
+    "kolmogorov, kolmogi : Functions for the two-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`smirnov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.ksone` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import smirnov\n"
+    ">>> from scipy.stats import norm\n"
+    "\n"
+    "Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a\n"
+    "sample of size 5.\n"
+    "\n"
+    ">>> smirnov(5, [0, 0.5, 1.0])\n"
+    "array([ 1.   ,  0.056,  0.   ])\n"
+    "\n"
+    "Compare a sample of size 5 against N(0, 1), the standard normal\n"
+    "distribution with mean 0 and standard deviation 1.\n"
+    "\n"
+    "`x` is the sample.\n"
+    "\n"
+    ">>> x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82])\n"
+    "\n"
+    ">>> target = norm(0, 1)\n"
+    ">>> cdfs = target.cdf(x)\n"
+    ">>> cdfs\n"
+    "array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ])\n"
+    "\n"
+    "Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn).\n"
+    "\n"
+    ">>> n = len(x)\n"
+    ">>> ecdfs = np.arange(n+1, dtype=float)/n\n"
+    ">>> cols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n],\n"
+    "...                        ecdfs[1:] - cdfs])\n"
+    ">>> with np.printoptions(precision=3):\n"
+    "...    print(cols)\n"
+    "[[-1.392  0.2    0.082  0.082  0.118]\n"
+    " [-0.135  0.4    0.446  0.246 -0.046]\n"
+    " [ 0.114  0.6    0.545  0.145  0.055]\n"
+    " [ 0.19   0.8    0.575 -0.025  0.225]\n"
+    " [ 1.82   1.     0.966  0.166  0.034]]\n"
+    ">>> gaps = cols[:, -2:]\n"
+    ">>> Dnpm = np.max(gaps, axis=0)\n"
+    ">>> print(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}')\n"
+    "Dn-=0.246306, Dn+=0.224655\n"
+    ">>> probs = smirnov(n, Dnpm)\n"
+    ">>> print(f'For a sample of size {n} drawn from N(0, 1):',\n"
+    "...       f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}',\n"
+    "...       f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}',\n"
+    "...       sep='\\n')\n"
+    "For a sample of size 5 drawn from N(0, 1):\n"
+    " Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711\n"
+    " Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245\n"
+    "\n"
+    "Plot the empirical CDF and the standard normal CDF.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> plt.step(np.concatenate(([-2.5], x, [2.5])),\n"
+    "...          np.concatenate((ecdfs, [1])),\n"
+    "...          where='post', label='Empirical CDF')\n"
+    ">>> xx = np.linspace(-2.5, 2.5, 100)\n"
+    ">>> plt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)')\n"
+    "\n"
+    "Add vertical lines marking Dn+ and Dn-.\n"
+    "\n"
+    ">>> iminus, iplus = np.argmax(gaps, axis=0)\n"
+    ">>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r',\n"
+    "...            alpha=0.5, lw=4)\n"
+    ">>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m',\n"
+    "...            alpha=0.5, lw=4)\n"
+    "\n"
+    ">>> plt.grid(True)\n"
+    ">>> plt.legend(framealpha=1, shadow=True)\n"
+    ">>> plt.show()")
+ufunc_smirnov_loops[0] = loop_d_pd__As_pd_d
+ufunc_smirnov_loops[1] = loop_d_dd__As_ff_f
+ufunc_smirnov_loops[2] = loop_d_dd__As_dd_d
+ufunc_smirnov_types[0] = NPY_INTP
+ufunc_smirnov_types[1] = NPY_DOUBLE
+ufunc_smirnov_types[2] = NPY_DOUBLE
+ufunc_smirnov_types[3] = NPY_FLOAT
+ufunc_smirnov_types[4] = NPY_FLOAT
+ufunc_smirnov_types[5] = NPY_FLOAT
+ufunc_smirnov_types[6] = NPY_DOUBLE
+ufunc_smirnov_types[7] = NPY_DOUBLE
+ufunc_smirnov_types[8] = NPY_DOUBLE
+ufunc_smirnov_ptr[2*0] = _func_cephes_smirnov_wrap
+ufunc_smirnov_ptr[2*0+1] = ("smirnov")
+ufunc_smirnov_ptr[2*1] = _func_smirnov_unsafe
+ufunc_smirnov_ptr[2*1+1] = ("smirnov")
+ufunc_smirnov_ptr[2*2] = _func_smirnov_unsafe
+ufunc_smirnov_ptr[2*2+1] = ("smirnov")
+ufunc_smirnov_data[0] = &ufunc_smirnov_ptr[2*0]
+ufunc_smirnov_data[1] = &ufunc_smirnov_ptr[2*1]
+ufunc_smirnov_data[2] = &ufunc_smirnov_ptr[2*2]
+smirnov = np.PyUFunc_FromFuncAndData(ufunc_smirnov_loops, ufunc_smirnov_data, ufunc_smirnov_types, 3, 2, 1, 0, "smirnov", ufunc_smirnov_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_smirnovi_loops[3]
+cdef void *ufunc_smirnovi_ptr[6]
+cdef void *ufunc_smirnovi_data[3]
+cdef char ufunc_smirnovi_types[9]
+cdef char *ufunc_smirnovi_doc = (
+    "smirnovi(n, p, out=None)\n"
+    "\n"
+    "Inverse to `smirnov`\n"
+    "\n"
+    "Returns `d` such that ``smirnov(n, d) == p``, the critical value\n"
+    "corresponding to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "  Number of samples\n"
+    "p : float array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of smirnovi(n, p), the critical values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "smirnov : The Survival Function (SF) for the distribution\n"
+    "scipy.stats.ksone : Provides the functionality as a continuous distribution\n"
+    "kolmogorov, kolmogi : Functions for the two-sided distribution\n"
+    "scipy.stats.kstwobign : Two-sided Kolmogorov-Smirnov distribution, large n\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`smirnov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.ksone` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import smirnovi, smirnov\n"
+    "\n"
+    ">>> n = 24\n"
+    ">>> deviations = [0.1, 0.2, 0.3]\n"
+    "\n"
+    "Use `smirnov` to compute the complementary CDF of the Smirnov\n"
+    "distribution for the given number of samples and deviations.\n"
+    "\n"
+    ">>> p = smirnov(n, deviations)\n"
+    ">>> p\n"
+    "array([0.58105083, 0.12826832, 0.01032231])\n"
+    "\n"
+    "The inverse function ``smirnovi(n, p)`` returns ``deviations``.\n"
+    "\n"
+    ">>> smirnovi(n, p)\n"
+    "array([0.1, 0.2, 0.3])")
+ufunc_smirnovi_loops[0] = loop_d_pd__As_pd_d
+ufunc_smirnovi_loops[1] = loop_d_dd__As_ff_f
+ufunc_smirnovi_loops[2] = loop_d_dd__As_dd_d
+ufunc_smirnovi_types[0] = NPY_INTP
+ufunc_smirnovi_types[1] = NPY_DOUBLE
+ufunc_smirnovi_types[2] = NPY_DOUBLE
+ufunc_smirnovi_types[3] = NPY_FLOAT
+ufunc_smirnovi_types[4] = NPY_FLOAT
+ufunc_smirnovi_types[5] = NPY_FLOAT
+ufunc_smirnovi_types[6] = NPY_DOUBLE
+ufunc_smirnovi_types[7] = NPY_DOUBLE
+ufunc_smirnovi_types[8] = NPY_DOUBLE
+ufunc_smirnovi_ptr[2*0] = _func_cephes_smirnovi_wrap
+ufunc_smirnovi_ptr[2*0+1] = ("smirnovi")
+ufunc_smirnovi_ptr[2*1] = _func_smirnovi_unsafe
+ufunc_smirnovi_ptr[2*1+1] = ("smirnovi")
+ufunc_smirnovi_ptr[2*2] = _func_smirnovi_unsafe
+ufunc_smirnovi_ptr[2*2+1] = ("smirnovi")
+ufunc_smirnovi_data[0] = &ufunc_smirnovi_ptr[2*0]
+ufunc_smirnovi_data[1] = &ufunc_smirnovi_ptr[2*1]
+ufunc_smirnovi_data[2] = &ufunc_smirnovi_ptr[2*2]
+smirnovi = np.PyUFunc_FromFuncAndData(ufunc_smirnovi_loops, ufunc_smirnovi_data, ufunc_smirnovi_types, 3, 2, 1, 0, "smirnovi", ufunc_smirnovi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_spence_loops[4]
+cdef void *ufunc_spence_ptr[8]
+cdef void *ufunc_spence_data[4]
+cdef char ufunc_spence_types[8]
+cdef char *ufunc_spence_doc = (
+    "spence(z, out=None)\n"
+    "\n"
+    "Spence's function, also known as the dilogarithm.\n"
+    "\n"
+    "It is defined to be\n"
+    "\n"
+    ".. math::\n"
+    "  \\int_1^z \\frac{\\log(t)}{1 - t}dt\n"
+    "\n"
+    "for complex :math:`z`, where the contour of integration is taken\n"
+    "to avoid the branch cut of the logarithm. Spence's function is\n"
+    "analytic everywhere except the negative real axis where it has a\n"
+    "branch cut.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Points at which to evaluate Spence's function\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "s : scalar or ndarray\n"
+    "    Computed values of Spence's function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "There is a different convention which defines Spence's function by\n"
+    "the integral\n"
+    "\n"
+    ".. math::\n"
+    "  -\\int_0^z \\frac{\\log(1 - t)}{t}dt;\n"
+    "\n"
+    "this is our ``spence(1 - z)``.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import spence\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "The function is defined for complex inputs:\n"
+    "\n"
+    ">>> spence([1-1j, 1.5+2j, 3j, -10-5j])\n"
+    "array([-0.20561676+0.91596559j, -0.86766909-1.39560134j,\n"
+    "       -0.59422064-2.49129918j, -1.14044398+6.80075924j])\n"
+    "\n"
+    "For complex inputs on the branch cut, which is the negative real axis,\n"
+    "the function returns the limit for ``z`` with positive imaginary part.\n"
+    "For example, in the following, note the sign change of the imaginary\n"
+    "part of the output for ``z = -2`` and ``z = -2 - 1e-8j``:\n"
+    "\n"
+    ">>> spence([-2 + 1e-8j, -2, -2 - 1e-8j])\n"
+    "array([2.32018041-3.45139229j, 2.32018042-3.4513923j ,\n"
+    "       2.32018041+3.45139229j])\n"
+    "\n"
+    "The function returns ``nan`` for real inputs on the branch cut:\n"
+    "\n"
+    ">>> spence(-1.5)\n"
+    "nan\n"
+    "\n"
+    "Verify some particular values: ``spence(0) = pi**2/6``,\n"
+    "``spence(1) = 0`` and ``spence(2) = -pi**2/12``.\n"
+    "\n"
+    ">>> spence([0, 1, 2])\n"
+    "array([ 1.64493407,  0.        , -0.82246703])\n"
+    ">>> np.pi**2/6, -np.pi**2/12\n"
+    "(1.6449340668482264, -0.8224670334241132)\n"
+    "\n"
+    "Verify the identity::\n"
+    "\n"
+    "    spence(z) + spence(1 - z) = pi**2/6 - log(z)*log(1 - z)\n"
+    "\n"
+    ">>> z = 3 + 4j\n"
+    ">>> spence(z) + spence(1 - z)\n"
+    "(-2.6523186143876067+1.8853470951513935j)\n"
+    ">>> np.pi**2/6 - np.log(z)*np.log(1 - z)\n"
+    "(-2.652318614387606+1.885347095151394j)\n"
+    "\n"
+    "Plot the function for positive real input.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(0, 6, 400)\n"
+    ">>> ax.plot(x, spence(x))\n"
+    ">>> ax.grid()\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('spence(x)')\n"
+    ">>> plt.show()")
+ufunc_spence_loops[0] = loop_d_d__As_f_f
+ufunc_spence_loops[1] = loop_d_d__As_d_d
+ufunc_spence_loops[2] = loop_D_D__As_F_F
+ufunc_spence_loops[3] = loop_D_D__As_D_D
+ufunc_spence_types[0] = NPY_FLOAT
+ufunc_spence_types[1] = NPY_FLOAT
+ufunc_spence_types[2] = NPY_DOUBLE
+ufunc_spence_types[3] = NPY_DOUBLE
+ufunc_spence_types[4] = NPY_CFLOAT
+ufunc_spence_types[5] = NPY_CFLOAT
+ufunc_spence_types[6] = NPY_CDOUBLE
+ufunc_spence_types[7] = NPY_CDOUBLE
+ufunc_spence_ptr[2*0] = _func_cephes_spence
+ufunc_spence_ptr[2*0+1] = ("spence")
+ufunc_spence_ptr[2*1] = _func_cephes_spence
+ufunc_spence_ptr[2*1+1] = ("spence")
+ufunc_spence_ptr[2*2] = _func_cspence
+ufunc_spence_ptr[2*2+1] = ("spence")
+ufunc_spence_ptr[2*3] = _func_cspence
+ufunc_spence_ptr[2*3+1] = ("spence")
+ufunc_spence_data[0] = &ufunc_spence_ptr[2*0]
+ufunc_spence_data[1] = &ufunc_spence_ptr[2*1]
+ufunc_spence_data[2] = &ufunc_spence_ptr[2*2]
+ufunc_spence_data[3] = &ufunc_spence_ptr[2*3]
+spence = np.PyUFunc_FromFuncAndData(ufunc_spence_loops, ufunc_spence_data, ufunc_spence_types, 4, 1, 1, 0, "spence", ufunc_spence_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtr_loops[2]
+cdef void *ufunc_stdtr_ptr[4]
+cdef void *ufunc_stdtr_data[2]
+cdef char ufunc_stdtr_types[6]
+cdef char *ufunc_stdtr_doc = (
+    "stdtr(df, t, out=None)\n"
+    "\n"
+    "Student t distribution cumulative distribution function\n"
+    "\n"
+    "Returns the integral:\n"
+    "\n"
+    ".. math::\n"
+    "    \\frac{\\Gamma((df+1)/2)}{\\sqrt{\\pi df} \\Gamma(df/2)}\n"
+    "    \\int_{-\\infty}^t (1+x^2/df)^{-(df+1)/2}\\, dx\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom\n"
+    "t : array_like\n"
+    "    Upper bound of the integral\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Student t CDF at t\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtridf : inverse of stdtr with respect to `df`\n"
+    "stdtrit : inverse of stdtr with respect to `t`\n"
+    "scipy.stats.t : student t distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The student t distribution is also available as `scipy.stats.t`.\n"
+    "Calling `stdtr` directly can improve performance compared to the\n"
+    "``cdf`` method of `scipy.stats.t` (see last example below).\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``df=3`` at ``t=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import stdtr\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> stdtr(3, 1)\n"
+    "0.8044988905221148\n"
+    "\n"
+    "Plot the function for three different degrees of freedom.\n"
+    "\n"
+    ">>> x = np.linspace(-10, 10, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> parameters = [(1, \"solid\"), (3, \"dashed\"), (10, \"dotted\")]\n"
+    ">>> for (df, linestyle) in parameters:\n"
+    "...     ax.plot(x, stdtr(df, x), ls=linestyle, label=f\"$df={df}$\")\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_title(\"Student t distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The function can be computed for several degrees of freedom at the same\n"
+    "time by providing a NumPy array or list for `df`:\n"
+    "\n"
+    ">>> stdtr([1, 2, 3], 1)\n"
+    "array([0.75      , 0.78867513, 0.80449889])\n"
+    "\n"
+    "It is possible to calculate the function at several points for several\n"
+    "different degrees of freedom simultaneously by providing arrays for `df`\n"
+    "and `t` with shapes compatible for broadcasting. Compute `stdtr` at\n"
+    "4 points for 3 degrees of freedom resulting in an array of shape 3x4.\n"
+    "\n"
+    ">>> dfs = np.array([[1], [2], [3]])\n"
+    ">>> t = np.array([2, 4, 6, 8])\n"
+    ">>> dfs.shape, t.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> stdtr(dfs, t)\n"
+    "array([[0.85241638, 0.92202087, 0.94743154, 0.96041658],\n"
+    "       [0.90824829, 0.97140452, 0.98666426, 0.99236596],\n"
+    "       [0.93033702, 0.98599577, 0.99536364, 0.99796171]])\n"
+    "\n"
+    "The t distribution is also available as `scipy.stats.t`. Calling `stdtr`\n"
+    "directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.t`. To get the same results, one must use the following\n"
+    "parametrization: ``scipy.stats.t(df).cdf(x) = stdtr(df, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import t\n"
+    ">>> df, x = 3, 1\n"
+    ">>> stdtr_result = stdtr(df, x)  # this can be faster than below\n"
+    ">>> stats_result = t(df).cdf(x)\n"
+    ">>> stats_result == stdtr_result  # test that results are equal\n"
+    "True")
+ufunc_stdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtr_types[0] = NPY_FLOAT
+ufunc_stdtr_types[1] = NPY_FLOAT
+ufunc_stdtr_types[2] = NPY_FLOAT
+ufunc_stdtr_types[3] = NPY_DOUBLE
+ufunc_stdtr_types[4] = NPY_DOUBLE
+ufunc_stdtr_types[5] = NPY_DOUBLE
+ufunc_stdtr_ptr[2*0] = _func_stdtr
+ufunc_stdtr_ptr[2*0+1] = ("stdtr")
+ufunc_stdtr_ptr[2*1] = _func_stdtr
+ufunc_stdtr_ptr[2*1+1] = ("stdtr")
+ufunc_stdtr_data[0] = &ufunc_stdtr_ptr[2*0]
+ufunc_stdtr_data[1] = &ufunc_stdtr_ptr[2*1]
+stdtr = np.PyUFunc_FromFuncAndData(ufunc_stdtr_loops, ufunc_stdtr_data, ufunc_stdtr_types, 2, 2, 1, 0, "stdtr", ufunc_stdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtridf_loops[2]
+cdef void *ufunc_stdtridf_ptr[4]
+cdef void *ufunc_stdtridf_data[2]
+cdef char ufunc_stdtridf_types[6]
+cdef char *ufunc_stdtridf_doc = (
+    "stdtridf(p, t, out=None)\n"
+    "\n"
+    "Inverse of `stdtr` vs df\n"
+    "\n"
+    "Returns the argument df such that stdtr(df, t) is equal to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "t : array_like\n"
+    "    Upper bound of the integral\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    Value of `df` such that ``stdtr(df, t) == p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtr : Student t CDF\n"
+    "stdtrit : inverse of stdtr with respect to `t`\n"
+    "scipy.stats.t : Student t distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the student t cumulative distribution function for one\n"
+    "parameter set.\n"
+    "\n"
+    ">>> from scipy.special import stdtr, stdtridf\n"
+    ">>> df, x = 5, 2\n"
+    ">>> cdf_value = stdtr(df, x)\n"
+    ">>> cdf_value\n"
+    "0.9490302605850709\n"
+    "\n"
+    "Verify that `stdtridf` recovers the original value for `df` given\n"
+    "the CDF value and `x`.\n"
+    "\n"
+    ">>> stdtridf(cdf_value, x)\n"
+    "5.0")
+ufunc_stdtridf_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtridf_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtridf_types[0] = NPY_FLOAT
+ufunc_stdtridf_types[1] = NPY_FLOAT
+ufunc_stdtridf_types[2] = NPY_FLOAT
+ufunc_stdtridf_types[3] = NPY_DOUBLE
+ufunc_stdtridf_types[4] = NPY_DOUBLE
+ufunc_stdtridf_types[5] = NPY_DOUBLE
+ufunc_stdtridf_ptr[2*0] = _func_stdtridf
+ufunc_stdtridf_ptr[2*0+1] = ("stdtridf")
+ufunc_stdtridf_ptr[2*1] = _func_stdtridf
+ufunc_stdtridf_ptr[2*1+1] = ("stdtridf")
+ufunc_stdtridf_data[0] = &ufunc_stdtridf_ptr[2*0]
+ufunc_stdtridf_data[1] = &ufunc_stdtridf_ptr[2*1]
+stdtridf = np.PyUFunc_FromFuncAndData(ufunc_stdtridf_loops, ufunc_stdtridf_data, ufunc_stdtridf_types, 2, 2, 1, 0, "stdtridf", ufunc_stdtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtrit_loops[2]
+cdef void *ufunc_stdtrit_ptr[4]
+cdef void *ufunc_stdtrit_data[2]
+cdef char ufunc_stdtrit_types[6]
+cdef char *ufunc_stdtrit_doc = (
+    "stdtrit(df, p, out=None)\n"
+    "\n"
+    "The `p`-th quantile of the student t distribution.\n"
+    "\n"
+    "This function is the inverse of the student t distribution cumulative\n"
+    "distribution function (CDF), returning `t` such that `stdtr(df, t) = p`.\n"
+    "\n"
+    "Returns the argument `t` such that stdtr(df, t) is equal to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t : scalar or ndarray\n"
+    "    Value of `t` such that ``stdtr(df, t) == p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtr : Student t CDF\n"
+    "stdtridf : inverse of stdtr with respect to `df`\n"
+    "scipy.stats.t : Student t distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The student t distribution is also available as `scipy.stats.t`. Calling\n"
+    "`stdtrit` directly can improve performance compared to the ``ppf``\n"
+    "method of `scipy.stats.t` (see last example below).\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`stdtrit` represents the inverse of the student t distribution CDF which\n"
+    "is available as `stdtr`. Here, we calculate the CDF for ``df`` at\n"
+    "``x=1``. `stdtrit` then returns ``1`` up to floating point errors\n"
+    "given the same value for `df` and the computed CDF value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import stdtr, stdtrit\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> df = 3\n"
+    ">>> x = 1\n"
+    ">>> cdf_value = stdtr(df, x)\n"
+    ">>> stdtrit(df, cdf_value)\n"
+    "0.9999999994418539\n"
+    "\n"
+    "Plot the function for three different degrees of freedom.\n"
+    "\n"
+    ">>> x = np.linspace(0, 1, 1000)\n"
+    ">>> parameters = [(1, \"solid\"), (2, \"dashed\"), (5, \"dotted\")]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for (df, linestyle) in parameters:\n"
+    "...     ax.plot(x, stdtrit(df, x), ls=linestyle, label=f\"$df={df}$\")\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylim(-10, 10)\n"
+    ">>> ax.set_title(\"Student t distribution quantile function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The function can be computed for several degrees of freedom at the same\n"
+    "time by providing a NumPy array or list for `df`:\n"
+    "\n"
+    ">>> stdtrit([1, 2, 3], 0.7)\n"
+    "array([0.72654253, 0.6172134 , 0.58438973])\n"
+    "\n"
+    "It is possible to calculate the function at several points for several\n"
+    "different degrees of freedom simultaneously by providing arrays for `df`\n"
+    "and `p` with shapes compatible for broadcasting. Compute `stdtrit` at\n"
+    "4 points for 3 degrees of freedom resulting in an array of shape 3x4.\n"
+    "\n"
+    ">>> dfs = np.array([[1], [2], [3]])\n"
+    ">>> p = np.array([0.2, 0.4, 0.7, 0.8])\n"
+    ">>> dfs.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> stdtrit(dfs, p)\n"
+    "array([[-1.37638192, -0.3249197 ,  0.72654253,  1.37638192],\n"
+    "       [-1.06066017, -0.28867513,  0.6172134 ,  1.06066017],\n"
+    "       [-0.97847231, -0.27667066,  0.58438973,  0.97847231]])\n"
+    "\n"
+    "The t distribution is also available as `scipy.stats.t`. Calling `stdtrit`\n"
+    "directly can be much faster than calling the ``ppf`` method of\n"
+    "`scipy.stats.t`. To get the same results, one must use the following\n"
+    "parametrization: ``scipy.stats.t(df).ppf(x) = stdtrit(df, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import t\n"
+    ">>> df, x = 3, 0.5\n"
+    ">>> stdtrit_result = stdtrit(df, x)  # this can be faster than below\n"
+    ">>> stats_result = t(df).ppf(x)\n"
+    ">>> stats_result == stdtrit_result  # test that results are equal\n"
+    "True")
+ufunc_stdtrit_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtrit_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtrit_types[0] = NPY_FLOAT
+ufunc_stdtrit_types[1] = NPY_FLOAT
+ufunc_stdtrit_types[2] = NPY_FLOAT
+ufunc_stdtrit_types[3] = NPY_DOUBLE
+ufunc_stdtrit_types[4] = NPY_DOUBLE
+ufunc_stdtrit_types[5] = NPY_DOUBLE
+ufunc_stdtrit_ptr[2*0] = _func_stdtrit
+ufunc_stdtrit_ptr[2*0+1] = ("stdtrit")
+ufunc_stdtrit_ptr[2*1] = _func_stdtrit
+ufunc_stdtrit_ptr[2*1+1] = ("stdtrit")
+ufunc_stdtrit_data[0] = &ufunc_stdtrit_ptr[2*0]
+ufunc_stdtrit_data[1] = &ufunc_stdtrit_ptr[2*1]
+stdtrit = np.PyUFunc_FromFuncAndData(ufunc_stdtrit_loops, ufunc_stdtrit_data, ufunc_stdtrit_types, 2, 2, 1, 0, "stdtrit", ufunc_stdtrit_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_tklmbda_loops[2]
+cdef void *ufunc_tklmbda_ptr[4]
+cdef void *ufunc_tklmbda_data[2]
+cdef char ufunc_tklmbda_types[6]
+cdef char *ufunc_tklmbda_doc = (
+    "tklmbda(x, lmbda, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the Tukey lambda distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, lmbda : array_like\n"
+    "    Parameters\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    Value of the Tukey lambda CDF\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.tukeylambda : Tukey lambda distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import tklmbda, expit\n"
+    "\n"
+    "Compute the cumulative distribution function (CDF) of the Tukey lambda\n"
+    "distribution at several ``x`` values for `lmbda` = -1.5.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 9)\n"
+    ">>> x\n"
+    "array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])\n"
+    ">>> tklmbda(x, -1.5)\n"
+    "array([0.34688734, 0.3786554 , 0.41528805, 0.45629737, 0.5       ,\n"
+    "       0.54370263, 0.58471195, 0.6213446 , 0.65311266])\n"
+    "\n"
+    "When `lmbda` is 0, the function is the logistic sigmoid function,\n"
+    "which is implemented in `scipy.special` as `expit`.\n"
+    "\n"
+    ">>> tklmbda(x, 0)\n"
+    "array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,\n"
+    "       0.62245933, 0.73105858, 0.81757448, 0.88079708])\n"
+    ">>> expit(x)\n"
+    "array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,\n"
+    "       0.62245933, 0.73105858, 0.81757448, 0.88079708])\n"
+    "\n"
+    "When `lmbda` is 1, the Tukey lambda distribution is uniform on the\n"
+    "interval [-1, 1], so the CDF increases linearly.\n"
+    "\n"
+    ">>> t = np.linspace(-1, 1, 9)\n"
+    ">>> tklmbda(t, 1)\n"
+    "array([0.   , 0.125, 0.25 , 0.375, 0.5  , 0.625, 0.75 , 0.875, 1.   ])\n"
+    "\n"
+    "In the following, we generate plots for several values of `lmbda`.\n"
+    "\n"
+    "The first figure shows graphs for `lmbda` <= 0.\n"
+    "\n"
+    ">>> styles = ['-', '-.', '--', ':']\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(-12, 12, 500)\n"
+    ">>> for k, lmbda in enumerate([-1.0, -0.5, 0.0]):\n"
+    "...     y = tklmbda(x, lmbda)\n"
+    "...     ax.plot(x, y, styles[k], label=rf'$\\lambda$ = {lmbda:-4.1f}')\n"
+    "\n"
+    ">>> ax.set_title(r'tklmbda(x, $\\lambda$)')\n"
+    ">>> ax.set_label('x')\n"
+    ">>> ax.legend(framealpha=1, shadow=True)\n"
+    ">>> ax.grid(True)\n"
+    "\n"
+    "The second figure shows graphs for `lmbda` > 0.  The dots in the\n"
+    "graphs show the bounds of the support of the distribution.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(-4.2, 4.2, 500)\n"
+    ">>> lmbdas = [0.25, 0.5, 1.0, 1.5]\n"
+    ">>> for k, lmbda in enumerate(lmbdas):\n"
+    "...     y = tklmbda(x, lmbda)\n"
+    "...     ax.plot(x, y, styles[k], label=fr'$\\lambda$ = {lmbda}')\n"
+    "\n"
+    ">>> ax.set_prop_cycle(None)\n"
+    ">>> for lmbda in lmbdas:\n"
+    "...     ax.plot([-1/lmbda, 1/lmbda], [0, 1], '.', ms=8)\n"
+    "\n"
+    ">>> ax.set_title(r'tklmbda(x, $\\lambda$)')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.legend(framealpha=1, shadow=True)\n"
+    ">>> ax.grid(True)\n"
+    "\n"
+    ">>> plt.tight_layout()\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The CDF of the Tukey lambda distribution is also implemented as the\n"
+    "``cdf`` method of `scipy.stats.tukeylambda`.  In the following,\n"
+    "``tukeylambda.cdf(x, -0.5)`` and ``tklmbda(x, -0.5)`` compute the\n"
+    "same values:\n"
+    "\n"
+    ">>> from scipy.stats import tukeylambda\n"
+    ">>> x = np.linspace(-2, 2, 9)\n"
+    "\n"
+    ">>> tukeylambda.cdf(x, -0.5)\n"
+    "array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,\n"
+    "       0.58671839, 0.66458323, 0.72906142, 0.78004843])\n"
+    "\n"
+    ">>> tklmbda(x, -0.5)\n"
+    "array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,\n"
+    "       0.58671839, 0.66458323, 0.72906142, 0.78004843])\n"
+    "\n"
+    "The implementation in ``tukeylambda`` also provides location and scale\n"
+    "parameters, and other methods such as ``pdf()`` (the probability\n"
+    "density function) and ``ppf()`` (the inverse of the CDF), so for\n"
+    "working with the Tukey lambda distribution, ``tukeylambda`` is more\n"
+    "generally useful.  The primary advantage of ``tklmbda`` is that it is\n"
+    "significantly faster than ``tukeylambda.cdf``.")
+ufunc_tklmbda_loops[0] = loop_d_dd__As_ff_f
+ufunc_tklmbda_loops[1] = loop_d_dd__As_dd_d
+ufunc_tklmbda_types[0] = NPY_FLOAT
+ufunc_tklmbda_types[1] = NPY_FLOAT
+ufunc_tklmbda_types[2] = NPY_FLOAT
+ufunc_tklmbda_types[3] = NPY_DOUBLE
+ufunc_tklmbda_types[4] = NPY_DOUBLE
+ufunc_tklmbda_types[5] = NPY_DOUBLE
+ufunc_tklmbda_ptr[2*0] = _func_xsf_tukeylambdacdf
+ufunc_tklmbda_ptr[2*0+1] = ("tklmbda")
+ufunc_tklmbda_ptr[2*1] = _func_xsf_tukeylambdacdf
+ufunc_tklmbda_ptr[2*1+1] = ("tklmbda")
+ufunc_tklmbda_data[0] = &ufunc_tklmbda_ptr[2*0]
+ufunc_tklmbda_data[1] = &ufunc_tklmbda_ptr[2*1]
+tklmbda = np.PyUFunc_FromFuncAndData(ufunc_tklmbda_loops, ufunc_tklmbda_data, ufunc_tklmbda_types, 2, 2, 1, 0, "tklmbda", ufunc_tklmbda_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_voigt_profile_loops[2]
+cdef void *ufunc_voigt_profile_ptr[4]
+cdef void *ufunc_voigt_profile_data[2]
+cdef char ufunc_voigt_profile_types[8]
+cdef char *ufunc_voigt_profile_doc = (
+    "voigt_profile(x, sigma, gamma, out=None)\n"
+    "\n"
+    "Voigt profile.\n"
+    "\n"
+    "The Voigt profile is a convolution of a 1-D Normal distribution with\n"
+    "standard deviation ``sigma`` and a 1-D Cauchy distribution with half-width at\n"
+    "half-maximum ``gamma``.\n"
+    "\n"
+    "If ``sigma = 0``, PDF of Cauchy distribution is returned.\n"
+    "Conversely, if ``gamma = 0``, PDF of Normal distribution is returned.\n"
+    "If ``sigma = gamma = 0``, the return value is ``Inf`` for ``x = 0``,\n"
+    "and ``0`` for all other ``x``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real argument\n"
+    "sigma : array_like\n"
+    "    The standard deviation of the Normal distribution part\n"
+    "gamma : array_like\n"
+    "    The half-width at half-maximum of the Cauchy distribution part\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The Voigt profile at the given arguments\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "wofz : Faddeeva function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "It can be expressed in terms of Faddeeva function\n"
+    "\n"
+    ".. math:: V(x; \\sigma, \\gamma) = \\frac{Re[w(z)]}{\\sigma\\sqrt{2\\pi}},\n"
+    ".. math:: z = \\frac{x + i\\gamma}{\\sqrt{2}\\sigma}\n"
+    "\n"
+    "where :math:`w(z)` is the Faddeeva function.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Voigt_profile\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function at point 2 for ``sigma=1`` and ``gamma=1``.\n"
+    "\n"
+    ">>> from scipy.special import voigt_profile\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> voigt_profile(2, 1., 1.)\n"
+    "0.09071519942627544\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array\n"
+    "for `x`.\n"
+    "\n"
+    ">>> values = np.array([-2., 0., 5])\n"
+    ">>> voigt_profile(values, 1., 1.)\n"
+    "array([0.0907152 , 0.20870928, 0.01388492])\n"
+    "\n"
+    "Plot the function for different parameter sets.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> x = np.linspace(-10, 10, 500)\n"
+    ">>> parameters_list = [(1.5, 0., \"solid\"), (1.3, 0.5, \"dashed\"),\n"
+    "...                    (0., 1.8, \"dotted\"), (1., 1., \"dashdot\")]\n"
+    ">>> for params in parameters_list:\n"
+    "...     sigma, gamma, linestyle = params\n"
+    "...     voigt = voigt_profile(x, sigma, gamma)\n"
+    "...     ax.plot(x, voigt, label=rf\"$\\sigma={sigma},\\, \\gamma={gamma}$\",\n"
+    "...             ls=linestyle)\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Verify visually that the Voigt profile indeed arises as the convolution\n"
+    "of a normal and a Cauchy distribution.\n"
+    "\n"
+    ">>> from scipy.signal import convolve\n"
+    ">>> x, dx = np.linspace(-10, 10, 500, retstep=True)\n"
+    ">>> def gaussian(x, sigma):\n"
+    "...     return np.exp(-0.5 * x**2/sigma**2)/(sigma * np.sqrt(2*np.pi))\n"
+    ">>> def cauchy(x, gamma):\n"
+    "...     return gamma/(np.pi * (np.square(x)+gamma**2))\n"
+    ">>> sigma = 2\n"
+    ">>> gamma = 1\n"
+    ">>> gauss_profile = gaussian(x, sigma)\n"
+    ">>> cauchy_profile = cauchy(x, gamma)\n"
+    ">>> convolved = dx * convolve(cauchy_profile, gauss_profile, mode=\"same\")\n"
+    ">>> voigt = voigt_profile(x, sigma, gamma)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> ax.plot(x, gauss_profile, label=\"Gauss: $G$\", c='b')\n"
+    ">>> ax.plot(x, cauchy_profile, label=\"Cauchy: $C$\", c='y', ls=\"dashed\")\n"
+    ">>> xx = 0.5*(x[1:] + x[:-1])  # midpoints\n"
+    ">>> ax.plot(xx, convolved[1:], label=\"Convolution: $G * C$\", ls='dashdot',\n"
+    "...         c='k')\n"
+    ">>> ax.plot(x, voigt, label=\"Voigt\", ls='dotted', c='r')\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()")
+ufunc_voigt_profile_loops[0] = loop_d_ddd__As_fff_f
+ufunc_voigt_profile_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_voigt_profile_types[0] = NPY_FLOAT
+ufunc_voigt_profile_types[1] = NPY_FLOAT
+ufunc_voigt_profile_types[2] = NPY_FLOAT
+ufunc_voigt_profile_types[3] = NPY_FLOAT
+ufunc_voigt_profile_types[4] = NPY_DOUBLE
+ufunc_voigt_profile_types[5] = NPY_DOUBLE
+ufunc_voigt_profile_types[6] = NPY_DOUBLE
+ufunc_voigt_profile_types[7] = NPY_DOUBLE
+ufunc_voigt_profile_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_voigt_profile
+ufunc_voigt_profile_ptr[2*0+1] = ("voigt_profile")
+ufunc_voigt_profile_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_voigt_profile
+ufunc_voigt_profile_ptr[2*1+1] = ("voigt_profile")
+ufunc_voigt_profile_data[0] = &ufunc_voigt_profile_ptr[2*0]
+ufunc_voigt_profile_data[1] = &ufunc_voigt_profile_ptr[2*1]
+voigt_profile = np.PyUFunc_FromFuncAndData(ufunc_voigt_profile_loops, ufunc_voigt_profile_data, ufunc_voigt_profile_types, 2, 3, 1, 0, "voigt_profile", ufunc_voigt_profile_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_wofz_loops[2]
+cdef void *ufunc_wofz_ptr[4]
+cdef void *ufunc_wofz_data[2]
+cdef char ufunc_wofz_types[4]
+cdef char *ufunc_wofz_doc = (
+    "wofz(z, out=None)\n"
+    "\n"
+    "Faddeeva function\n"
+    "\n"
+    "Returns the value of the Faddeeva function for complex argument::\n"
+    "\n"
+    "    exp(-z**2) * erfc(-i*z)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    complex argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Faddeeva function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "dawsn, erf, erfc, erfcx, erfi\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> z = special.wofz(x)\n"
+    "\n"
+    ">>> plt.plot(x, z.real, label='wofz(x).real')\n"
+    ">>> plt.plot(x, z.imag, label='wofz(x).imag')\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.legend(framealpha=1, shadow=True)\n"
+    ">>> plt.grid(alpha=0.25)\n"
+    ">>> plt.show()")
+ufunc_wofz_loops[0] = loop_D_D__As_F_F
+ufunc_wofz_loops[1] = loop_D_D__As_D_D
+ufunc_wofz_types[0] = NPY_CFLOAT
+ufunc_wofz_types[1] = NPY_CFLOAT
+ufunc_wofz_types[2] = NPY_CDOUBLE
+ufunc_wofz_types[3] = NPY_CDOUBLE
+ufunc_wofz_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_w
+ufunc_wofz_ptr[2*0+1] = ("wofz")
+ufunc_wofz_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_w
+ufunc_wofz_ptr[2*1+1] = ("wofz")
+ufunc_wofz_data[0] = &ufunc_wofz_ptr[2*0]
+ufunc_wofz_data[1] = &ufunc_wofz_ptr[2*1]
+wofz = np.PyUFunc_FromFuncAndData(ufunc_wofz_loops, ufunc_wofz_data, ufunc_wofz_types, 2, 1, 1, 0, "wofz", ufunc_wofz_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_wrightomega_loops[4]
+cdef void *ufunc_wrightomega_ptr[8]
+cdef void *ufunc_wrightomega_data[4]
+cdef char ufunc_wrightomega_types[8]
+cdef char *ufunc_wrightomega_doc = (
+    "wrightomega(z, out=None)\n"
+    "\n"
+    "Wright Omega function.\n"
+    "\n"
+    "Defined as the solution to\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\omega + \\log(\\omega) = z\n"
+    "\n"
+    "where :math:`\\log` is the principal branch of the complex logarithm.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Points at which to evaluate the Wright Omega function\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "omega : scalar or ndarray\n"
+    "    Values of the Wright Omega function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "lambertw : The Lambert W function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.19.0\n"
+    "\n"
+    "The function can also be defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\omega(z) = W_{K(z)}(e^z)\n"
+    "\n"
+    "where :math:`K(z) = \\lceil (\\Im(z) - \\pi)/(2\\pi) \\rceil` is the\n"
+    "unwinding number and :math:`W` is the Lambert W function.\n"
+    "\n"
+    "The implementation here is taken from [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Lawrence, Corless, and Jeffrey, \"Algorithm 917: Complex\n"
+    "       Double-Precision Evaluation of the Wright :math:`\\omega`\n"
+    "       Function.\" ACM Transactions on Mathematical Software,\n"
+    "       2012. :doi:`10.1145/2168773.2168779`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import wrightomega, lambertw\n"
+    "\n"
+    ">>> wrightomega([-2, -1, 0, 1, 2])\n"
+    "array([0.12002824, 0.27846454, 0.56714329, 1.        , 1.5571456 ])\n"
+    "\n"
+    "Complex input:\n"
+    "\n"
+    ">>> wrightomega(3 + 5j)\n"
+    "(1.5804428632097158+3.8213626783287937j)\n"
+    "\n"
+    "Verify that ``wrightomega(z)`` satisfies ``w + log(w) = z``:\n"
+    "\n"
+    ">>> w = -5 + 4j\n"
+    ">>> wrightomega(w + np.log(w))\n"
+    "(-5+4j)\n"
+    "\n"
+    "Verify the connection to ``lambertw``:\n"
+    "\n"
+    ">>> z = 0.5 + 3j\n"
+    ">>> wrightomega(z)\n"
+    "(0.0966015889280649+1.4937828458191993j)\n"
+    ">>> lambertw(np.exp(z))\n"
+    "(0.09660158892806493+1.4937828458191993j)\n"
+    "\n"
+    ">>> z = 0.5 + 4j\n"
+    ">>> wrightomega(z)\n"
+    "(-0.3362123489037213+2.282986001579032j)\n"
+    ">>> lambertw(np.exp(z), k=1)\n"
+    "(-0.33621234890372115+2.282986001579032j)")
+ufunc_wrightomega_loops[0] = loop_d_d__As_f_f
+ufunc_wrightomega_loops[1] = loop_d_d__As_d_d
+ufunc_wrightomega_loops[2] = loop_D_D__As_F_F
+ufunc_wrightomega_loops[3] = loop_D_D__As_D_D
+ufunc_wrightomega_types[0] = NPY_FLOAT
+ufunc_wrightomega_types[1] = NPY_FLOAT
+ufunc_wrightomega_types[2] = NPY_DOUBLE
+ufunc_wrightomega_types[3] = NPY_DOUBLE
+ufunc_wrightomega_types[4] = NPY_CFLOAT
+ufunc_wrightomega_types[5] = NPY_CFLOAT
+ufunc_wrightomega_types[6] = NPY_CDOUBLE
+ufunc_wrightomega_types[7] = NPY_CDOUBLE
+ufunc_wrightomega_ptr[2*0] = scipy.special._ufuncs_cxx._export_wrightomega_real
+ufunc_wrightomega_ptr[2*0+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*1] = scipy.special._ufuncs_cxx._export_wrightomega_real
+ufunc_wrightomega_ptr[2*1+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*2] = scipy.special._ufuncs_cxx._export_wrightomega
+ufunc_wrightomega_ptr[2*2+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*3] = scipy.special._ufuncs_cxx._export_wrightomega
+ufunc_wrightomega_ptr[2*3+1] = ("wrightomega")
+ufunc_wrightomega_data[0] = &ufunc_wrightomega_ptr[2*0]
+ufunc_wrightomega_data[1] = &ufunc_wrightomega_ptr[2*1]
+ufunc_wrightomega_data[2] = &ufunc_wrightomega_ptr[2*2]
+ufunc_wrightomega_data[3] = &ufunc_wrightomega_ptr[2*3]
+wrightomega = np.PyUFunc_FromFuncAndData(ufunc_wrightomega_loops, ufunc_wrightomega_data, ufunc_wrightomega_types, 4, 1, 1, 0, "wrightomega", ufunc_wrightomega_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_xlog1py_loops[4]
+cdef void *ufunc_xlog1py_ptr[8]
+cdef void *ufunc_xlog1py_data[4]
+cdef char ufunc_xlog1py_types[12]
+cdef char *ufunc_xlog1py_doc = (
+    "xlog1py(x, y, out=None)\n"
+    "\n"
+    "Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Multiplier\n"
+    "y : array_like\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "z : scalar or ndarray\n"
+    "    Computed x*log1p(y)\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.13.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "This example shows how the function can be used to calculate the log of\n"
+    "the probability mass function for a geometric discrete random variable.\n"
+    "The probability mass function of the geometric distribution is defined\n"
+    "as follows:\n"
+    "\n"
+    ".. math:: f(k) = (1-p)^{k-1} p\n"
+    "\n"
+    "where :math:`p` is the probability of a single success\n"
+    "and :math:`1-p` is the probability of a single failure\n"
+    "and :math:`k` is the number of trials to get the first success.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import xlog1py\n"
+    ">>> p = 0.5\n"
+    ">>> k = 100\n"
+    ">>> _pmf = np.power(1 - p, k - 1) * p\n"
+    ">>> _pmf\n"
+    "7.888609052210118e-31\n"
+    "\n"
+    "If we take k as a relatively large number the value of the probability\n"
+    "mass function can become very low. In such cases taking the log of the\n"
+    "pmf would be more suitable as the log function can change the values\n"
+    "to a scale that is more appropriate to work with.\n"
+    "\n"
+    ">>> _log_pmf = xlog1py(k - 1, -p) + np.log(p)\n"
+    ">>> _log_pmf\n"
+    "-69.31471805599453\n"
+    "\n"
+    "We can confirm that we get a value close to the original pmf value by\n"
+    "taking the exponential of the log pmf.\n"
+    "\n"
+    ">>> _orig_pmf = np.exp(_log_pmf)\n"
+    ">>> np.isclose(_pmf, _orig_pmf)\n"
+    "True")
+ufunc_xlog1py_loops[0] = loop_d_dd__As_ff_f
+ufunc_xlog1py_loops[1] = loop_d_dd__As_dd_d
+ufunc_xlog1py_loops[2] = loop_D_DD__As_FF_F
+ufunc_xlog1py_loops[3] = loop_D_DD__As_DD_D
+ufunc_xlog1py_types[0] = NPY_FLOAT
+ufunc_xlog1py_types[1] = NPY_FLOAT
+ufunc_xlog1py_types[2] = NPY_FLOAT
+ufunc_xlog1py_types[3] = NPY_DOUBLE
+ufunc_xlog1py_types[4] = NPY_DOUBLE
+ufunc_xlog1py_types[5] = NPY_DOUBLE
+ufunc_xlog1py_types[6] = NPY_CFLOAT
+ufunc_xlog1py_types[7] = NPY_CFLOAT
+ufunc_xlog1py_types[8] = NPY_CFLOAT
+ufunc_xlog1py_types[9] = NPY_CDOUBLE
+ufunc_xlog1py_types[10] = NPY_CDOUBLE
+ufunc_xlog1py_types[11] = NPY_CDOUBLE
+ufunc_xlog1py_ptr[2*0] = _func_xlog1py[double]
+ufunc_xlog1py_ptr[2*0+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*1] = _func_xlog1py[double]
+ufunc_xlog1py_ptr[2*1+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*2] = _func_xlog1py[double_complex]
+ufunc_xlog1py_ptr[2*2+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*3] = _func_xlog1py[double_complex]
+ufunc_xlog1py_ptr[2*3+1] = ("xlog1py")
+ufunc_xlog1py_data[0] = &ufunc_xlog1py_ptr[2*0]
+ufunc_xlog1py_data[1] = &ufunc_xlog1py_ptr[2*1]
+ufunc_xlog1py_data[2] = &ufunc_xlog1py_ptr[2*2]
+ufunc_xlog1py_data[3] = &ufunc_xlog1py_ptr[2*3]
+xlog1py = np.PyUFunc_FromFuncAndData(ufunc_xlog1py_loops, ufunc_xlog1py_data, ufunc_xlog1py_types, 4, 2, 1, 0, "xlog1py", ufunc_xlog1py_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_xlogy_loops[4]
+cdef void *ufunc_xlogy_ptr[8]
+cdef void *ufunc_xlogy_data[4]
+cdef char ufunc_xlogy_types[12]
+cdef char *ufunc_xlogy_doc = (
+    "xlogy(x, y, out=None)\n"
+    "\n"
+    "Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Multiplier\n"
+    "y : array_like\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "z : scalar or ndarray\n"
+    "    Computed x*log(y)\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The log function used in the computation is the natural log.\n"
+    "\n"
+    ".. versionadded:: 0.13.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "We can use this function to calculate the binary logistic loss also\n"
+    "known as the binary cross entropy. This loss function is used for\n"
+    "binary classification problems and is defined as:\n"
+    "\n"
+    ".. math::\n"
+    "    L = 1/n * \\sum_{i=0}^n -(y_i*log(y\\_pred_i) + (1-y_i)*log(1-y\\_pred_i))\n"
+    "\n"
+    "We can define the parameters `x` and `y` as y and y_pred respectively.\n"
+    "y is the array of the actual labels which over here can be either 0 or 1.\n"
+    "y_pred is the array of the predicted probabilities with respect to\n"
+    "the positive class (1).\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import xlogy\n"
+    ">>> y = np.array([0, 1, 0, 1, 1, 0])\n"
+    ">>> y_pred = np.array([0.3, 0.8, 0.4, 0.7, 0.9, 0.2])\n"
+    ">>> n = len(y)\n"
+    ">>> loss = -(xlogy(y, y_pred) + xlogy(1 - y, 1 - y_pred)).sum()\n"
+    ">>> loss /= n\n"
+    ">>> loss\n"
+    "0.29597052165495025\n"
+    "\n"
+    "A lower loss is usually better as it indicates that the predictions are\n"
+    "similar to the actual labels. In this example since our predicted\n"
+    "probabilities are close to the actual labels, we get an overall loss\n"
+    "that is reasonably low and appropriate.")
+ufunc_xlogy_loops[0] = loop_d_dd__As_ff_f
+ufunc_xlogy_loops[1] = loop_d_dd__As_dd_d
+ufunc_xlogy_loops[2] = loop_D_DD__As_FF_F
+ufunc_xlogy_loops[3] = loop_D_DD__As_DD_D
+ufunc_xlogy_types[0] = NPY_FLOAT
+ufunc_xlogy_types[1] = NPY_FLOAT
+ufunc_xlogy_types[2] = NPY_FLOAT
+ufunc_xlogy_types[3] = NPY_DOUBLE
+ufunc_xlogy_types[4] = NPY_DOUBLE
+ufunc_xlogy_types[5] = NPY_DOUBLE
+ufunc_xlogy_types[6] = NPY_CFLOAT
+ufunc_xlogy_types[7] = NPY_CFLOAT
+ufunc_xlogy_types[8] = NPY_CFLOAT
+ufunc_xlogy_types[9] = NPY_CDOUBLE
+ufunc_xlogy_types[10] = NPY_CDOUBLE
+ufunc_xlogy_types[11] = NPY_CDOUBLE
+ufunc_xlogy_ptr[2*0] = _func_xlogy[double]
+ufunc_xlogy_ptr[2*0+1] = ("xlogy")
+ufunc_xlogy_ptr[2*1] = _func_xlogy[double]
+ufunc_xlogy_ptr[2*1+1] = ("xlogy")
+ufunc_xlogy_ptr[2*2] = _func_xlogy[double_complex]
+ufunc_xlogy_ptr[2*2+1] = ("xlogy")
+ufunc_xlogy_ptr[2*3] = _func_xlogy[double_complex]
+ufunc_xlogy_ptr[2*3+1] = ("xlogy")
+ufunc_xlogy_data[0] = &ufunc_xlogy_ptr[2*0]
+ufunc_xlogy_data[1] = &ufunc_xlogy_ptr[2*1]
+ufunc_xlogy_data[2] = &ufunc_xlogy_ptr[2*2]
+ufunc_xlogy_data[3] = &ufunc_xlogy_ptr[2*3]
+xlogy = np.PyUFunc_FromFuncAndData(ufunc_xlogy_loops, ufunc_xlogy_data, ufunc_xlogy_types, 4, 2, 1, 0, "xlogy", ufunc_xlogy_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_yn_loops[3]
+cdef void *ufunc_yn_ptr[6]
+cdef void *ufunc_yn_data[3]
+cdef char ufunc_yn_types[9]
+cdef char *ufunc_yn_doc = (
+    "yn(n, x, out=None)\n"
+    "\n"
+    "Bessel function of the second kind of integer order and real argument.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Order (integer).\n"
+    "x : array_like\n"
+    "    Argument (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "Y : scalar or ndarray\n"
+    "    Value of the Bessel function, :math:`Y_n(x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "yv : For real order and real or complex argument.\n"
+    "y0: faster implementation of this function for order 0\n"
+    "y1: faster implementation of this function for order 1\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the Cephes [1]_ routine `yn`.\n"
+    "\n"
+    "The function is evaluated by forward recurrence on `n`, starting with\n"
+    "values computed by the Cephes routines `y0` and `y1`. If ``n = 0`` or 1,\n"
+    "the routine for `y0` or `y1` is called directly.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Evaluate the function of order 0 at one point.\n"
+    "\n"
+    ">>> from scipy.special import yn\n"
+    ">>> yn(0, 1.)\n"
+    "0.08825696421567697\n"
+    "\n"
+    "Evaluate the function at one point for different orders.\n"
+    "\n"
+    ">>> yn(0, 1.), yn(1, 1.), yn(2, 1.)\n"
+    "(0.08825696421567697, -0.7812128213002888, -1.6506826068162546)\n"
+    "\n"
+    "The evaluation for different orders can be carried out in one call by\n"
+    "providing a list or NumPy array as argument for the `v` parameter:\n"
+    "\n"
+    ">>> yn([0, 1, 2], 1.)\n"
+    "array([ 0.08825696, -0.78121282, -1.65068261])\n"
+    "\n"
+    "Evaluate the function at several points for order 0 by providing an\n"
+    "array for `z`.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> points = np.array([0.5, 3., 8.])\n"
+    ">>> yn(0, points)\n"
+    "array([-0.44451873,  0.37685001,  0.22352149])\n"
+    "\n"
+    "If `z` is an array, the order parameter `v` must be broadcastable to\n"
+    "the correct shape if different orders shall be computed in one call.\n"
+    "To calculate the orders 0 and 1 for an 1D array:\n"
+    "\n"
+    ">>> orders = np.array([[0], [1]])\n"
+    ">>> orders.shape\n"
+    "(2, 1)\n"
+    "\n"
+    ">>> yn(orders, points)\n"
+    "array([[-0.44451873,  0.37685001,  0.22352149],\n"
+    "       [-1.47147239,  0.32467442, -0.15806046]])\n"
+    "\n"
+    "Plot the functions of order 0 to 3 from 0 to 10.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(0., 10., 1000)\n"
+    ">>> for i in range(4):\n"
+    "...     ax.plot(x, yn(i, x), label=f'$Y_{i!r}$')\n"
+    ">>> ax.set_ylim(-3, 1)\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()")
+ufunc_yn_loops[0] = loop_d_pd__As_pd_d
+ufunc_yn_loops[1] = loop_d_dd__As_ff_f
+ufunc_yn_loops[2] = loop_d_dd__As_dd_d
+ufunc_yn_types[0] = NPY_INTP
+ufunc_yn_types[1] = NPY_DOUBLE
+ufunc_yn_types[2] = NPY_DOUBLE
+ufunc_yn_types[3] = NPY_FLOAT
+ufunc_yn_types[4] = NPY_FLOAT
+ufunc_yn_types[5] = NPY_FLOAT
+ufunc_yn_types[6] = NPY_DOUBLE
+ufunc_yn_types[7] = NPY_DOUBLE
+ufunc_yn_types[8] = NPY_DOUBLE
+ufunc_yn_ptr[2*0] = _func_cephes_yn_wrap
+ufunc_yn_ptr[2*0+1] = ("yn")
+ufunc_yn_ptr[2*1] = _func_yn_unsafe
+ufunc_yn_ptr[2*1+1] = ("yn")
+ufunc_yn_ptr[2*2] = _func_yn_unsafe
+ufunc_yn_ptr[2*2+1] = ("yn")
+ufunc_yn_data[0] = &ufunc_yn_ptr[2*0]
+ufunc_yn_data[1] = &ufunc_yn_ptr[2*1]
+ufunc_yn_data[2] = &ufunc_yn_ptr[2*2]
+yn = np.PyUFunc_FromFuncAndData(ufunc_yn_loops, ufunc_yn_data, ufunc_yn_types, 3, 2, 1, 0, "yn", ufunc_yn_doc, 0)
+
+from ._special_ufuncs import (_cospi, _lambertw, _scaled_exp1, _sinpi, _spherical_jn, _spherical_jn_d, _spherical_yn, _spherical_yn_d, _spherical_in, _spherical_in_d, _spherical_kn, _spherical_kn_d, airy, airye, bei, beip, ber, berp, binom, exp1, expi, expit, exprel, gamma, gammaln, hankel1, hankel1e, hankel2, hankel2e, hyp2f1, it2i0k0, it2j0y0, it2struve0, itairy, iti0k0, itj0y0, itmodstruve0, itstruve0, iv, _iv_ratio, _iv_ratio_c, ive, jv, jve, kei, keip, kelvin, ker, kerp, kv, kve, log_expit, log_wright_bessel, loggamma, logit, mathieu_a, mathieu_b, mathieu_cem, mathieu_modcem1, mathieu_modcem2, mathieu_modsem1, mathieu_modsem2, mathieu_sem, modfresnelm, modfresnelp, obl_ang1, obl_ang1_cv, obl_cv, obl_rad1, obl_rad1_cv, obl_rad2, obl_rad2_cv, pbdv, pbvv, pbwa, pro_ang1, pro_ang1_cv, pro_cv, pro_rad1, pro_rad1_cv, pro_rad2, pro_rad2_cv, psi, rgamma, sph_harm, wright_bessel, yv, yve, zetac, _zeta, sindg, cosdg, tandg, cotdg, i0, i0e, i1, i1e, k0, k0e, k1, k1e, y0, y1, j0, j1, struve, modstruve, beta, betaln, besselpoly, gammaln, gammasgn, cbrt, radian, cosm1, gammainc, gammaincinv, gammaincc, gammainccinv, fresnel, ellipe, ellipeinc, ellipk, ellipkinc, ellipkm1, ellipj, _riemann_zeta)
+
+#
+# Aliases
+#
+jn = jv
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..a2fffff86812d1a7ca547a71a19078b6d5f59716
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd
@@ -0,0 +1,155 @@
+from . cimport sf_error
+cdef void _set_action(sf_error.sf_error_t, sf_error.sf_action_t) noexcept nogil
+cdef void *_export_beta_pdf_float
+cdef void *_export_beta_pdf_double
+cdef void *_export_beta_ppf_float
+cdef void *_export_beta_ppf_double
+cdef void *_export_binom_cdf_float
+cdef void *_export_binom_cdf_double
+cdef void *_export_binom_isf_float
+cdef void *_export_binom_isf_double
+cdef void *_export_binom_pmf_float
+cdef void *_export_binom_pmf_double
+cdef void *_export_binom_ppf_float
+cdef void *_export_binom_ppf_double
+cdef void *_export_binom_sf_float
+cdef void *_export_binom_sf_double
+cdef void *_export_cauchy_isf_float
+cdef void *_export_cauchy_isf_double
+cdef void *_export_cauchy_ppf_float
+cdef void *_export_cauchy_ppf_double
+cdef void *_export_hypergeom_cdf_float
+cdef void *_export_hypergeom_cdf_double
+cdef void *_export_hypergeom_mean_float
+cdef void *_export_hypergeom_mean_double
+cdef void *_export_hypergeom_pmf_float
+cdef void *_export_hypergeom_pmf_double
+cdef void *_export_hypergeom_sf_float
+cdef void *_export_hypergeom_sf_double
+cdef void *_export_hypergeom_skewness_float
+cdef void *_export_hypergeom_skewness_double
+cdef void *_export_hypergeom_variance_float
+cdef void *_export_hypergeom_variance_double
+cdef void *_export_invgauss_isf_float
+cdef void *_export_invgauss_isf_double
+cdef void *_export_invgauss_ppf_float
+cdef void *_export_invgauss_ppf_double
+cdef void *_export_landau_cdf_float
+cdef void *_export_landau_cdf_double
+cdef void *_export_landau_isf_float
+cdef void *_export_landau_isf_double
+cdef void *_export_landau_pdf_float
+cdef void *_export_landau_pdf_double
+cdef void *_export_landau_ppf_float
+cdef void *_export_landau_ppf_double
+cdef void *_export_landau_sf_float
+cdef void *_export_landau_sf_double
+cdef void *_export_nbinom_cdf_float
+cdef void *_export_nbinom_cdf_double
+cdef void *_export_nbinom_isf_float
+cdef void *_export_nbinom_isf_double
+cdef void *_export_nbinom_kurtosis_excess_float
+cdef void *_export_nbinom_kurtosis_excess_double
+cdef void *_export_nbinom_mean_float
+cdef void *_export_nbinom_mean_double
+cdef void *_export_nbinom_pmf_float
+cdef void *_export_nbinom_pmf_double
+cdef void *_export_nbinom_ppf_float
+cdef void *_export_nbinom_ppf_double
+cdef void *_export_nbinom_sf_float
+cdef void *_export_nbinom_sf_double
+cdef void *_export_nbinom_skewness_float
+cdef void *_export_nbinom_skewness_double
+cdef void *_export_nbinom_variance_float
+cdef void *_export_nbinom_variance_double
+cdef void *_export_ncf_isf_float
+cdef void *_export_ncf_isf_double
+cdef void *_export_ncf_kurtosis_excess_float
+cdef void *_export_ncf_kurtosis_excess_double
+cdef void *_export_ncf_mean_float
+cdef void *_export_ncf_mean_double
+cdef void *_export_ncf_pdf_float
+cdef void *_export_ncf_pdf_double
+cdef void *_export_ncf_sf_float
+cdef void *_export_ncf_sf_double
+cdef void *_export_ncf_skewness_float
+cdef void *_export_ncf_skewness_double
+cdef void *_export_ncf_variance_float
+cdef void *_export_ncf_variance_double
+cdef void *_export_nct_isf_float
+cdef void *_export_nct_isf_double
+cdef void *_export_nct_kurtosis_excess_float
+cdef void *_export_nct_kurtosis_excess_double
+cdef void *_export_nct_mean_float
+cdef void *_export_nct_mean_double
+cdef void *_export_nct_pdf_float
+cdef void *_export_nct_pdf_double
+cdef void *_export_nct_ppf_float
+cdef void *_export_nct_ppf_double
+cdef void *_export_nct_sf_float
+cdef void *_export_nct_sf_double
+cdef void *_export_nct_skewness_float
+cdef void *_export_nct_skewness_double
+cdef void *_export_nct_variance_float
+cdef void *_export_nct_variance_double
+cdef void *_export_ncx2_cdf_float
+cdef void *_export_ncx2_cdf_double
+cdef void *_export_ncx2_isf_float
+cdef void *_export_ncx2_isf_double
+cdef void *_export_ncx2_pdf_float
+cdef void *_export_ncx2_pdf_double
+cdef void *_export_ncx2_ppf_float
+cdef void *_export_ncx2_ppf_double
+cdef void *_export_ncx2_sf_float
+cdef void *_export_ncx2_sf_double
+cdef void *_export_skewnorm_cdf_float
+cdef void *_export_skewnorm_cdf_double
+cdef void *_export_skewnorm_isf_float
+cdef void *_export_skewnorm_isf_double
+cdef void *_export_skewnorm_ppf_float
+cdef void *_export_skewnorm_ppf_double
+cdef void *_export__stirling2_inexact
+cdef void *_export_ibeta_float
+cdef void *_export_ibeta_double
+cdef void *_export_ibetac_float
+cdef void *_export_ibetac_double
+cdef void *_export_ibetac_inv_float
+cdef void *_export_ibetac_inv_double
+cdef void *_export_ibeta_inv_float
+cdef void *_export_ibeta_inv_double
+cdef void *_export_faddeeva_dawsn
+cdef void *_export_faddeeva_dawsn_complex
+cdef void *_export_fellint_RC
+cdef void *_export_cellint_RC
+cdef void *_export_fellint_RD
+cdef void *_export_cellint_RD
+cdef void *_export_fellint_RF
+cdef void *_export_cellint_RF
+cdef void *_export_fellint_RG
+cdef void *_export_cellint_RG
+cdef void *_export_fellint_RJ
+cdef void *_export_cellint_RJ
+cdef void *_export_faddeeva_erf
+cdef void *_export_faddeeva_erfc_complex
+cdef void *_export_faddeeva_erfcx
+cdef void *_export_faddeeva_erfcx_complex
+cdef void *_export_faddeeva_erfi
+cdef void *_export_faddeeva_erfi_complex
+cdef void *_export_erfinv_float
+cdef void *_export_erfinv_double
+cdef void *_export_hyp1f1_double
+cdef void *_export_faddeeva_log_ndtr
+cdef void *_export_faddeeva_log_ndtr_complex
+cdef void *_export_ncf_cdf_float
+cdef void *_export_ncf_cdf_double
+cdef void *_export_ncf_ppf_float
+cdef void *_export_ncf_ppf_double
+cdef void *_export_nct_cdf_float
+cdef void *_export_nct_cdf_double
+cdef void *_export_faddeeva_ndtr
+cdef void *_export_powm1_float
+cdef void *_export_powm1_double
+cdef void *_export_faddeeva_voigt_profile
+cdef void *_export_faddeeva_w
+cdef void *_export_wrightomega
+cdef void *_export_wrightomega_real
\ No newline at end of file
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..19cbd36c4707bb593e7e5638b9a158df504d3001
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx
@@ -0,0 +1,466 @@
+# This file is automatically generated by _generate_pyx.py.
+# Do not edit manually!
+
+from libc.math cimport NAN
+
+include "_ufuncs_extra_code_common.pxi"
+
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_beta_pdf_float "beta_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_beta_pdf_float = _func_beta_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_beta_pdf_double "beta_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_beta_pdf_double = _func_beta_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_beta_ppf_float "beta_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_beta_ppf_float = _func_beta_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_beta_ppf_double "beta_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_beta_ppf_double = _func_beta_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_cdf_float "binom_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_cdf_float = _func_binom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_cdf_double "binom_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_cdf_double = _func_binom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_isf_float "binom_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_isf_float = _func_binom_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_isf_double "binom_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_isf_double = _func_binom_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_pmf_float "binom_pmf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_pmf_float = _func_binom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_pmf_double "binom_pmf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_pmf_double = _func_binom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_ppf_float "binom_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_ppf_float = _func_binom_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_ppf_double "binom_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_ppf_double = _func_binom_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_sf_float "binom_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_sf_float = _func_binom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_sf_double "binom_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_sf_double = _func_binom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_cauchy_isf_float "cauchy_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_cauchy_isf_float = _func_cauchy_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_cauchy_isf_double "cauchy_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_cauchy_isf_double = _func_cauchy_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_cauchy_ppf_float "cauchy_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_cauchy_ppf_float = _func_cauchy_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_cauchy_ppf_double "cauchy_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_cauchy_ppf_double = _func_cauchy_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_cdf_float "hypergeom_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_cdf_float = _func_hypergeom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_cdf_double "hypergeom_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_cdf_double = _func_hypergeom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_mean_float "hypergeom_mean_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_mean_float = _func_hypergeom_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_mean_double "hypergeom_mean_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_mean_double = _func_hypergeom_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_pmf_float "hypergeom_pmf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_pmf_float = _func_hypergeom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_pmf_double "hypergeom_pmf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_pmf_double = _func_hypergeom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_sf_float "hypergeom_sf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_sf_float = _func_hypergeom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_sf_double "hypergeom_sf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_sf_double = _func_hypergeom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_skewness_float "hypergeom_skewness_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_skewness_float = _func_hypergeom_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_skewness_double "hypergeom_skewness_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_skewness_double = _func_hypergeom_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_variance_float "hypergeom_variance_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_variance_float = _func_hypergeom_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_variance_double "hypergeom_variance_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_variance_double = _func_hypergeom_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_invgauss_isf_float "invgauss_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_invgauss_isf_float = _func_invgauss_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_invgauss_isf_double "invgauss_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_invgauss_isf_double = _func_invgauss_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_invgauss_ppf_float "invgauss_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_invgauss_ppf_float = _func_invgauss_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_invgauss_ppf_double "invgauss_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_invgauss_ppf_double = _func_invgauss_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_cdf_float "landau_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_cdf_float = _func_landau_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_cdf_double "landau_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_cdf_double = _func_landau_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_isf_float "landau_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_isf_float = _func_landau_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_isf_double "landau_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_isf_double = _func_landau_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_pdf_float "landau_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_pdf_float = _func_landau_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_pdf_double "landau_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_pdf_double = _func_landau_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_ppf_float "landau_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_ppf_float = _func_landau_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_ppf_double "landau_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_ppf_double = _func_landau_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_sf_float "landau_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_sf_float = _func_landau_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_sf_double "landau_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_sf_double = _func_landau_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_cdf_float "nbinom_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_cdf_float = _func_nbinom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_cdf_double "nbinom_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_cdf_double = _func_nbinom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_isf_float "nbinom_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_isf_float = _func_nbinom_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_isf_double "nbinom_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_isf_double = _func_nbinom_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_kurtosis_excess_float "nbinom_kurtosis_excess_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_kurtosis_excess_float = _func_nbinom_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_kurtosis_excess_double "nbinom_kurtosis_excess_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_kurtosis_excess_double = _func_nbinom_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_mean_float "nbinom_mean_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_mean_float = _func_nbinom_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_mean_double "nbinom_mean_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_mean_double = _func_nbinom_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_pmf_float "nbinom_pmf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_pmf_float = _func_nbinom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_pmf_double "nbinom_pmf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_pmf_double = _func_nbinom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_ppf_float "nbinom_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_ppf_float = _func_nbinom_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_ppf_double "nbinom_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_ppf_double = _func_nbinom_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_sf_float "nbinom_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_sf_float = _func_nbinom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_sf_double "nbinom_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_sf_double = _func_nbinom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_skewness_float "nbinom_skewness_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_skewness_float = _func_nbinom_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_skewness_double "nbinom_skewness_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_skewness_double = _func_nbinom_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_variance_float "nbinom_variance_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_variance_float = _func_nbinom_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_variance_double "nbinom_variance_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_variance_double = _func_nbinom_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_isf_float "ncf_isf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_isf_float = _func_ncf_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_isf_double "ncf_isf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_isf_double = _func_ncf_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_kurtosis_excess_float "ncf_kurtosis_excess_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_kurtosis_excess_float = _func_ncf_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_kurtosis_excess_double "ncf_kurtosis_excess_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_kurtosis_excess_double = _func_ncf_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_mean_float "ncf_mean_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_mean_float = _func_ncf_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_mean_double "ncf_mean_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_mean_double = _func_ncf_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_pdf_float "ncf_pdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_pdf_float = _func_ncf_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_pdf_double "ncf_pdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_pdf_double = _func_ncf_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_sf_float "ncf_sf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_sf_float = _func_ncf_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_sf_double "ncf_sf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_sf_double = _func_ncf_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_skewness_float "ncf_skewness_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_skewness_float = _func_ncf_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_skewness_double "ncf_skewness_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_skewness_double = _func_ncf_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_variance_float "ncf_variance_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_variance_float = _func_ncf_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_variance_double "ncf_variance_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_variance_double = _func_ncf_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_isf_float "nct_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_isf_float = _func_nct_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_isf_double "nct_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_isf_double = _func_nct_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_kurtosis_excess_float "nct_kurtosis_excess_float"(float, float) noexcept nogil
+cdef void *_export_nct_kurtosis_excess_float = _func_nct_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_kurtosis_excess_double "nct_kurtosis_excess_double"(double, double) noexcept nogil
+cdef void *_export_nct_kurtosis_excess_double = _func_nct_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_mean_float "nct_mean_float"(float, float) noexcept nogil
+cdef void *_export_nct_mean_float = _func_nct_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_mean_double "nct_mean_double"(double, double) noexcept nogil
+cdef void *_export_nct_mean_double = _func_nct_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_pdf_float "nct_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_pdf_float = _func_nct_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_pdf_double "nct_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_pdf_double = _func_nct_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_ppf_float "nct_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_ppf_float = _func_nct_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_ppf_double "nct_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_ppf_double = _func_nct_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_sf_float "nct_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_sf_float = _func_nct_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_sf_double "nct_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_sf_double = _func_nct_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_skewness_float "nct_skewness_float"(float, float) noexcept nogil
+cdef void *_export_nct_skewness_float = _func_nct_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_skewness_double "nct_skewness_double"(double, double) noexcept nogil
+cdef void *_export_nct_skewness_double = _func_nct_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_variance_float "nct_variance_float"(float, float) noexcept nogil
+cdef void *_export_nct_variance_float = _func_nct_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_variance_double "nct_variance_double"(double, double) noexcept nogil
+cdef void *_export_nct_variance_double = _func_nct_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_cdf_float "ncx2_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_cdf_float = _func_ncx2_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_cdf_double "ncx2_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_cdf_double = _func_ncx2_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_isf_float "ncx2_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_isf_float = _func_ncx2_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_isf_double "ncx2_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_isf_double = _func_ncx2_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_pdf_float "ncx2_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_pdf_float = _func_ncx2_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_pdf_double "ncx2_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_pdf_double = _func_ncx2_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_ppf_float "ncx2_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_ppf_float = _func_ncx2_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_ppf_double "ncx2_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_ppf_double = _func_ncx2_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_sf_float "ncx2_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_sf_float = _func_ncx2_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_sf_double "ncx2_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_sf_double = _func_ncx2_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_cdf_float "skewnorm_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_cdf_float = _func_skewnorm_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_cdf_double "skewnorm_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_cdf_double = _func_skewnorm_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_isf_float "skewnorm_isf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_isf_float = _func_skewnorm_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_isf_double "skewnorm_isf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_isf_double = _func_skewnorm_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_ppf_float "skewnorm_ppf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_ppf_float = _func_skewnorm_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_ppf_double "skewnorm_ppf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_ppf_double = _func_skewnorm_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func__stirling2_inexact "_stirling2_inexact"(double, double) noexcept nogil
+cdef void *_export__stirling2_inexact = _func__stirling2_inexact
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibeta_float "ibeta_float"(float, float, float) noexcept nogil
+cdef void *_export_ibeta_float = _func_ibeta_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibeta_double "ibeta_double"(double, double, double) noexcept nogil
+cdef void *_export_ibeta_double = _func_ibeta_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibetac_float "ibetac_float"(float, float, float) noexcept nogil
+cdef void *_export_ibetac_float = _func_ibetac_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibetac_double "ibetac_double"(double, double, double) noexcept nogil
+cdef void *_export_ibetac_double = _func_ibetac_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibetac_inv_float "ibetac_inv_float"(float, float, float) noexcept nogil
+cdef void *_export_ibetac_inv_float = _func_ibetac_inv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibetac_inv_double "ibetac_inv_double"(double, double, double) noexcept nogil
+cdef void *_export_ibetac_inv_double = _func_ibetac_inv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibeta_inv_float "ibeta_inv_float"(float, float, float) noexcept nogil
+cdef void *_export_ibeta_inv_float = _func_ibeta_inv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibeta_inv_double "ibeta_inv_double"(double, double, double) noexcept nogil
+cdef void *_export_ibeta_inv_double = _func_ibeta_inv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_dawsn "faddeeva_dawsn"(double) noexcept nogil
+cdef void *_export_faddeeva_dawsn = _func_faddeeva_dawsn
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_dawsn_complex "faddeeva_dawsn_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_dawsn_complex = _func_faddeeva_dawsn_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RC "fellint_RC"(double, double) noexcept nogil
+cdef void *_export_fellint_RC = _func_fellint_RC
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RC "cellint_RC"(double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RC = _func_cellint_RC
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RD "fellint_RD"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RD = _func_fellint_RD
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RD "cellint_RD"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RD = _func_cellint_RD
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RF "fellint_RF"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RF = _func_fellint_RF
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RF "cellint_RF"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RF = _func_cellint_RF
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RG "fellint_RG"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RG = _func_fellint_RG
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RG "cellint_RG"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RG = _func_cellint_RG
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RJ "fellint_RJ"(double, double, double, double) noexcept nogil
+cdef void *_export_fellint_RJ = _func_fellint_RJ
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RJ "cellint_RJ"(double complex, double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RJ = _func_cellint_RJ
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erf "faddeeva_erf"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erf = _func_faddeeva_erf
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfc_complex "faddeeva_erfc_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfc_complex = _func_faddeeva_erfc_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_erfcx "faddeeva_erfcx"(double) noexcept nogil
+cdef void *_export_faddeeva_erfcx = _func_faddeeva_erfcx
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfcx_complex "faddeeva_erfcx_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfcx_complex = _func_faddeeva_erfcx_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_erfi "faddeeva_erfi"(double) noexcept nogil
+cdef void *_export_faddeeva_erfi = _func_faddeeva_erfi
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfi_complex "faddeeva_erfi_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfi_complex = _func_faddeeva_erfi_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_erfinv_float "erfinv_float"(float) noexcept nogil
+cdef void *_export_erfinv_float = _func_erfinv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_erfinv_double "erfinv_double"(double) noexcept nogil
+cdef void *_export_erfinv_double = _func_erfinv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hyp1f1_double "hyp1f1_double"(double, double, double) noexcept nogil
+cdef void *_export_hyp1f1_double = _func_hyp1f1_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_log_ndtr "faddeeva_log_ndtr"(double) noexcept nogil
+cdef void *_export_faddeeva_log_ndtr = _func_faddeeva_log_ndtr
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_log_ndtr_complex "faddeeva_log_ndtr_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_log_ndtr_complex = _func_faddeeva_log_ndtr_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_cdf_float "ncf_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_cdf_float = _func_ncf_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_cdf_double "ncf_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_cdf_double = _func_ncf_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_ppf_float "ncf_ppf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_ppf_float = _func_ncf_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_ppf_double "ncf_ppf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_ppf_double = _func_ncf_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_cdf_float "nct_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_cdf_float = _func_nct_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_cdf_double "nct_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_cdf_double = _func_nct_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_ndtr "faddeeva_ndtr"(double complex) noexcept nogil
+cdef void *_export_faddeeva_ndtr = _func_faddeeva_ndtr
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_powm1_float "powm1_float"(float, float) noexcept nogil
+cdef void *_export_powm1_float = _func_powm1_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_powm1_double "powm1_double"(double, double) noexcept nogil
+cdef void *_export_powm1_double = _func_powm1_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_voigt_profile "faddeeva_voigt_profile"(double, double, double) noexcept nogil
+cdef void *_export_faddeeva_voigt_profile = _func_faddeeva_voigt_profile
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_w "faddeeva_w"(double complex) noexcept nogil
+cdef void *_export_faddeeva_w = _func_faddeeva_w
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_wrightomega "wrightomega"(double complex) noexcept nogil
+cdef void *_export_wrightomega = _func_wrightomega
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_wrightomega_real "wrightomega_real"(double) noexcept nogil
+cdef void *_export_wrightomega_real = _func_wrightomega_real
\ No newline at end of file
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..4e916ce565742ecd949c2c6f9c1a1891e734a96d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h
@@ -0,0 +1,161 @@
+#ifndef UFUNCS_PROTO_H
+#define UFUNCS_PROTO_H 1
+#include "boost_special_functions.h"
+npy_float beta_pdf_float(npy_float, npy_float, npy_float);
+npy_double beta_pdf_double(npy_double, npy_double, npy_double);
+npy_float beta_ppf_float(npy_float, npy_float, npy_float);
+npy_double beta_ppf_double(npy_double, npy_double, npy_double);
+npy_float binom_cdf_float(npy_float, npy_float, npy_float);
+npy_double binom_cdf_double(npy_double, npy_double, npy_double);
+npy_float binom_isf_float(npy_float, npy_float, npy_float);
+npy_double binom_isf_double(npy_double, npy_double, npy_double);
+npy_float binom_pmf_float(npy_float, npy_float, npy_float);
+npy_double binom_pmf_double(npy_double, npy_double, npy_double);
+npy_float binom_ppf_float(npy_float, npy_float, npy_float);
+npy_double binom_ppf_double(npy_double, npy_double, npy_double);
+npy_float binom_sf_float(npy_float, npy_float, npy_float);
+npy_double binom_sf_double(npy_double, npy_double, npy_double);
+npy_float cauchy_isf_float(npy_float, npy_float, npy_float);
+npy_double cauchy_isf_double(npy_double, npy_double, npy_double);
+npy_float cauchy_ppf_float(npy_float, npy_float, npy_float);
+npy_double cauchy_ppf_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_mean_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_mean_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_pmf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_pmf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_sf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_sf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_skewness_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_skewness_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_variance_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_variance_double(npy_double, npy_double, npy_double);
+npy_float invgauss_isf_float(npy_float, npy_float, npy_float);
+npy_double invgauss_isf_double(npy_double, npy_double, npy_double);
+npy_float invgauss_ppf_float(npy_float, npy_float, npy_float);
+npy_double invgauss_ppf_double(npy_double, npy_double, npy_double);
+npy_float landau_cdf_float(npy_float, npy_float, npy_float);
+npy_double landau_cdf_double(npy_double, npy_double, npy_double);
+npy_float landau_isf_float(npy_float, npy_float, npy_float);
+npy_double landau_isf_double(npy_double, npy_double, npy_double);
+npy_float landau_pdf_float(npy_float, npy_float, npy_float);
+npy_double landau_pdf_double(npy_double, npy_double, npy_double);
+npy_float landau_ppf_float(npy_float, npy_float, npy_float);
+npy_double landau_ppf_double(npy_double, npy_double, npy_double);
+npy_float landau_sf_float(npy_float, npy_float, npy_float);
+npy_double landau_sf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_cdf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_cdf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_isf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_isf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_kurtosis_excess_float(npy_float, npy_float);
+npy_double nbinom_kurtosis_excess_double(npy_double, npy_double);
+npy_float nbinom_mean_float(npy_float, npy_float);
+npy_double nbinom_mean_double(npy_double, npy_double);
+npy_float nbinom_pmf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_pmf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_ppf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_ppf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_sf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_sf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_skewness_float(npy_float, npy_float);
+npy_double nbinom_skewness_double(npy_double, npy_double);
+npy_float nbinom_variance_float(npy_float, npy_float);
+npy_double nbinom_variance_double(npy_double, npy_double);
+npy_float ncf_isf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_isf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_kurtosis_excess_float(npy_float, npy_float, npy_float);
+npy_double ncf_kurtosis_excess_double(npy_double, npy_double, npy_double);
+npy_float ncf_mean_float(npy_float, npy_float, npy_float);
+npy_double ncf_mean_double(npy_double, npy_double, npy_double);
+npy_float ncf_pdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_pdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_sf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_sf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_skewness_float(npy_float, npy_float, npy_float);
+npy_double ncf_skewness_double(npy_double, npy_double, npy_double);
+npy_float ncf_variance_float(npy_float, npy_float, npy_float);
+npy_double ncf_variance_double(npy_double, npy_double, npy_double);
+npy_float nct_isf_float(npy_float, npy_float, npy_float);
+npy_double nct_isf_double(npy_double, npy_double, npy_double);
+npy_float nct_kurtosis_excess_float(npy_float, npy_float);
+npy_double nct_kurtosis_excess_double(npy_double, npy_double);
+npy_float nct_mean_float(npy_float, npy_float);
+npy_double nct_mean_double(npy_double, npy_double);
+npy_float nct_pdf_float(npy_float, npy_float, npy_float);
+npy_double nct_pdf_double(npy_double, npy_double, npy_double);
+npy_float nct_ppf_float(npy_float, npy_float, npy_float);
+npy_double nct_ppf_double(npy_double, npy_double, npy_double);
+npy_float nct_sf_float(npy_float, npy_float, npy_float);
+npy_double nct_sf_double(npy_double, npy_double, npy_double);
+npy_float nct_skewness_float(npy_float, npy_float);
+npy_double nct_skewness_double(npy_double, npy_double);
+npy_float nct_variance_float(npy_float, npy_float);
+npy_double nct_variance_double(npy_double, npy_double);
+npy_float ncx2_cdf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_cdf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_isf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_isf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_pdf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_pdf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_ppf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_ppf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_sf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_sf_double(npy_double, npy_double, npy_double);
+npy_float skewnorm_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float skewnorm_isf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_isf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float skewnorm_ppf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_ppf_double(npy_double, npy_double, npy_double, npy_double);
+#include "stirling2.h"
+npy_double _stirling2_inexact(npy_double, npy_double);
+npy_float ibeta_float(npy_float, npy_float, npy_float);
+npy_double ibeta_double(npy_double, npy_double, npy_double);
+npy_float ibetac_float(npy_float, npy_float, npy_float);
+npy_double ibetac_double(npy_double, npy_double, npy_double);
+npy_float ibetac_inv_float(npy_float, npy_float, npy_float);
+npy_double ibetac_inv_double(npy_double, npy_double, npy_double);
+npy_float ibeta_inv_float(npy_float, npy_float, npy_float);
+npy_double ibeta_inv_double(npy_double, npy_double, npy_double);
+#include "_faddeeva.h"
+npy_double faddeeva_dawsn(npy_double);
+npy_cdouble faddeeva_dawsn_complex(npy_cdouble);
+#include "ellint_carlson_wrap.hh"
+npy_double fellint_RC(npy_double, npy_double);
+npy_cdouble cellint_RC(npy_cdouble, npy_cdouble);
+npy_double fellint_RD(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RD(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RF(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RF(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RG(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RG(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RJ(npy_double, npy_double, npy_double, npy_double);
+npy_cdouble cellint_RJ(npy_cdouble, npy_cdouble, npy_cdouble, npy_cdouble);
+npy_cdouble faddeeva_erf(npy_cdouble);
+npy_cdouble faddeeva_erfc_complex(npy_cdouble);
+npy_double faddeeva_erfcx(npy_double);
+npy_cdouble faddeeva_erfcx_complex(npy_cdouble);
+npy_double faddeeva_erfi(npy_double);
+npy_cdouble faddeeva_erfi_complex(npy_cdouble);
+npy_float erfinv_float(npy_float);
+npy_double erfinv_double(npy_double);
+npy_double hyp1f1_double(npy_double, npy_double, npy_double);
+npy_double faddeeva_log_ndtr(npy_double);
+npy_cdouble faddeeva_log_ndtr_complex(npy_cdouble);
+npy_float ncf_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_ppf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_ppf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float nct_cdf_float(npy_float, npy_float, npy_float);
+npy_double nct_cdf_double(npy_double, npy_double, npy_double);
+npy_cdouble faddeeva_ndtr(npy_cdouble);
+npy_float powm1_float(npy_float, npy_float);
+npy_double powm1_double(npy_double, npy_double);
+npy_double faddeeva_voigt_profile(npy_double, npy_double, npy_double);
+npy_cdouble faddeeva_w(npy_cdouble);
+#include "_wright.h"
+npy_cdouble wrightomega(npy_cdouble);
+npy_double wrightomega_real(npy_double);
+#endif
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..86d2349d2b7881b71bfdec2a60a78e2bfc18f9fe
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h
@@ -0,0 +1,65 @@
+#ifndef UFUNCS_PROTO_H
+#define UFUNCS_PROTO_H 1
+#include "_cosine.h"
+npy_double cosine_cdf(npy_double);
+npy_double cosine_invcdf(npy_double);
+#include "xsf_wrappers.h"
+npy_double cephes_igam_fac(npy_double, npy_double);
+npy_double xsf_kolmogc(npy_double);
+npy_double xsf_kolmogci(npy_double);
+npy_double xsf_kolmogp(npy_double);
+npy_double cephes_lanczos_sum_expg_scaled(npy_double);
+npy_double cephes_lgam1p(npy_double);
+npy_double cephes_log1pmx(npy_double);
+npy_double cephes_smirnovc_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovci_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovp_wrap(npy_intp, npy_double);
+npy_double cephes__struve_asymp_large_z(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes__struve_bessel_series(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes__struve_power_series(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes_bdtr_wrap(npy_double, npy_intp, npy_double);
+npy_double cephes_bdtrc_wrap(npy_double, npy_intp, npy_double);
+npy_double cephes_bdtri_wrap(npy_double, npy_intp, npy_double);
+npy_double xsf_chdtr(npy_double, npy_double);
+npy_double xsf_chdtrc(npy_double, npy_double);
+npy_double xsf_chdtri(npy_double, npy_double);
+npy_double cephes_erf(npy_double);
+npy_double cephes_erfc(npy_double);
+npy_double cephes_erfcinv(npy_double);
+npy_double cephes_exp10(npy_double);
+npy_double cephes_exp2(npy_double);
+npy_double cephes_expm1(npy_double);
+npy_double cephes_expn_wrap(npy_intp, npy_double);
+npy_double xsf_fdtr(npy_double, npy_double, npy_double);
+npy_double xsf_fdtrc(npy_double, npy_double, npy_double);
+npy_double xsf_fdtri(npy_double, npy_double, npy_double);
+npy_double xsf_gdtr(npy_double, npy_double, npy_double);
+npy_double xsf_gdtrc(npy_double, npy_double, npy_double);
+npy_double xsf_gdtrib(npy_double, npy_double, npy_double);
+npy_cdouble chyp1f1_wrap(npy_double, npy_double, npy_cdouble);
+npy_double special_cyl_bessel_k_int(npy_intp, npy_double);
+npy_double xsf_kolmogi(npy_double);
+npy_double xsf_kolmogorov(npy_double);
+npy_double cephes_log1p(npy_double);
+npy_double pmv_wrap(npy_double, npy_double, npy_double);
+npy_double cephes_nbdtr_wrap(npy_intp, npy_intp, npy_double);
+npy_double cephes_nbdtrc_wrap(npy_intp, npy_intp, npy_double);
+npy_double cephes_nbdtri_wrap(npy_intp, npy_intp, npy_double);
+npy_double xsf_ndtr(npy_double);
+npy_double xsf_ndtri(npy_double);
+npy_double xsf_owens_t(npy_double, npy_double);
+npy_double xsf_pdtr(npy_double, npy_double);
+npy_double xsf_pdtrc(npy_double, npy_double);
+npy_double cephes_pdtri_wrap(npy_intp, npy_double);
+npy_double cephes_poch(npy_double, npy_double);
+npy_double cephes_round(npy_double);
+npy_int xsf_cshichi(npy_cdouble, npy_cdouble *, npy_cdouble *);
+npy_int xsf_shichi(npy_double, npy_double *, npy_double *);
+npy_int xsf_csici(npy_cdouble, npy_cdouble *, npy_cdouble *);
+npy_int xsf_sici(npy_double, npy_double *, npy_double *);
+npy_double cephes_smirnov_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovi_wrap(npy_intp, npy_double);
+npy_double cephes_spence(npy_double);
+npy_double xsf_tukeylambdacdf(npy_double, npy_double);
+npy_double cephes_yn_wrap(npy_intp, npy_double);
+#endif
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..5549717d35710d71655e42c836625cde9346bcc3
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.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="special", module="add_newdocs",
+                                   private_modules=["_add_newdocs"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/basic.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..e55695f44d05187d6c83f1ebefd70270af2c2d76
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/basic.py
@@ -0,0 +1,87 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'ai_zeros',
+    'assoc_laguerre',
+    'bei_zeros',
+    'beip_zeros',
+    'ber_zeros',
+    'bernoulli',
+    'berp_zeros',
+    'bi_zeros',
+    'clpmn',
+    'comb',
+    'digamma',
+    'diric',
+    'erf_zeros',
+    'euler',
+    'factorial',
+    'factorial2',
+    'factorialk',
+    'fresnel_zeros',
+    'fresnelc_zeros',
+    'fresnels_zeros',
+    'gamma',
+    'h1vp',
+    'h2vp',
+    'hankel1',
+    'hankel2',
+    'iv',
+    'ivp',
+    'jn_zeros',
+    'jnjnp_zeros',
+    'jnp_zeros',
+    'jnyn_zeros',
+    'jv',
+    'jvp',
+    'kei_zeros',
+    'keip_zeros',
+    'kelvin_zeros',
+    'ker_zeros',
+    'kerp_zeros',
+    'kv',
+    'kvp',
+    'lmbda',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'lqn',
+    'mathieu_a',
+    'mathieu_b',
+    'mathieu_even_coef',
+    'mathieu_odd_coef',
+    'obl_cv_seq',
+    'pbdn_seq',
+    'pbdv_seq',
+    'pbvv_seq',
+    'perm',
+    'polygamma',
+    'pro_cv_seq',
+    'psi',
+    'riccati_jn',
+    'riccati_yn',
+    'sinc',
+    'y0_zeros',
+    'y1_zeros',
+    'y1p_zeros',
+    'yn_zeros',
+    'ynp_zeros',
+    'yv',
+    'yvp',
+    'zeta'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="basic",
+                                   private_modules=["_basic", "_ufuncs"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..c5d323fbd5f04ec56749505bc24feb080a851506
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd
@@ -0,0 +1,259 @@
+
+ctypedef fused number_t:
+    double complex
+    double
+
+cpdef number_t spherical_jn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_yn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_in(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_kn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+
+ctypedef fused Dd_number_t:
+    double complex
+    double
+
+ctypedef fused df_number_t:
+    double
+    float
+
+ctypedef fused dfg_number_t:
+    double
+    float
+    long double
+
+ctypedef fused dlp_number_t:
+    double
+    long
+    Py_ssize_t
+
+cpdef double voigt_profile(double x0, double x1, double x2) noexcept nogil
+cpdef double agm(double x0, double x1) noexcept nogil
+cdef void airy(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1, Dd_number_t *y2, Dd_number_t *y3) noexcept nogil
+cdef void airye(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1, Dd_number_t *y2, Dd_number_t *y3) noexcept nogil
+cpdef double bdtr(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtrc(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtri(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtrik(double x0, double x1, double x2) noexcept nogil
+cpdef double bdtrin(double x0, double x1, double x2) noexcept nogil
+cpdef double bei(double x0) noexcept nogil
+cpdef double beip(double x0) noexcept nogil
+cpdef double ber(double x0) noexcept nogil
+cpdef double berp(double x0) noexcept nogil
+cpdef double besselpoly(double x0, double x1, double x2) noexcept nogil
+cpdef double beta(double x0, double x1) noexcept nogil
+cpdef df_number_t betainc(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betaincc(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betaincinv(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betainccinv(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef double betaln(double x0, double x1) noexcept nogil
+cpdef double binom(double x0, double x1) noexcept nogil
+cpdef double boxcox(double x0, double x1) noexcept nogil
+cpdef double boxcox1p(double x0, double x1) noexcept nogil
+cpdef double btdtria(double x0, double x1, double x2) noexcept nogil
+cpdef double btdtrib(double x0, double x1, double x2) noexcept nogil
+cpdef double cbrt(double x0) noexcept nogil
+cpdef double chdtr(double x0, double x1) noexcept nogil
+cpdef double chdtrc(double x0, double x1) noexcept nogil
+cpdef double chdtri(double x0, double x1) noexcept nogil
+cpdef double chdtriv(double x0, double x1) noexcept nogil
+cpdef double chndtr(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtridf(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtrinc(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtrix(double x0, double x1, double x2) noexcept nogil
+cpdef double cosdg(double x0) noexcept nogil
+cpdef double cosm1(double x0) noexcept nogil
+cpdef double cotdg(double x0) noexcept nogil
+cpdef Dd_number_t dawsn(Dd_number_t x0) noexcept nogil
+cpdef double ellipe(double x0) noexcept nogil
+cpdef double ellipeinc(double x0, double x1) noexcept nogil
+cdef void ellipj(double x0, double x1, double *y0, double *y1, double *y2, double *y3) noexcept nogil
+cpdef double ellipkinc(double x0, double x1) noexcept nogil
+cpdef double ellipkm1(double x0) noexcept nogil
+cpdef double ellipk(double x0) noexcept nogil
+cpdef Dd_number_t elliprc(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t elliprd(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprf(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprg(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprj(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2, Dd_number_t x3) noexcept nogil
+cpdef double entr(double x0) noexcept nogil
+cpdef Dd_number_t erf(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfc(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfcx(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfi(Dd_number_t x0) noexcept nogil
+cpdef df_number_t erfinv(df_number_t x0) noexcept nogil
+cpdef double erfcinv(double x0) noexcept nogil
+cpdef Dd_number_t eval_chebyc(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebys(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebyt(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebyu(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_gegenbauer(dlp_number_t x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t eval_genlaguerre(dlp_number_t x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef double eval_hermite(Py_ssize_t x0, double x1) noexcept nogil
+cpdef double eval_hermitenorm(Py_ssize_t x0, double x1) noexcept nogil
+cpdef Dd_number_t eval_jacobi(dlp_number_t x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef Dd_number_t eval_laguerre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_legendre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_chebyt(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_chebyu(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_jacobi(dlp_number_t x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef Dd_number_t eval_sh_legendre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t exp1(Dd_number_t x0) noexcept nogil
+cpdef double exp10(double x0) noexcept nogil
+cpdef double exp2(double x0) noexcept nogil
+cpdef Dd_number_t expi(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t expit(dfg_number_t x0) noexcept nogil
+cpdef Dd_number_t expm1(Dd_number_t x0) noexcept nogil
+cpdef double expn(dlp_number_t x0, double x1) noexcept nogil
+cpdef double exprel(double x0) noexcept nogil
+cpdef double fdtr(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtrc(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtri(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtridfd(double x0, double x1, double x2) noexcept nogil
+cdef void fresnel(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cpdef Dd_number_t gamma(Dd_number_t x0) noexcept nogil
+cpdef double gammainc(double x0, double x1) noexcept nogil
+cpdef double gammaincc(double x0, double x1) noexcept nogil
+cpdef double gammainccinv(double x0, double x1) noexcept nogil
+cpdef double gammaincinv(double x0, double x1) noexcept nogil
+cpdef double gammaln(double x0) noexcept nogil
+cpdef double gammasgn(double x0) noexcept nogil
+cpdef double gdtr(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrc(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtria(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrib(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrix(double x0, double x1, double x2) noexcept nogil
+cpdef double complex hankel1(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel1e(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel2(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel2e(double x0, double complex x1) noexcept nogil
+cpdef double huber(double x0, double x1) noexcept nogil
+cpdef Dd_number_t hyp0f1(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t hyp1f1(double x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t hyp2f1(double x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef double hyperu(double x0, double x1, double x2) noexcept nogil
+cpdef double i0(double x0) noexcept nogil
+cpdef double i0e(double x0) noexcept nogil
+cpdef double i1(double x0) noexcept nogil
+cpdef double i1e(double x0) noexcept nogil
+cpdef double inv_boxcox(double x0, double x1) noexcept nogil
+cpdef double inv_boxcox1p(double x0, double x1) noexcept nogil
+cdef void it2i0k0(double x0, double *y0, double *y1) noexcept nogil
+cdef void it2j0y0(double x0, double *y0, double *y1) noexcept nogil
+cpdef double it2struve0(double x0) noexcept nogil
+cdef void itairy(double x0, double *y0, double *y1, double *y2, double *y3) noexcept nogil
+cdef void iti0k0(double x0, double *y0, double *y1) noexcept nogil
+cdef void itj0y0(double x0, double *y0, double *y1) noexcept nogil
+cpdef double itmodstruve0(double x0) noexcept nogil
+cpdef double itstruve0(double x0) noexcept nogil
+cpdef Dd_number_t iv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t ive(double x0, Dd_number_t x1) noexcept nogil
+cpdef double j0(double x0) noexcept nogil
+cpdef double j1(double x0) noexcept nogil
+cpdef Dd_number_t jv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t jve(double x0, Dd_number_t x1) noexcept nogil
+cpdef double k0(double x0) noexcept nogil
+cpdef double k0e(double x0) noexcept nogil
+cpdef double k1(double x0) noexcept nogil
+cpdef double k1e(double x0) noexcept nogil
+cpdef double kei(double x0) noexcept nogil
+cpdef double keip(double x0) noexcept nogil
+cdef void kelvin(double x0, double complex *y0, double complex *y1, double complex *y2, double complex *y3) noexcept nogil
+cpdef double ker(double x0) noexcept nogil
+cpdef double kerp(double x0) noexcept nogil
+cpdef double kl_div(double x0, double x1) noexcept nogil
+cpdef double kn(dlp_number_t x0, double x1) noexcept nogil
+cpdef double kolmogi(double x0) noexcept nogil
+cpdef double kolmogorov(double x0) noexcept nogil
+cpdef Dd_number_t kv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t kve(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t log1p(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t log_expit(dfg_number_t x0) noexcept nogil
+cpdef Dd_number_t log_ndtr(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t loggamma(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t logit(dfg_number_t x0) noexcept nogil
+cpdef double lpmv(double x0, double x1, double x2) noexcept nogil
+cpdef double mathieu_a(double x0, double x1) noexcept nogil
+cpdef double mathieu_b(double x0, double x1) noexcept nogil
+cdef void mathieu_cem(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modcem1(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modcem2(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modsem1(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modsem2(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_sem(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void modfresnelm(double x0, double complex *y0, double complex *y1) noexcept nogil
+cdef void modfresnelp(double x0, double complex *y0, double complex *y1) noexcept nogil
+cpdef double modstruve(double x0, double x1) noexcept nogil
+cpdef double nbdtr(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtrc(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtri(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtrik(double x0, double x1, double x2) noexcept nogil
+cpdef double nbdtrin(double x0, double x1, double x2) noexcept nogil
+cpdef df_number_t ncfdtr(df_number_t x0, df_number_t x1, df_number_t x2, df_number_t x3) noexcept nogil
+cpdef df_number_t ncfdtri(df_number_t x0, df_number_t x1, df_number_t x2, df_number_t x3) noexcept nogil
+cpdef double ncfdtridfd(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef double ncfdtridfn(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef double ncfdtrinc(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef df_number_t nctdtr(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef double nctdtridf(double x0, double x1, double x2) noexcept nogil
+cpdef double nctdtrinc(double x0, double x1, double x2) noexcept nogil
+cpdef double nctdtrit(double x0, double x1, double x2) noexcept nogil
+cpdef Dd_number_t ndtr(Dd_number_t x0) noexcept nogil
+cpdef double ndtri(double x0) noexcept nogil
+cpdef double nrdtrimn(double x0, double x1, double x2) noexcept nogil
+cpdef double nrdtrisd(double x0, double x1, double x2) noexcept nogil
+cdef void obl_ang1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_ang1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double obl_cv(double x0, double x1, double x2) noexcept nogil
+cdef void obl_rad1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_rad1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cdef void obl_rad2(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_rad2_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double owens_t(double x0, double x1) noexcept nogil
+cdef void pbdv(double x0, double x1, double *y0, double *y1) noexcept nogil
+cdef void pbvv(double x0, double x1, double *y0, double *y1) noexcept nogil
+cdef void pbwa(double x0, double x1, double *y0, double *y1) noexcept nogil
+cpdef double pdtr(double x0, double x1) noexcept nogil
+cpdef double pdtrc(double x0, double x1) noexcept nogil
+cpdef double pdtri(dlp_number_t x0, double x1) noexcept nogil
+cpdef double pdtrik(double x0, double x1) noexcept nogil
+cpdef double poch(double x0, double x1) noexcept nogil
+cpdef df_number_t powm1(df_number_t x0, df_number_t x1) noexcept nogil
+cdef void pro_ang1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_ang1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double pro_cv(double x0, double x1, double x2) noexcept nogil
+cdef void pro_rad1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_rad1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cdef void pro_rad2(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_rad2_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double pseudo_huber(double x0, double x1) noexcept nogil
+cpdef Dd_number_t psi(Dd_number_t x0) noexcept nogil
+cpdef double radian(double x0, double x1, double x2) noexcept nogil
+cpdef double rel_entr(double x0, double x1) noexcept nogil
+cpdef Dd_number_t rgamma(Dd_number_t x0) noexcept nogil
+cpdef double round(double x0) noexcept nogil
+cdef void shichi(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cdef void sici(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cpdef double sindg(double x0) noexcept nogil
+cpdef double smirnov(dlp_number_t x0, double x1) noexcept nogil
+cpdef double smirnovi(dlp_number_t x0, double x1) noexcept nogil
+cpdef Dd_number_t spence(Dd_number_t x0) noexcept nogil
+cpdef double complex sph_harm(dlp_number_t x0, dlp_number_t x1, double x2, double x3) noexcept nogil
+cpdef double stdtr(double x0, double x1) noexcept nogil
+cpdef double stdtridf(double x0, double x1) noexcept nogil
+cpdef double stdtrit(double x0, double x1) noexcept nogil
+cpdef double struve(double x0, double x1) noexcept nogil
+cpdef double tandg(double x0) noexcept nogil
+cpdef double tklmbda(double x0, double x1) noexcept nogil
+cpdef double complex wofz(double complex x0) noexcept nogil
+cpdef Dd_number_t wrightomega(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t xlog1py(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t xlogy(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef double y0(double x0) noexcept nogil
+cpdef double y1(double x0) noexcept nogil
+cpdef double yn(dlp_number_t x0, double x1) noexcept nogil
+cpdef Dd_number_t yv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t yve(double x0, Dd_number_t x1) noexcept nogil
+cpdef double zetac(double x0) noexcept nogil
+cpdef double wright_bessel(double x0, double x1, double x2) noexcept nogil
+cpdef double log_wright_bessel(double x0, double x1, double x2) noexcept nogil
+cpdef double ndtri_exp(double x0) noexcept nogil
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..024e962b10df8892631eaad20223f7fc8378ea83
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name) -> Any: ...
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so
new file mode 100644
index 0000000000000000000000000000000000000000..84e37bedbdfcc83bb65efc5d7f1961f2b749ebeb
Binary files /dev/null and b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so differ
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b13a08a96cb683d72a4a00d6962446e1779c88a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py
@@ -0,0 +1,45 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+_polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys',
+             'jacobi', 'laguerre', 'genlaguerre', 'hermite',
+             'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt',
+             'sh_chebyu', 'sh_jacobi']
+
+# Correspondence between new and old names of root functions
+_rootfuns_map = {'roots_legendre': 'p_roots',
+               'roots_chebyt': 't_roots',
+               'roots_chebyu': 'u_roots',
+               'roots_chebyc': 'c_roots',
+               'roots_chebys': 's_roots',
+               'roots_jacobi': 'j_roots',
+               'roots_laguerre': 'l_roots',
+               'roots_genlaguerre': 'la_roots',
+               'roots_hermite': 'h_roots',
+               'roots_hermitenorm': 'he_roots',
+               'roots_gegenbauer': 'cg_roots',
+               'roots_sh_legendre': 'ps_roots',
+               'roots_sh_chebyt': 'ts_roots',
+               'roots_sh_chebyu': 'us_roots',
+               'roots_sh_jacobi': 'js_roots'}
+
+
+__all__ = _polyfuns + list(_rootfuns_map.keys()) + [  # noqa: F822
+    'airy', 'p_roots', 't_roots', 'u_roots', 'c_roots', 's_roots',
+    'j_roots', 'l_roots', 'la_roots', 'h_roots', 'he_roots', 'cg_roots',
+    'ps_roots', 'ts_roots', 'us_roots', 'js_roots'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="orthogonal",
+                                   private_modules=["_orthogonal"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/sf_error.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ff73756acd4219a4ba94eb089bce7d4c32266d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/sf_error.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.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'SpecialFunctionWarning',
+    'SpecialFunctionError'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="sf_error",
+                                   private_modules=["_sf_error"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/specfun.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/specfun.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fca00415a6406b8cdf41a42b6fbf991cea1f53f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/specfun.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.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+# ruff: noqa: F822
+__all__ = [
+    'clpmn',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'pbdv'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="specfun",
+                                   private_modules=["_basic", "_specfun"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1e58487aaa547483c9f2531ac4efc2ad5e4795c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.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.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ['multigammaln']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="spfun_stats",
+                                   private_modules=["_spfun_stats"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..132fb9ab11ec19d8efa00c5bb96f851795017d31
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py
@@ -0,0 +1,61 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.special._ufuncs as scu
+from scipy.integrate import tanhsinh
+
+
+type_char_to_type_tol = {'f': (np.float32, 32*np.finfo(np.float32).eps),
+                         'd': (np.float64, 32*np.finfo(np.float64).eps)}
+
+
+# Each item in this list is
+#   (func, args, expected_value)
+# All the values can be represented exactly, even with np.float32.
+#
+# This is not an exhaustive test data set of all the functions!
+# It is a spot check of several functions, primarily for
+# checking that the different data types are handled correctly.
+test_data = [
+    (scu._beta_pdf, (0.5, 2, 3), 1.5),
+    (scu._beta_pdf, (0, 1, 5), 5.0),
+    (scu._beta_pdf, (1, 5, 1), 5.0),
+    (scu._beta_ppf, (0.5, 5., 5.), 0.5),  # gh-21303
+    (scu._binom_cdf, (1, 3, 0.5), 0.5),
+    (scu._binom_pmf, (1, 4, 0.5), 0.25),
+    (scu._hypergeom_cdf, (2, 3, 5, 6), 0.5),
+    (scu._nbinom_cdf, (1, 4, 0.25), 0.015625),
+    (scu._ncf_mean, (10, 12, 2.5), 1.5),
+]
+
+
+@pytest.mark.parametrize('func, args, expected', test_data)
+def test_stats_boost_ufunc(func, args, expected):
+    type_sigs = func.types
+    type_chars = [sig.split('->')[-1] for sig in type_sigs]
+    for type_char in type_chars:
+        typ, rtol = type_char_to_type_tol[type_char]
+        args = [typ(arg) for arg in args]
+        # Harmless overflow warnings are a "feature" of some wrappers on some
+        # platforms. This test is about dtype and accuracy, so let's avoid false
+        # test failures cause by these warnings. See gh-17432.
+        with np.errstate(over='ignore'):
+            value = func(*args)
+        assert isinstance(value, typ)
+        assert_allclose(value, expected, rtol=rtol)
+
+
+def test_landau():
+    # Test that Landau distribution ufuncs are wrapped as expected;
+    # accuracy is tested by Boost.
+    x = np.linspace(-3, 10, 10)
+    args = (0, 1)
+    res = tanhsinh(lambda x: scu._landau_pdf(x, *args), -np.inf, x)
+    cdf = scu._landau_cdf(x, *args)
+    assert_allclose(res.integral, cdf)
+    sf = scu._landau_sf(x, *args)
+    assert_allclose(sf, 1-cdf)
+    ppf = scu._landau_ppf(cdf, *args)
+    assert_allclose(ppf, x)
+    isf = scu._landau_isf(sf, *args)
+    assert_allclose(isf, x, rtol=1e-6)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ecaf51545e006e37a451a08f356ce0392a3159c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py
@@ -0,0 +1,28 @@
+import os
+import platform
+import sysconfig
+
+import pytest
+
+from scipy._lib._testutils import IS_EDITABLE,_test_cython_extension, cython
+from scipy.special import beta, gamma
+
+
+@pytest.mark.fail_slow(40)
+# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247
+@pytest.mark.skipif(IS_EDITABLE,
+                    reason='Editable install cannot find .pxd headers.')
+@pytest.mark.skipif((platform.system() == 'Windows' and
+                     sysconfig.get_config_var('Py_GIL_DISABLED')),
+                    reason='gh-22039')
+@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"],
+                    reason="Can't start subprocess")
+@pytest.mark.skipif(cython is None, reason="requires cython")
+def test_cython(tmp_path):
+    srcdir = os.path.dirname(os.path.dirname(__file__))
+    extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir)
+    # actually test the cython c-extensions
+    assert extensions.cy_beta(0.5, 0.1) == beta(0.5, 0.1)
+    assert extensions.cy_gamma(0.5 + 1.0j) == gamma(0.5 + 1.0j)
+    assert extensions_cpp.cy_beta(0.5, 0.1) == beta(0.5, 0.1)
+    assert extensions_cpp.cy_gamma(0.5 + 1.0j) == gamma(0.5 + 1.0j)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py
new file mode 100644
index 0000000000000000000000000000000000000000..8868f66c47ce0d4bbb21c78435a6c89d44065252
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py
@@ -0,0 +1,85 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.special as sc
+from scipy.special._testutils import FuncData
+
+
+class TestVoigtProfile:
+
+    @pytest.mark.parametrize('x, sigma, gamma', [
+        (np.nan, 1, 1),
+        (0, np.nan, 1),
+        (0, 1, np.nan),
+        (1, np.nan, 0),
+        (np.nan, 1, 0),
+        (1, 0, np.nan),
+        (np.nan, 0, 1),
+        (np.nan, 0, 0)
+    ])
+    def test_nan(self, x, sigma, gamma):
+        assert np.isnan(sc.voigt_profile(x, sigma, gamma))
+
+    @pytest.mark.parametrize('x, desired', [
+        (-np.inf, 0),
+        (np.inf, 0)
+    ])
+    def test_inf(self, x, desired):
+        assert sc.voigt_profile(x, 1, 1) == desired
+
+    def test_against_mathematica(self):
+        # Results obtained from Mathematica by computing
+        #
+        # PDF[VoigtDistribution[gamma, sigma], x]
+        #
+        points = np.array([
+            [-7.89, 45.06, 6.66, 0.0077921073660388806401],
+            [-0.05, 7.98, 24.13, 0.012068223646769913478],
+            [-13.98, 16.83, 42.37, 0.0062442236362132357833],
+            [-12.66, 0.21, 6.32, 0.010052516161087379402],
+            [11.34, 4.25, 21.96, 0.0113698923627278917805],
+            [-11.56, 20.40, 30.53, 0.0076332760432097464987],
+            [-9.17, 25.61, 8.32, 0.011646345779083005429],
+            [16.59, 18.05, 2.50, 0.013637768837526809181],
+            [9.11, 2.12, 39.33, 0.0076644040807277677585],
+            [-43.33, 0.30, 45.68, 0.0036680463875330150996]
+        ])
+        FuncData(
+            sc.voigt_profile,
+            points,
+            (0, 1, 2),
+            3,
+            atol=0,
+            rtol=1e-15
+        ).check()
+
+    def test_symmetry(self):
+        x = np.linspace(0, 10, 20)
+        assert_allclose(
+            sc.voigt_profile(x, 1, 1),
+            sc.voigt_profile(-x, 1, 1),
+            rtol=1e-15,
+            atol=0
+        )
+
+    @pytest.mark.parametrize('x, sigma, gamma, desired', [
+        (0, 0, 0, np.inf),
+        (1, 0, 0, 0)
+    ])
+    def test_corner_cases(self, x, sigma, gamma, desired):
+        assert sc.voigt_profile(x, sigma, gamma) == desired
+
+    @pytest.mark.parametrize('sigma1, gamma1, sigma2, gamma2', [
+        (0, 1, 1e-16, 1),
+        (1, 0, 1, 1e-16),
+        (0, 0, 1e-16, 1e-16)
+    ])
+    def test_continuity(self, sigma1, gamma1, sigma2, gamma2):
+        x = np.linspace(1, 10, 20)
+        assert_allclose(
+            sc.voigt_profile(x, sigma1, gamma1),
+            sc.voigt_profile(x, sigma2, gamma2),
+            rtol=1e-16,
+            atol=1e-16
+        )
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py
new file mode 100644
index 0000000000000000000000000000000000000000..430a4175426e30bde02be7972b3144eed4923b27
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py
@@ -0,0 +1,1518 @@
+import math
+
+import numpy as np
+
+import pytest
+from numpy.testing import (assert_equal, assert_almost_equal, assert_array_almost_equal,
+    assert_allclose, suppress_warnings)
+
+from scipy import special
+from scipy.special import (legendre_p, legendre_p_all, assoc_legendre_p,
+    assoc_legendre_p_all, sph_legendre_p, sph_legendre_p_all)
+
+# The functions lpn, lpmn, clpmn, appearing below are
+# deprecated in favor of legendre_p_all, assoc_legendre_p_all, and
+# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn)
+# respectively. The deprecated functions listed above are implemented as
+# shims around their respective replacements. The replacements are tested
+# separately, but tests for the deprecated functions remain to verify the
+# correctness of the shims.
+
+# Base polynomials come from Abrahmowitz and Stegan
+class TestLegendre:
+    def test_legendre(self):
+        leg0 = special.legendre(0)
+        leg1 = special.legendre(1)
+        leg2 = special.legendre(2)
+        leg3 = special.legendre(3)
+        leg4 = special.legendre(4)
+        leg5 = special.legendre(5)
+        assert_equal(leg0.c, [1])
+        assert_equal(leg1.c, [1,0])
+        assert_almost_equal(leg2.c, np.array([3,0,-1])/2.0, decimal=13)
+        assert_almost_equal(leg3.c, np.array([5,0,-3,0])/2.0)
+        assert_almost_equal(leg4.c, np.array([35,0,-30,0,3])/8.0)
+        assert_almost_equal(leg5.c, np.array([63,0,-70,0,15,0])/8.0)
+
+    @pytest.mark.parametrize('n', [1, 2, 3, 4, 5])
+    @pytest.mark.parametrize('zr', [0.5241717, 12.80232, -9.699001,
+                                    0.5122437, 0.1714377])
+    @pytest.mark.parametrize('zi', [9.766818, 0.2999083, 8.24726, -22.84843,
+                                    -0.8792666])
+    def test_lpn_against_clpmn(self, n, zr, zi):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            reslpn = special.lpn(n, zr + zi*1j)
+            resclpmn = special.clpmn(0, n, zr+zi*1j)
+
+        assert_allclose(reslpn[0], resclpmn[0][0])
+        assert_allclose(reslpn[1], resclpmn[1][0])
+
+class TestLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_ode(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 100, shape)
+        x = rng.uniform(-1, 1, shape)
+
+        p, p_jac, p_hess = legendre_p(n, x, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        err = (1 - x * x) * p_hess - 2 * x * p_jac + n * (n + 1) * p
+        np.testing.assert_allclose(err, 0, atol=1e-10)
+
+    @pytest.mark.parametrize("n_max", [1, 2, 4, 8, 16, 32])
+    @pytest.mark.parametrize("x_shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_all_ode(self, n_max, x_shape):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-1, 1, x_shape)
+        p, p_jac, p_hess = legendre_p_all(n_max, x, diff_n=2)
+
+        n = np.arange(n_max + 1)
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 1)))
+
+        assert p.shape == (len(n),) + x.shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        err = (1 - x * x) * p_hess - 2 * x * p_jac + n * (n + 1) * p
+        np.testing.assert_allclose(err, 0, atol=1e-10)
+
+    def test_legacy(self):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            p, pd = special.lpn(2, 0.5)
+
+        assert_array_almost_equal(p, [1.00000, 0.50000, -0.12500], 4)
+        assert_array_almost_equal(pd, [0.00000, 1.00000, 1.50000], 4)
+
+class TestAssocLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    @pytest.mark.parametrize("m_max", [5, 4])
+    @pytest.mark.parametrize("n_max", [7, 10])
+    def test_lpmn(self, shape, n_max, m_max):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-0.99, 0.99, shape)
+        p_all, p_all_jac, p_all_hess = \
+            assoc_legendre_p_all(n_max, m_max, x, diff_n=2)
+
+        n = np.arange(n_max + 1)
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2)))
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2)))
+
+        x = np.expand_dims(x, axis = (0, 1))
+        p, p_jac, p_hess = assoc_legendre_p(n, m, x, diff_n=2)
+
+        np.testing.assert_allclose(p, p_all)
+        np.testing.assert_allclose(p_jac, p_all_jac)
+        np.testing.assert_allclose(p_hess, p_all_hess)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_ode(self, shape, norm):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 10, shape)
+        m = rng.integers(-10, 10, shape)
+        x = rng.uniform(-1, 1, shape)
+
+        p, p_jac, p_hess = assoc_legendre_p(n, m, x, norm=norm, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        np.testing.assert_allclose((1 - x * x) * p_hess,
+            2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p,
+            rtol=1e-05, atol=1e-08)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_all(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n_max = 20
+        m_max = 20
+
+        x = rng.uniform(-0.99, 0.99, shape)
+
+        p, p_jac, p_hess = assoc_legendre_p_all(n_max, m_max, x, diff_n=2)
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        n = np.arange(n_max + 1)
+
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2)))
+        m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2)))
+        np.testing.assert_allclose((1 - x * x) * p_hess,
+            2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p,
+            rtol=1e-05, atol=1e-08)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_specific(self, shape, norm):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-0.99, 0.99, shape)
+
+        p, p_jac = assoc_legendre_p_all(4, 4, x, norm=norm, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            assoc_legendre_p_0_0(x, norm=norm))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            assoc_legendre_p_1_0(x, norm=norm))
+        np.testing.assert_allclose(p[1, 1],
+            assoc_legendre_p_1_1(x, norm=norm))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            assoc_legendre_p_1_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[2, 0],
+            assoc_legendre_p_2_0(x, norm=norm))
+        np.testing.assert_allclose(p[2, 1],
+            assoc_legendre_p_2_1(x, norm=norm))
+        np.testing.assert_allclose(p[2, 2],
+            assoc_legendre_p_2_2(x, norm=norm))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            assoc_legendre_p_2_m2(x, norm=norm))
+        np.testing.assert_allclose(p[2, -1],
+            assoc_legendre_p_2_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[3, 0],
+            assoc_legendre_p_3_0(x, norm=norm))
+        np.testing.assert_allclose(p[3, 1],
+            assoc_legendre_p_3_1(x, norm=norm))
+        np.testing.assert_allclose(p[3, 2],
+            assoc_legendre_p_3_2(x, norm=norm))
+        np.testing.assert_allclose(p[3, 3],
+            assoc_legendre_p_3_3(x, norm=norm))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            assoc_legendre_p_3_m3(x, norm=norm))
+        np.testing.assert_allclose(p[3, -2],
+            assoc_legendre_p_3_m2(x, norm=norm))
+        np.testing.assert_allclose(p[3, -1],
+            assoc_legendre_p_3_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[4, 0],
+            assoc_legendre_p_4_0(x, norm=norm))
+        np.testing.assert_allclose(p[4, 1],
+            assoc_legendre_p_4_1(x, norm=norm))
+        np.testing.assert_allclose(p[4, 2],
+            assoc_legendre_p_4_2(x, norm=norm))
+        np.testing.assert_allclose(p[4, 3],
+            assoc_legendre_p_4_3(x, norm=norm))
+        np.testing.assert_allclose(p[4, 4],
+            assoc_legendre_p_4_4(x, norm=norm))
+        np.testing.assert_allclose(p[4, -4],
+            assoc_legendre_p_4_m4(x, norm=norm))
+        np.testing.assert_allclose(p[4, -3],
+            assoc_legendre_p_4_m3(x, norm=norm))
+        np.testing.assert_allclose(p[4, -2],
+            assoc_legendre_p_4_m2(x, norm=norm))
+        np.testing.assert_allclose(p[4, -1],
+            assoc_legendre_p_4_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            assoc_legendre_p_0_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            assoc_legendre_p_1_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 1],
+            assoc_legendre_p_1_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            assoc_legendre_p_1_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            assoc_legendre_p_2_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 1],
+            assoc_legendre_p_2_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 2],
+            assoc_legendre_p_2_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            assoc_legendre_p_2_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, -1],
+            assoc_legendre_p_2_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            assoc_legendre_p_3_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 1],
+            assoc_legendre_p_3_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 2],
+            assoc_legendre_p_3_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 3],
+            assoc_legendre_p_3_3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            assoc_legendre_p_3_m3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -2],
+            assoc_legendre_p_3_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -1],
+            assoc_legendre_p_3_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            assoc_legendre_p_4_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 1],
+            assoc_legendre_p_4_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 2],
+            assoc_legendre_p_4_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 3],
+            assoc_legendre_p_4_3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 4],
+            assoc_legendre_p_4_4_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -4],
+            assoc_legendre_p_4_m4_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -3],
+            assoc_legendre_p_4_m3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -2],
+            assoc_legendre_p_4_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -1],
+            assoc_legendre_p_4_m1_jac(x, norm=norm))
+
+    @pytest.mark.parametrize("m_max", [7])
+    @pytest.mark.parametrize("n_max", [10])
+    @pytest.mark.parametrize("x", [1, -1])
+    def test_all_limits(self, m_max, n_max, x):
+        p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1)
+
+        n = np.arange(n_max + 1)
+
+        np.testing.assert_allclose(p_jac[:, 0],
+            pow(x, n + 1) * n * (n + 1) / 2)
+        np.testing.assert_allclose(p_jac[:, 1],
+            np.where(n >= 1, pow(x, n) * np.inf, 0))
+        np.testing.assert_allclose(p_jac[:, 2],
+            np.where(n >= 2, -pow(x, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[:, -2],
+            np.where(n >= 2, -pow(x, n + 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[:, -1],
+            np.where(n >= 1, -pow(x, n) * np.inf, 0))
+
+        for m in range(3, m_max + 1):
+            np.testing.assert_allclose(p_jac[:, m], 0)
+            np.testing.assert_allclose(p_jac[:, -m], 0)
+
+    @pytest.mark.parametrize("m_max", [3, 5, 10])
+    @pytest.mark.parametrize("n_max", [10])
+    def test_legacy(self, m_max, n_max):
+        x = 0.5
+        p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1)
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+
+            p_legacy, p_jac_legacy = special.lpmn(m_max, n_max, x)
+            for m in range(m_max + 1):
+                np.testing.assert_allclose(p_legacy[m], p[:, m])
+
+            p_legacy, p_jac_legacy = special.lpmn(-m_max, n_max, x)
+            for m in range(m_max + 1):
+                np.testing.assert_allclose(p_legacy[m], p[:, -m])
+
+class TestMultiAssocLegendreP:
+    @pytest.mark.parametrize("shape", [(1000,), (4, 9), (3, 5, 7)])
+    @pytest.mark.parametrize("branch_cut", [2, 3])
+    @pytest.mark.parametrize("z_min, z_max", [(-10 - 10j, 10 + 10j),
+        (-1, 1), (-10j, 10j)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_specific(self, shape, branch_cut, z_min, z_max, norm):
+        rng = np.random.default_rng(1234)
+
+        z = rng.uniform(z_min.real, z_max.real, shape) + \
+            1j * rng.uniform(z_min.imag, z_max.imag, shape)
+
+        p, p_jac = assoc_legendre_p_all(4, 4,
+            z, branch_cut=branch_cut, norm=norm, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            assoc_legendre_p_0_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            assoc_legendre_p_1_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[1, 1],
+            assoc_legendre_p_1_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            assoc_legendre_p_1_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[2, 0],
+            assoc_legendre_p_2_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 1],
+            assoc_legendre_p_2_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 2],
+            assoc_legendre_p_2_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            assoc_legendre_p_2_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, -1],
+            assoc_legendre_p_2_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[3, 0],
+            assoc_legendre_p_3_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 1],
+            assoc_legendre_p_3_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 2],
+            assoc_legendre_p_3_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 3],
+            assoc_legendre_p_3_3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            assoc_legendre_p_3_m3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, -2],
+            assoc_legendre_p_3_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, -1],
+            assoc_legendre_p_3_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[4, 0],
+            assoc_legendre_p_4_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 1],
+            assoc_legendre_p_4_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 2],
+            assoc_legendre_p_4_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 3],
+            assoc_legendre_p_4_3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 4],
+            assoc_legendre_p_4_4(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -4],
+            assoc_legendre_p_4_m4(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -3],
+            assoc_legendre_p_4_m3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -2],
+            assoc_legendre_p_4_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -1],
+            assoc_legendre_p_4_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            assoc_legendre_p_0_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            assoc_legendre_p_1_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 1],
+            assoc_legendre_p_1_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            assoc_legendre_p_1_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            assoc_legendre_p_2_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 1],
+            assoc_legendre_p_2_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 2],
+            assoc_legendre_p_2_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            assoc_legendre_p_2_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, -1],
+            assoc_legendre_p_2_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            assoc_legendre_p_3_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 1],
+            assoc_legendre_p_3_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 2],
+            assoc_legendre_p_3_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 3],
+            assoc_legendre_p_3_3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            assoc_legendre_p_3_m3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -2],
+            assoc_legendre_p_3_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -1],
+            assoc_legendre_p_3_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            assoc_legendre_p_4_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 1],
+            assoc_legendre_p_4_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 2],
+            assoc_legendre_p_4_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 3],
+            assoc_legendre_p_4_3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 4],
+            assoc_legendre_p_4_4_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -4],
+            assoc_legendre_p_4_m4_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -3],
+            assoc_legendre_p_4_m3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -2],
+            assoc_legendre_p_4_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -1],
+            assoc_legendre_p_4_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+class TestSphLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_specific(self, shape):
+        rng = np.random.default_rng(1234)
+
+        theta = rng.uniform(-np.pi, np.pi, shape)
+
+        p, p_jac = sph_legendre_p_all(4, 4, theta, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            sph_legendre_p_0_0(theta))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            sph_legendre_p_1_0(theta))
+        np.testing.assert_allclose(p[1, 1],
+            sph_legendre_p_1_1(theta))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            sph_legendre_p_1_m1(theta))
+
+        np.testing.assert_allclose(p[2, 0],
+            sph_legendre_p_2_0(theta))
+        np.testing.assert_allclose(p[2, 1],
+            sph_legendre_p_2_1(theta))
+        np.testing.assert_allclose(p[2, 2],
+            sph_legendre_p_2_2(theta))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            sph_legendre_p_2_m2(theta))
+        np.testing.assert_allclose(p[2, -1],
+            sph_legendre_p_2_m1(theta))
+
+        np.testing.assert_allclose(p[3, 0],
+            sph_legendre_p_3_0(theta))
+        np.testing.assert_allclose(p[3, 1],
+            sph_legendre_p_3_1(theta))
+        np.testing.assert_allclose(p[3, 2],
+            sph_legendre_p_3_2(theta))
+        np.testing.assert_allclose(p[3, 3],
+            sph_legendre_p_3_3(theta))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            sph_legendre_p_3_m3(theta))
+        np.testing.assert_allclose(p[3, -2],
+            sph_legendre_p_3_m2(theta))
+        np.testing.assert_allclose(p[3, -1],
+            sph_legendre_p_3_m1(theta))
+
+        np.testing.assert_allclose(p[4, 0],
+            sph_legendre_p_4_0(theta))
+        np.testing.assert_allclose(p[4, 1],
+            sph_legendre_p_4_1(theta))
+        np.testing.assert_allclose(p[4, 2],
+            sph_legendre_p_4_2(theta))
+        np.testing.assert_allclose(p[4, 3],
+            sph_legendre_p_4_3(theta))
+        np.testing.assert_allclose(p[4, 4],
+            sph_legendre_p_4_4(theta))
+        np.testing.assert_allclose(p[4, -4],
+            sph_legendre_p_4_m4(theta))
+        np.testing.assert_allclose(p[4, -3],
+            sph_legendre_p_4_m3(theta))
+        np.testing.assert_allclose(p[4, -2],
+            sph_legendre_p_4_m2(theta))
+        np.testing.assert_allclose(p[4, -1],
+            sph_legendre_p_4_m1(theta))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            sph_legendre_p_0_0_jac(theta))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            sph_legendre_p_1_0_jac(theta))
+        np.testing.assert_allclose(p_jac[1, 1],
+            sph_legendre_p_1_1_jac(theta))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            sph_legendre_p_1_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            sph_legendre_p_2_0_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 1],
+            sph_legendre_p_2_1_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 2],
+            sph_legendre_p_2_2_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            sph_legendre_p_2_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[2, -1],
+            sph_legendre_p_2_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            sph_legendre_p_3_0_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 1],
+            sph_legendre_p_3_1_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 2],
+            sph_legendre_p_3_2_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 3],
+            sph_legendre_p_3_3_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            sph_legendre_p_3_m3_jac(theta))
+        np.testing.assert_allclose(p_jac[3, -2],
+            sph_legendre_p_3_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[3, -1],
+            sph_legendre_p_3_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            sph_legendre_p_4_0_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 1],
+            sph_legendre_p_4_1_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 2],
+            sph_legendre_p_4_2_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 3],
+            sph_legendre_p_4_3_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 4],
+            sph_legendre_p_4_4_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -4],
+            sph_legendre_p_4_m4_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -3],
+            sph_legendre_p_4_m3_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -2],
+            sph_legendre_p_4_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -1],
+            sph_legendre_p_4_m1_jac(theta))
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    def test_ode(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 10, shape)
+        m = rng.integers(-10, 10, shape)
+        theta = rng.uniform(-np.pi, np.pi, shape)
+
+        p, p_jac, p_hess = sph_legendre_p(n, m, theta, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        np.testing.assert_allclose(np.sin(theta) * p_hess, -np.cos(theta) * p_jac
+            - (n * (n + 1) * np.sin(theta) - m * m / np.sin(theta)) * p,
+            rtol=1e-05, atol=1e-08)
+
+class TestLegendreFunctions:
+    def test_clpmn(self):
+        z = 0.5+0.3j
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp = special.clpmn(2, 2, z, 3)
+
+        assert_array_almost_equal(clp,
+                   (np.array([[1.0000, z, 0.5*(3*z*z-1)],
+                           [0.0000, np.sqrt(z*z-1), 3*z*np.sqrt(z*z-1)],
+                           [0.0000, 0.0000, 3*(z*z-1)]]),
+                    np.array([[0.0000, 1.0000, 3*z],
+                           [0.0000, z/np.sqrt(z*z-1), 3*(2*z*z-1)/np.sqrt(z*z-1)],
+                           [0.0000, 0.0000, 6*z]])),
+                    7)
+
+    def test_clpmn_close_to_real_2(self):
+        eps = 1e-10
+        m = 1
+        n = 3
+        x = 0.5
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n]
+            clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n]
+
+        assert_array_almost_equal(np.array([clp_plus, clp_minus]),
+                                  np.array([special.lpmv(m, n, x),
+                                         special.lpmv(m, n, x)]),
+                                  7)
+
+    def test_clpmn_close_to_real_3(self):
+        eps = 1e-10
+        m = 1
+        n = 3
+        x = 0.5
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n]
+            clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n]
+
+        assert_array_almost_equal(np.array([clp_plus, clp_minus]),
+                                  np.array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi),
+                                         special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]),
+                                  7)
+
+    def test_clpmn_across_unit_circle(self):
+        eps = 1e-7
+        m = 1
+        n = 1
+        x = 1j
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for type in [2, 3]:
+                assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n],
+                                special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6)
+
+    def test_inf(self):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for z in (1, -1):
+                for n in range(4):
+                    for m in range(1, n):
+                        lp = special.clpmn(m, n, z)
+                        assert np.isinf(lp[1][1,1:]).all()
+                        lp = special.lpmn(m, n, z)
+                        assert np.isinf(lp[1][1,1:]).all()
+
+    def test_deriv_clpmn(self):
+        # data inside and outside of the unit circle
+        zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j,
+                 1+1j, -1+1j, -1-1j, 1-1j]
+        m = 2
+        n = 3
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for type in [2, 3]:
+                for z in zvals:
+                    for h in [1e-3, 1e-3j]:
+                        approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0]
+                                            - special.clpmn(m, n, z-0.5*h, type)[0])/h
+                        assert_allclose(special.clpmn(m, n, z, type)[1],
+                                        approx_derivative,
+                                        rtol=1e-4)
+
+    """
+    @pytest.mark.parametrize("m_max", [3])
+    @pytest.mark.parametrize("n_max", [5])
+    @pytest.mark.parametrize("z", [-1])
+    def test_clpmn_all_limits(self, m_max, n_max, z):
+        rng = np.random.default_rng(1234)
+
+        type = 2
+
+        p, p_jac = special.clpmn_all(m_max, n_max, type, z, diff_n=1)
+
+        n = np.arange(n_max + 1)
+
+        np.testing.assert_allclose(p_jac[0], pow(z, n + 1) * n * (n + 1) / 2)
+        np.testing.assert_allclose(p_jac[1], np.where(n >= 1, pow(z, n) * np.inf, 0))
+        np.testing.assert_allclose(p_jac[2], np.where(n >= 2,
+            -pow(z, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[-2], np.where(n >= 2, -pow(z, n + 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[-1], np.where(n >= 1, -pow(z, n) * np.inf, 0))
+
+        for m in range(3, m_max + 1):
+            np.testing.assert_allclose(p_jac[m], 0)
+            np.testing.assert_allclose(p_jac[-m], 0)
+    """
+
+    def test_lpmv(self):
+        lp = special.lpmv(0,2,.5)
+        assert_almost_equal(lp,-0.125,7)
+        lp = special.lpmv(0,40,.001)
+        assert_almost_equal(lp,0.1252678976534484,7)
+
+        # XXX: this is outside the domain of the current implementation,
+        #      so ensure it returns a NaN rather than a wrong answer.
+        with np.errstate(all='ignore'):
+            lp = special.lpmv(-1,-1,.001)
+        assert lp != 0 or np.isnan(lp)
+
+    def test_lqmn(self):
+        lqmnf = special.lqmn(0,2,.5)
+        lqf = special.lqn(2,.5)
+        assert_array_almost_equal(lqmnf[0][0],lqf[0],4)
+        assert_array_almost_equal(lqmnf[1][0],lqf[1],4)
+
+    def test_lqmn_gt1(self):
+        """algorithm for real arguments changes at 1.0001
+           test against analytical result for m=2, n=1
+        """
+        x0 = 1.0001
+        delta = 0.00002
+        for x in (x0-delta, x0+delta):
+            lq = special.lqmn(2, 1, x)[0][-1, -1]
+            expected = 2/(x*x-1)
+            assert_almost_equal(lq, expected)
+
+    def test_lqmn_shape(self):
+        a, b = special.lqmn(4, 4, 1.1)
+        assert_equal(a.shape, (5, 5))
+        assert_equal(b.shape, (5, 5))
+
+        a, b = special.lqmn(4, 0, 1.1)
+        assert_equal(a.shape, (5, 1))
+        assert_equal(b.shape, (5, 1))
+
+    def test_lqn(self):
+        lqf = special.lqn(2,.5)
+        assert_array_almost_equal(lqf,(np.array([0.5493, -0.7253, -0.8187]),
+                                       np.array([1.3333, 1.216, -0.8427])),4)
+
+    @pytest.mark.parametrize("function", [special.lpn, special.lqn])
+    @pytest.mark.parametrize("n", [1, 2, 4, 8, 16, 32])
+    @pytest.mark.parametrize("z_complex", [False, True])
+    @pytest.mark.parametrize("z_inexact", [False, True])
+    @pytest.mark.parametrize(
+        "input_shape",
+        [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1), (2, 2, 2)
+        ]
+    )
+    def test_array_inputs_lxn(self, function, n, z_complex, z_inexact, input_shape):
+        """Tests for correct output shapes."""
+        rng = np.random.default_rng(1234)
+        if z_inexact:
+            z = rng.integers(-3, 3, size=input_shape)
+        else:
+            z = rng.uniform(-1, 1, size=input_shape)
+
+        if z_complex:
+            z = 1j * z + 0.5j * z
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            P_z, P_d_z = function(n, z)
+        assert P_z.shape == (n + 1, ) + input_shape
+        assert P_d_z.shape == (n + 1, ) + input_shape
+
+    @pytest.mark.parametrize("function", [special.lqmn])
+    @pytest.mark.parametrize(
+        "m,n",
+        [(0, 1), (1, 2), (1, 4), (3, 8), (11, 16), (19, 32)]
+    )
+    @pytest.mark.parametrize("z_inexact", [False, True])
+    @pytest.mark.parametrize(
+        "input_shape", [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1)
+        ]
+    )
+    def test_array_inputs_lxmn(self, function, m, n, z_inexact, input_shape):
+        """Tests for correct output shapes and dtypes."""
+        rng = np.random.default_rng(1234)
+        if z_inexact:
+            z = rng.integers(-3, 3, size=input_shape)
+        else:
+            z = rng.uniform(-1, 1, size=input_shape)
+
+        P_z, P_d_z = function(m, n, z)
+        assert P_z.shape == (m + 1, n + 1) + input_shape
+        assert P_d_z.shape == (m + 1, n + 1) + input_shape
+
+    @pytest.mark.parametrize("function", [special.clpmn, special.lqmn])
+    @pytest.mark.parametrize(
+        "m,n",
+        [(0, 1), (1, 2), (1, 4), (3, 8), (11, 16), (19, 32)]
+    )
+    @pytest.mark.parametrize(
+        "input_shape", [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1)
+        ]
+    )
+    def test_array_inputs_clxmn(self, function, m, n, input_shape):
+        """Tests for correct output shapes and dtypes."""
+        rng = np.random.default_rng(1234)
+        z = rng.uniform(-1, 1, size=input_shape)
+        z = 1j * z + 0.5j * z
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            P_z, P_d_z = function(m, n, z)
+
+        assert P_z.shape == (m + 1, n + 1) + input_shape
+        assert P_d_z.shape == (m + 1, n + 1) + input_shape
+
+def assoc_legendre_factor(n, m, norm):
+    if norm:
+        return (math.sqrt((2 * n + 1) *
+            math.factorial(n - m) / (2 * math.factorial(n + m))))
+
+    return 1
+
+def assoc_legendre_p_0_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(0, 0, norm)
+
+    return np.full_like(z, fac)
+
+def assoc_legendre_p_1_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 0, norm)
+
+    return fac * z
+
+def assoc_legendre_p_1_1(z, *, branch_cut=2, norm=False):
+    branch_sign = np.where(branch_cut == 3, np.where(np.signbit(np.real(z)), 1, -1), -1)
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, 1, norm)
+
+    w = np.sqrt(np.where(branch_cut == 3, z * z - 1, 1 - z * z))
+
+    return branch_cut_sign * branch_sign * fac * w
+
+def assoc_legendre_p_1_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, -1, norm)
+
+    return (-branch_cut_sign * fac *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 0, norm)
+
+    return fac * (3 * z * z - 1) / 2
+
+def assoc_legendre_p_2_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 1, norm)
+
+    return (3 * fac * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_2_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, 2, norm)
+
+    return 3 * branch_cut_sign * fac * (1 - z * z)
+
+def assoc_legendre_p_2_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -2, norm)
+
+    return branch_cut_sign * fac * (1 - z * z) / 8
+
+def assoc_legendre_p_2_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -1, norm)
+
+    return (-branch_cut_sign * fac * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 0, norm)
+
+    return fac * (5 * z * z - 3) * z / 2
+
+def assoc_legendre_p_3_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 1, norm)
+
+    return (3 * fac * (5 * z * z - 1) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 2, norm)
+
+    return 15 * branch_cut_sign * fac * (1 - z * z) * z
+
+def assoc_legendre_p_3_3(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 3, norm)
+
+    return (15 * branch_cut_sign * fac * (1 - z * z) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_3_m3(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, -3, norm)
+
+    return (fac * (z * z - 1) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_3_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -2, norm)
+
+    return branch_cut_sign * fac * (1 - z * z) * z / 8
+
+def assoc_legendre_p_3_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -1, norm)
+
+    return (branch_cut_sign * fac * (1 - 5 * z * z) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_4_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 0, norm)
+
+    return fac * ((35 * z * z - 30) * z * z + 3) / 8
+
+def assoc_legendre_p_4_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 1, norm)
+
+    return (5 * fac * (7 * z * z - 3) * z *
+       assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_4_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 2, norm)
+
+    return 15 * branch_cut_sign * fac * ((8 - 7 * z * z) * z * z - 1) / 2
+
+def assoc_legendre_p_4_3(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 3, norm)
+
+    return (105 * branch_cut_sign * fac * (1 - z * z) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_4_4(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 4, norm)
+
+    return 105 * fac * np.square(z * z - 1)
+
+def assoc_legendre_p_4_m4(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -4, norm)
+
+    return fac * np.square(z * z - 1) / 384
+
+def assoc_legendre_p_4_m3(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -3, norm)
+
+    return (fac * (z * z - 1) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_4_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -2, norm)
+
+    return branch_cut_sign * fac * ((8 - 7 * z * z) * z * z - 1) / 48
+
+def assoc_legendre_p_4_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -1, norm)
+
+    return (branch_cut_sign * fac * (3 - 7 * z * z) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_1_1_jac_div_z(z, branch_cut=2):
+    branch_sign = np.where(branch_cut == 3, np.where(np.signbit(np.real(z)), 1, -1), -1)
+
+    out11_div_z = (-branch_sign /
+        np.sqrt(np.where(branch_cut == 3, z * z - 1, 1 - z * z)))
+
+    return out11_div_z
+
+def assoc_legendre_p_0_0_jac(z, *, branch_cut=2, norm=False):
+    return np.zeros_like(z)
+
+def assoc_legendre_p_1_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 0, norm)
+
+    return np.full_like(z, fac)
+
+def assoc_legendre_p_1_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 1, norm)
+
+    return (fac * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_1_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, -1, norm)
+
+    return (-branch_cut_sign * fac * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 0, norm)
+
+    return 3 * fac * z
+
+def assoc_legendre_p_2_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 1, norm)
+
+    return (3 * fac * (2 * z * z - 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_2_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, 2, norm)
+
+    return -6 * branch_cut_sign * fac * z
+
+def assoc_legendre_p_2_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -1, norm)
+
+    return (branch_cut_sign * fac * (1 - 2 * z * z) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -2, norm)
+
+    return -branch_cut_sign * fac * z / 4
+
+def assoc_legendre_p_3_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 0, norm)
+
+    return 3 * fac * (5 * z * z - 1) / 2
+
+def assoc_legendre_p_3_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 1, norm)
+
+    return (3 * fac * (15 * z * z - 11) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 2, norm)
+
+    return 15 * branch_cut_sign * fac * (1 - 3 * z * z)
+
+def assoc_legendre_p_3_3_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 3, norm)
+
+    return (45 * branch_cut_sign * fac * (1 - z * z) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_3_m3_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, -3, norm)
+
+    return (fac * (z * z - 1) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 16)
+
+def assoc_legendre_p_3_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -2, norm)
+
+    return branch_cut_sign * fac * (1 - 3 * z * z) / 8
+
+def assoc_legendre_p_3_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -1, norm)
+
+    return (branch_cut_sign * fac * (11 - 15 * z * z) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_4_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 0, norm)
+
+    return 5 * fac * (7 * z * z - 3) * z / 2
+
+def assoc_legendre_p_4_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 1, norm)
+
+    return (5 * fac * ((28 * z * z - 27) * z * z + 3) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_4_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 2, norm)
+
+    return 30 * branch_cut_sign * fac * (4 - 7 * z * z) * z
+
+def assoc_legendre_p_4_3_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 3, norm)
+
+    return (105 * branch_cut_sign * fac * ((5 - 4 * z * z) * z * z - 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_4_4_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 4, norm)
+
+    return 420 * fac * (z * z - 1) * z
+
+def assoc_legendre_p_4_m4_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -4, norm)
+
+    return fac * (z * z - 1) * z / 96
+
+def assoc_legendre_p_4_m3_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -3, norm)
+
+    return (fac * ((4 * z * z - 5) * z * z + 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_4_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -2, norm)
+
+    return branch_cut_sign * fac * (4 - 7 * z * z) * z / 12
+
+def assoc_legendre_p_4_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -1, norm)
+
+    return (branch_cut_sign * fac * ((27 - 28 * z * z) * z * z - 3) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 8)
+
+def sph_legendre_factor(n, m):
+    return assoc_legendre_factor(n, m, norm=True) / np.sqrt(2 * np.pi)
+
+def sph_legendre_p_0_0(theta):
+    fac = sph_legendre_factor(0, 0)
+
+    return np.full_like(theta, fac)
+
+def sph_legendre_p_1_0(theta):
+    fac = sph_legendre_factor(1, 0)
+
+    return fac * np.cos(theta)
+
+def sph_legendre_p_1_1(theta):
+    fac = sph_legendre_factor(1, 1)
+
+    return -fac * np.abs(np.sin(theta))
+
+def sph_legendre_p_1_m1(theta):
+    fac = sph_legendre_factor(1, -1)
+
+    return fac * np.abs(np.sin(theta)) / 2
+
+def sph_legendre_p_2_0(theta):
+    fac = sph_legendre_factor(2, 0)
+
+    return fac * (3 * np.square(np.cos(theta)) - 1) / 2
+
+def sph_legendre_p_2_1(theta):
+    fac = sph_legendre_factor(2, 1)
+
+    return -3 * fac * np.abs(np.sin(theta)) * np.cos(theta)
+
+def sph_legendre_p_2_2(theta):
+    fac = sph_legendre_factor(2, 2)
+
+    return 3 * fac * (1 - np.square(np.cos(theta)))
+
+def sph_legendre_p_2_m2(theta):
+    fac = sph_legendre_factor(2, -2)
+
+    return fac * (1 - np.square(np.cos(theta))) / 8
+
+def sph_legendre_p_2_m1(theta):
+    fac = sph_legendre_factor(2, -1)
+
+    return fac * np.cos(theta) * np.abs(np.sin(theta)) / 2
+
+def sph_legendre_p_3_0(theta):
+    fac = sph_legendre_factor(3, 0)
+
+    return (fac * (5 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) / 2)
+
+def sph_legendre_p_3_1(theta):
+    fac = sph_legendre_factor(3, 1)
+
+    return (-3 * fac * (5 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) / 2)
+
+def sph_legendre_p_3_2(theta):
+    fac = sph_legendre_factor(3, 2)
+
+    return (-15 * fac * (np.square(np.cos(theta)) - 1) *
+        np.cos(theta))
+
+def sph_legendre_p_3_3(theta):
+    fac = sph_legendre_factor(3, 3)
+
+    return -15 * fac * np.power(np.abs(np.sin(theta)), 3)
+
+def sph_legendre_p_3_m3(theta):
+    fac = sph_legendre_factor(3, -3)
+
+    return fac * np.power(np.abs(np.sin(theta)), 3) / 48
+
+def sph_legendre_p_3_m2(theta):
+    fac = sph_legendre_factor(3, -2)
+
+    return (-fac * (np.square(np.cos(theta)) - 1) *
+        np.cos(theta) / 8)
+
+def sph_legendre_p_3_m1(theta):
+    fac = sph_legendre_factor(3, -1)
+
+    return (fac * (5 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) / 8)
+
+def sph_legendre_p_4_0(theta):
+    fac = sph_legendre_factor(4, 0)
+
+    return (fac * (35 * np.square(np.square(np.cos(theta))) -
+        30 * np.square(np.cos(theta)) + 3) / 8)
+
+def sph_legendre_p_4_1(theta):
+    fac = sph_legendre_factor(4, 1)
+
+    return (-5 * fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) * np.abs(np.sin(theta)) / 2)
+
+def sph_legendre_p_4_2(theta):
+    fac = sph_legendre_factor(4, 2)
+
+    return (-15 * fac * (7 * np.square(np.cos(theta)) - 1) *
+        (np.square(np.cos(theta)) - 1) / 2)
+
+def sph_legendre_p_4_3(theta):
+    fac = sph_legendre_factor(4, 3)
+
+    return -105 * fac * np.power(np.abs(np.sin(theta)), 3) * np.cos(theta)
+
+def sph_legendre_p_4_4(theta):
+    fac = sph_legendre_factor(4, 4)
+
+    return 105 * fac * np.square(np.square(np.cos(theta)) - 1)
+
+def sph_legendre_p_4_m4(theta):
+    fac = sph_legendre_factor(4, -4)
+
+    return fac * np.square(np.square(np.cos(theta)) - 1) / 384
+
+def sph_legendre_p_4_m3(theta):
+    fac = sph_legendre_factor(4, -3)
+
+    return (fac * np.power(np.abs(np.sin(theta)), 3) *
+        np.cos(theta) / 48)
+
+def sph_legendre_p_4_m2(theta):
+    fac = sph_legendre_factor(4, -2)
+
+    return (-fac * (7 * np.square(np.cos(theta)) - 1) *
+        (np.square(np.cos(theta)) - 1) / 48)
+
+def sph_legendre_p_4_m1(theta):
+    fac = sph_legendre_factor(4, -1)
+
+    return (fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) * np.abs(np.sin(theta)) / 8)
+
+def sph_legendre_p_0_0_jac(theta):
+    return np.zeros_like(theta)
+
+def sph_legendre_p_1_0_jac(theta):
+    fac = sph_legendre_factor(1, 0)
+
+    return -fac * np.sin(theta)
+
+def sph_legendre_p_1_1_jac(theta):
+    fac = sph_legendre_factor(1, 1)
+
+    return -fac * np.cos(theta) * (2 * np.heaviside(np.sin(theta), 1) - 1)
+
+def sph_legendre_p_1_m1_jac(theta):
+    fac = sph_legendre_factor(1, -1)
+
+    return fac * np.cos(theta) * (2 * np.heaviside(np.sin(theta), 1) - 1) / 2
+
+def sph_legendre_p_2_0_jac(theta):
+    fac = sph_legendre_factor(2, 0)
+
+    return -3 * fac * np.cos(theta) * np.sin(theta)
+
+def sph_legendre_p_2_1_jac(theta):
+    fac = sph_legendre_factor(2, 1)
+
+    return (3 * fac * (-np.square(np.cos(theta)) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) +
+        np.abs(np.sin(theta)) * np.sin(theta)))
+
+def sph_legendre_p_2_2_jac(theta):
+    fac = sph_legendre_factor(2, 2)
+
+    return 6 * fac * np.sin(theta) * np.cos(theta)
+
+def sph_legendre_p_2_m2_jac(theta):
+    fac = sph_legendre_factor(2, -2)
+
+    return fac * np.sin(theta) * np.cos(theta) / 4
+
+def sph_legendre_p_2_m1_jac(theta):
+    fac = sph_legendre_factor(2, -1)
+
+    return (-fac * (-np.square(np.cos(theta)) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) +
+        np.abs(np.sin(theta)) * np.sin(theta)) / 2)
+
+def sph_legendre_p_3_0_jac(theta):
+    fac = sph_legendre_factor(3, 0)
+
+    return 3 * fac * (1 - 5 * np.square(np.cos(theta))) * np.sin(theta) / 2
+
+def sph_legendre_p_3_1_jac(theta):
+    fac = sph_legendre_factor(3, 1)
+
+    return (3 * fac * (11 - 15 * np.square(np.cos(theta))) * np.cos(theta) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 2)
+
+def sph_legendre_p_3_2_jac(theta):
+    fac = sph_legendre_factor(3, 2)
+
+    return 15 * fac * (3 * np.square(np.cos(theta)) - 1) * np.sin(theta)
+
+def sph_legendre_p_3_3_jac(theta):
+    fac = sph_legendre_factor(3, 3)
+
+    return -45 * fac * np.abs(np.sin(theta)) * np.sin(theta) * np.cos(theta)
+
+def sph_legendre_p_3_m3_jac(theta):
+    fac = sph_legendre_factor(3, -3)
+
+    return fac * np.abs(np.sin(theta)) * np.sin(theta) * np.cos(theta) / 16
+
+def sph_legendre_p_3_m2_jac(theta):
+    fac = sph_legendre_factor(3, -2)
+
+    return fac * (3 * np.square(np.cos(theta)) - 1) * np.sin(theta) / 8
+
+def sph_legendre_p_3_m1_jac(theta):
+    fac = sph_legendre_factor(3, -1)
+
+    return (-fac * (11 - 15 * np.square(np.cos(theta))) *
+        np.cos(theta) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 8)
+
+def sph_legendre_p_4_0_jac(theta):
+    fac = sph_legendre_factor(4, 0)
+
+    return (-5 * fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.sin(theta) * np.cos(theta) / 2)
+
+def sph_legendre_p_4_1_jac(theta):
+    fac = sph_legendre_factor(4, 1)
+
+    return (5 * fac * (-3 + 27 * np.square(np.cos(theta)) -
+        28 * np.square(np.square(np.cos(theta)))) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 2)
+
+def sph_legendre_p_4_2_jac(theta):
+    fac = sph_legendre_factor(4, 2)
+
+    return (30 * fac * (7 * np.square(np.cos(theta)) - 4) *
+        np.sin(theta) * np.cos(theta))
+
+def sph_legendre_p_4_3_jac(theta):
+    fac = sph_legendre_factor(4, 3)
+
+    return (-105 * fac * (4 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) * np.sin(theta))
+
+def sph_legendre_p_4_4_jac(theta):
+    fac = sph_legendre_factor(4, 4)
+
+    return (-420 * fac * (np.square(np.cos(theta)) - 1) *
+        np.sin(theta) * np.cos(theta))
+
+def sph_legendre_p_4_m4_jac(theta):
+    fac = sph_legendre_factor(4, -4)
+
+    return (-fac * (np.square(np.cos(theta)) - 1) *
+        np.sin(theta) * np.cos(theta) / 96)
+
+def sph_legendre_p_4_m3_jac(theta):
+    fac = sph_legendre_factor(4, -3)
+
+    return (fac * (4 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) * np.sin(theta) / 48)
+
+def sph_legendre_p_4_m2_jac(theta):
+    fac = sph_legendre_factor(4, -2)
+
+    return (fac * (7 * np.square(np.cos(theta)) - 4) * np.sin(theta) *
+        np.cos(theta) / 12)
+
+def sph_legendre_p_4_m1_jac(theta):
+    fac = sph_legendre_factor(4, -1)
+
+    return (-fac * (-3 + 27 * np.square(np.cos(theta)) -
+        28 * np.square(np.square(np.cos(theta)))) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 8)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fcb5a20037de46df939895d38fbe5fe6b85c9aa
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py
@@ -0,0 +1,70 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_
+
+from scipy.special._testutils import FuncData
+from scipy.special import gamma, gammaln, loggamma
+
+
+def test_identities1():
+    # test the identity exp(loggamma(z)) = gamma(z)
+    x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5])
+    y = x.copy()
+    x, y = np.meshgrid(x, y)
+    z = (x + 1J*y).flatten()
+    dataset = np.vstack((z, gamma(z))).T
+
+    def f(z):
+        return np.exp(loggamma(z))
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_identities2():
+    # test the identity loggamma(z + 1) = log(z) + loggamma(z)
+    x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5])
+    y = x.copy()
+    x, y = np.meshgrid(x, y)
+    z = (x + 1J*y).flatten()
+    dataset = np.vstack((z, np.log(z) + loggamma(z))).T
+
+    def f(z):
+        return loggamma(z + 1)
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_complex_dispatch_realpart():
+    # Test that the real parts of loggamma and gammaln agree on the
+    # real axis.
+    x = np.r_[-np.logspace(10, -10), np.logspace(-10, 10)] + 0.5
+
+    dataset = np.vstack((x, gammaln(x))).T
+
+    def f(z):
+        z = np.array(z, dtype='complex128')
+        return loggamma(z).real
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_real_dispatch():
+    x = np.logspace(-10, 10) + 0.5
+    dataset = np.vstack((x, gammaln(x))).T
+
+    FuncData(loggamma, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+    assert_(loggamma(0) == np.inf)
+    assert_(np.isnan(loggamma(-1)))
+
+
+def test_gh_6536():
+    z = loggamma(complex(-3.4, +0.0))
+    zbar = loggamma(complex(-3.4, -0.0))
+    assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0)
+
+
+def test_branch_cut():
+    # Make sure negative zero is treated correctly
+    x = -np.logspace(300, -30, 100)
+    z = np.asarray([complex(x0, 0.0) for x0 in x])
+    zbar = np.asarray([complex(x0, -0.0) for x0 in x])
+    assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py
new file mode 100644
index 0000000000000000000000000000000000000000..050e8db5cb408c5c576c6cd292175d2df7c8f756
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py
@@ -0,0 +1,162 @@
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal,
+                           assert_allclose)
+from scipy.special import logit, expit, log_expit
+
+
+class TestLogit:
+
+    def check_logit_out(self, a, expected):
+        actual = logit(a)
+        assert_equal(actual.dtype, a.dtype)
+        rtol = 16*np.finfo(a.dtype).eps
+        assert_allclose(actual, expected, rtol=rtol)
+
+    def test_float32(self):
+        a = np.concatenate((np.linspace(0, 1, 10, dtype=np.float32),
+                            [np.float32(0.0001), np.float32(0.49999),
+                             np.float32(0.50001)]))
+        # Expected values computed with mpmath from float32 inputs, e.g.
+        #   from mpmath import mp
+        #   mp.dps = 200
+        #   a = np.float32(1/9)
+        #   print(np.float32(mp.log(a) - mp.log1p(-a)))
+        # prints `-2.0794415`.
+        expected = np.array([-np.inf, -2.0794415, -1.2527629, -6.9314712e-01,
+                             -2.2314353e-01,  2.2314365e-01,  6.9314724e-01,
+                             1.2527630, 2.0794415, np.inf,
+                             -9.2102404, -4.0054321e-05, 4.0054321e-05],
+                            dtype=np.float32)
+        self.check_logit_out(a, expected)
+
+    def test_float64(self):
+        a = np.concatenate((np.linspace(0, 1, 10, dtype=np.float64),
+                            [1e-8, 0.4999999999999, 0.50000000001]))
+        # Expected values computed with mpmath.
+        expected = np.array([-np.inf,
+                             -2.079441541679836,
+                             -1.252762968495368,
+                             -0.6931471805599454,
+                             -0.22314355131420985,
+                             0.22314355131420985,
+                             0.6931471805599452,
+                             1.2527629684953674,
+                             2.0794415416798353,
+                             np.inf,
+                             -18.420680733952366,
+                             -3.999023334699814e-13,
+                             4.000000330961484e-11])
+        self.check_logit_out(a, expected)
+
+    def test_nan(self):
+        expected = np.array([np.nan]*4)
+        with np.errstate(invalid='ignore'):
+            actual = logit(np.array([-3., -2., 2., 3.]))
+
+        assert_equal(expected, actual)
+
+
+class TestExpit:
+    def check_expit_out(self, dtype, expected):
+        a = np.linspace(-4, 4, 10)
+        a = np.array(a, dtype=dtype)
+        actual = expit(a)
+        assert_almost_equal(actual, expected)
+        assert_equal(actual.dtype, np.dtype(dtype))
+
+    def test_float32(self):
+        expected = np.array([0.01798621, 0.04265125,
+                            0.09777259, 0.20860852,
+                            0.39068246, 0.60931754,
+                            0.79139149, 0.9022274,
+                            0.95734876, 0.98201376], dtype=np.float32)
+        self.check_expit_out('f4', expected)
+
+    def test_float64(self):
+        expected = np.array([0.01798621, 0.04265125,
+                            0.0977726, 0.20860853,
+                            0.39068246, 0.60931754,
+                            0.79139147, 0.9022274,
+                            0.95734875, 0.98201379])
+        self.check_expit_out('f8', expected)
+
+    def test_large(self):
+        for dtype in (np.float32, np.float64, np.longdouble):
+            for n in (88, 89, 709, 710, 11356, 11357):
+                n = np.array(n, dtype=dtype)
+                assert_allclose(expit(n), 1.0, atol=1e-20)
+                assert_allclose(expit(-n), 0.0, atol=1e-20)
+                assert_equal(expit(n).dtype, dtype)
+                assert_equal(expit(-n).dtype, dtype)
+
+
+class TestLogExpit:
+
+    def test_large_negative(self):
+        x = np.array([-10000.0, -750.0, -500.0, -35.0])
+        y = log_expit(x)
+        assert_equal(y, x)
+
+    def test_large_positive(self):
+        x = np.array([750.0, 1000.0, 10000.0])
+        y = log_expit(x)
+        # y will contain -0.0, and -0.0 is used in the expected value,
+        # but assert_equal does not check the sign of zeros, and I don't
+        # think the sign is an essential part of the test (i.e. it would
+        # probably be OK if log_expit(1000) returned 0.0 instead of -0.0).
+        assert_equal(y, np.array([-0.0, -0.0, -0.0]))
+
+    def test_basic_float64(self):
+        x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9,
+                      0, 1e-9, 0.1, 1, 10, 100, 500, 710, 725, 735])
+        y = log_expit(x)
+        #
+        # Expected values were computed with mpmath:
+        #
+        #   import mpmath
+        #
+        #   mpmath.mp.dps = 100
+        #
+        #   def mp_log_expit(x):
+        #       return -mpmath.log1p(mpmath.exp(-x))
+        #
+        #   expected = [float(mp_log_expit(t)) for t in x]
+        #
+        expected = [-32.000000000000014, -20.000000002061153,
+                    -10.000045398899218, -3.048587351573742,
+                    -1.3132616875182228, -0.7443966600735709,
+                    -0.6931471810599453, -0.6931471805599453,
+                    -0.6931471800599454, -0.6443966600735709,
+                    -0.3132616875182228, -4.539889921686465e-05,
+                    -3.720075976020836e-44, -7.124576406741286e-218,
+                    -4.47628622567513e-309, -1.36930634e-315,
+                    -6.217e-320]
+
+        # When tested locally, only one value in y was not exactly equal to
+        # expected.  That was for x=1, and the y value differed from the
+        # expected by 1 ULP.  For this test, however, I'll use rtol=1e-15.
+        assert_allclose(y, expected, rtol=1e-15)
+
+    def test_basic_float32(self):
+        x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9,
+                      0, 1e-9, 0.1, 1, 10, 100], dtype=np.float32)
+        y = log_expit(x)
+        #
+        # Expected values were computed with mpmath:
+        #
+        #   import mpmath
+        #
+        #   mpmath.mp.dps = 100
+        #
+        #   def mp_log_expit(x):
+        #       return -mpmath.log1p(mpmath.exp(-x))
+        #
+        #   expected = [np.float32(mp_log_expit(t)) for t in x]
+        #
+        expected = np.array([-32.0, -20.0, -10.000046, -3.0485873,
+                             -1.3132616, -0.7443967, -0.6931472,
+                             -0.6931472, -0.6931472, -0.64439666,
+                             -0.3132617, -4.5398898e-05, -3.8e-44],
+                            dtype=np.float32)
+
+        assert_allclose(y, expected, rtol=5e-7)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py
new file mode 100644
index 0000000000000000000000000000000000000000..43e84e444f2eda03aef77ea923ca2d498aef4126
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py
@@ -0,0 +1,2292 @@
+"""
+Test SciPy functions versus mpmath, if available.
+
+"""
+import numpy as np
+from numpy.testing import assert_, assert_allclose, suppress_warnings
+from numpy import pi
+import pytest
+import itertools
+
+from scipy._lib import _pep440
+
+import scipy.special as sc
+from scipy.special._testutils import (
+    MissingModule, check_version, FuncData,
+    assert_func_equal)
+from scipy.special._mptestutils import (
+    Arg, FixedArg, ComplexArg, IntArg, assert_mpmath_equal,
+    nonfunctional_tooslow, trace_args, time_limited, exception_to_nan,
+    inf_to_nan)
+from scipy.special._ufuncs import (
+    _sinpi, _cospi, _lgam1p, _lanczos_sum_expg_scaled, _log1pmx,
+    _igam_fac)
+
+try:
+    import mpmath
+except ImportError:
+    mpmath = MissingModule('mpmath')
+
+
+# ------------------------------------------------------------------------------
+# expi
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.10')
+def test_expi_complex():
+    dataset = []
+    for r in np.logspace(-99, 2, 10):
+        for p in np.linspace(0, 2*np.pi, 30):
+            z = r*np.exp(1j*p)
+            dataset.append((z, complex(mpmath.ei(z))))
+    dataset = np.array(dataset, dtype=np.cdouble)
+
+    FuncData(sc.expi, dataset, 0, 1).check()
+
+
+# ------------------------------------------------------------------------------
+# expn
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_expn_large_n():
+    # Test the transition to the asymptotic regime of n.
+    dataset = []
+    for n in [50, 51]:
+        for x in np.logspace(0, 4, 200):
+            with mpmath.workdps(100):
+                dataset.append((n, x, float(mpmath.expint(n, x))))
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.expn, dataset, (0, 1), 2, rtol=1e-13).check()
+
+# ------------------------------------------------------------------------------
+# hyp0f1
+# ------------------------------------------------------------------------------
+
+
+@check_version(mpmath, '0.19')
+def test_hyp0f1_gh5764():
+    # Do a small and somewhat systematic test that runs quickly
+    dataset = []
+    axis = [-99.5, -9.5, -0.5, 0.5, 9.5, 99.5]
+    for v in axis:
+        for x in axis:
+            for y in axis:
+                z = x + 1j*y
+                # mpmath computes the answer correctly at dps ~ 17 but
+                # fails for 20 < dps < 120 (uses a different method);
+                # set the dps high enough that this isn't an issue
+                with mpmath.workdps(120):
+                    res = complex(mpmath.hyp0f1(v, z))
+                dataset.append((v, z, res))
+    dataset = np.array(dataset)
+
+    FuncData(lambda v, z: sc.hyp0f1(v.real, z), dataset, (0, 1), 2,
+             rtol=1e-13).check()
+
+
+@check_version(mpmath, '0.19')
+def test_hyp0f1_gh_1609():
+    # this is a regression test for gh-1609
+    vv = np.linspace(150, 180, 21)
+    af = sc.hyp0f1(vv, 0.5)
+    mf = np.array([mpmath.hyp0f1(v, 0.5) for v in vv])
+    assert_allclose(af, mf.astype(float), rtol=1e-12)
+
+
+# ------------------------------------------------------------------------------
+# hyperu
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '1.1.0')
+def test_hyperu_around_0():
+    dataset = []
+    # DLMF 13.2.14-15 test points.
+    for n in np.arange(-5, 5):
+        for b in np.linspace(-5, 5, 20):
+            a = -n
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+            a = -n + b - 1
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+    # DLMF 13.2.16-22 test points.
+    for a in [-10.5, -1.5, -0.5, 0, 0.5, 1, 10]:
+        for b in [-1.0, -0.5, 0, 0.5, 1, 1.5, 2, 2.5]:
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+    dataset = np.array(dataset)
+
+    FuncData(sc.hyperu, dataset, (0, 1, 2), 3, rtol=1e-15, atol=5e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# hyp2f1
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '1.0.0')
+def test_hyp2f1_strange_points():
+    pts = [
+        (2, -1, -1, 0.7),  # expected: 2.4
+        (2, -2, -2, 0.7),  # expected: 3.87
+    ]
+    pts += list(itertools.product([2, 1, -0.7, -1000], repeat=4))
+    pts = [
+        (a, b, c, x) for a, b, c, x in pts
+        if b == c and round(b) == b and b < 0 and b != -1000
+    ]
+    kw = dict(eliminate=True)
+    dataset = [p + (float(mpmath.hyp2f1(*p, **kw)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.13')
+def test_hyp2f1_real_some_points():
+    pts = [
+        (1, 2, 3, 0),
+        (1./3, 2./3, 5./6, 27./32),
+        (1./4, 1./2, 3./4, 80./81),
+        (2,-2, -3, 3),
+        (2, -3, -2, 3),
+        (2, -1.5, -1.5, 3),
+        (1, 2, 3, 0),
+        (0.7235, -1, -5, 0.3),
+        (0.25, 1./3, 2, 0.999),
+        (0.25, 1./3, 2, -1),
+        (2, 3, 5, 0.99),
+        (3./2, -0.5, 3, 0.99),
+        (2, 2.5, -3.25, 0.999),
+        (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001),
+        (-10, 900, -10.5, 0.99),
+        (-10, 900, 10.5, 0.99),
+        (-1, 2, 1, 1.0),
+        (-1, 2, 1, -1.0),
+        (-3, 13, 5, 1.0),
+        (-3, 13, 5, -1.0),
+        (0.5, 1 - 270.5, 1.5, 0.999**2),  # from issue 1561
+    ]
+    dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.14')
+def test_hyp2f1_some_points_2():
+    # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but
+    # was fixed in their SVN since then
+    pts = [
+        (112, (51,10), (-9,10), -0.99999),
+        (10,-900,10.5,0.99),
+        (10,-900,-10.5,0.99),
+    ]
+
+    def fev(x):
+        if isinstance(x, tuple):
+            return float(x[0]) / x[1]
+        else:
+            return x
+
+    dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.13')
+def test_hyp2f1_real_some():
+    dataset = []
+    for a in [-10, -5, -1.8, 1.8, 5, 10]:
+        for b in [-2.5, -1, 1, 7.4]:
+            for c in [-9, -1.8, 5, 20.4]:
+                for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]:
+                    try:
+                        v = float(mpmath.hyp2f1(a, b, c, z))
+                    except Exception:
+                        continue
+                    dataset.append((a, b, c, z, v))
+    dataset = np.array(dataset, dtype=np.float64)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9,
+                 ignore_inf_sign=True).check()
+
+
+@check_version(mpmath, '0.12')
+@pytest.mark.slow
+def test_hyp2f1_real_random():
+    npoints = 500
+    dataset = np.zeros((npoints, 5), np.float64)
+
+    np.random.seed(1234)
+    dataset[:, 0] = np.random.pareto(1.5, npoints)
+    dataset[:, 1] = np.random.pareto(1.5, npoints)
+    dataset[:, 2] = np.random.pareto(1.5, npoints)
+    dataset[:, 3] = 2*np.random.rand(npoints) - 1
+
+    dataset[:, 0] *= (-1)**np.random.randint(2, npoints)
+    dataset[:, 1] *= (-1)**np.random.randint(2, npoints)
+    dataset[:, 2] *= (-1)**np.random.randint(2, npoints)
+
+    for ds in dataset:
+        if mpmath.__version__ < '0.14':
+            # mpmath < 0.14 fails for c too much smaller than a, b
+            if abs(ds[:2]).max() > abs(ds[2]):
+                ds[2] = abs(ds[:2]).max()
+        ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4])))
+
+    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check()
+
+
+# ------------------------------------------------------------------------------
+# erf (complex)
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.14')
+def test_erf_complex():
+    # need to increase mpmath precision for this test
+    old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+    try:
+        mpmath.mp.dps = 70
+        x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11))
+        x2, y2 = np.meshgrid(np.logspace(-80, .8, 31), np.logspace(-80, .8, 11))
+        points = np.r_[x1.ravel(),x2.ravel()] + 1j*np.r_[y1.ravel(), y2.ravel()]
+
+        assert_func_equal(sc.erf, lambda x: complex(mpmath.erf(x)), points,
+                          vectorized=False, rtol=1e-13)
+        assert_func_equal(sc.erfc, lambda x: complex(mpmath.erfc(x)), points,
+                          vectorized=False, rtol=1e-13)
+    finally:
+        mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+
+# ------------------------------------------------------------------------------
+# lpmv
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.15')
+def test_lpmv():
+    pts = []
+    for x in [-0.99, -0.557, 1e-6, 0.132, 1]:
+        pts.extend([
+            (1, 1, x),
+            (1, -1, x),
+            (-1, 1, x),
+            (-1, -2, x),
+            (1, 1.7, x),
+            (1, -1.7, x),
+            (-1, 1.7, x),
+            (-1, -2.7, x),
+            (1, 10, x),
+            (1, 11, x),
+            (3, 8, x),
+            (5, 11, x),
+            (-3, 8, x),
+            (-5, 11, x),
+            (3, -8, x),
+            (5, -11, x),
+            (-3, -8, x),
+            (-5, -11, x),
+            (3, 8.3, x),
+            (5, 11.3, x),
+            (-3, 8.3, x),
+            (-5, 11.3, x),
+            (3, -8.3, x),
+            (5, -11.3, x),
+            (-3, -8.3, x),
+            (-5, -11.3, x),
+        ])
+
+    def mplegenp(nu, mu, x):
+        if mu == int(mu) and x == 1:
+            # mpmath 0.17 gets this wrong
+            if mu == 0:
+                return 1
+            else:
+                return 0
+        return mpmath.legenp(nu, mu, x)
+
+    dataset = [p + (mplegenp(p[1], p[0], p[2]),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    def evf(mu, nu, x):
+        return sc.lpmv(mu.astype(int), nu, x)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(evf, dataset, (0,1,2), 3, rtol=1e-10, atol=1e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# beta
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.15')
+def test_beta():
+    np.random.seed(1234)
+
+    b = np.r_[np.logspace(-200, 200, 4),
+              np.logspace(-10, 10, 4),
+              np.logspace(-1, 1, 4),
+              np.arange(-10, 11, 1),
+              np.arange(-10, 11, 1) + 0.5,
+              -1, -2.3, -3, -100.3, -10003.4]
+    a = b
+
+    ab = np.array(np.broadcast_arrays(a[:,None], b[None,:])).reshape(2, -1).T
+
+    old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+    try:
+        mpmath.mp.dps = 400
+
+        assert_func_equal(sc.beta,
+                          lambda a, b: float(mpmath.beta(a, b)),
+                          ab,
+                          vectorized=False,
+                          rtol=1e-10,
+                          ignore_inf_sign=True)
+
+        assert_func_equal(
+            sc.betaln,
+            lambda a, b: float(mpmath.log(abs(mpmath.beta(a, b)))),
+            ab,
+            vectorized=False,
+            rtol=1e-10)
+    finally:
+        mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+
+# ------------------------------------------------------------------------------
+# loggamma
+# ------------------------------------------------------------------------------
+
+LOGGAMMA_TAYLOR_RADIUS = 0.2
+
+
+@check_version(mpmath, '0.19')
+def test_loggamma_taylor_transition():
+    # Make sure there isn't a big jump in accuracy when we move from
+    # using the Taylor series to using the recurrence relation.
+
+    r = LOGGAMMA_TAYLOR_RADIUS + np.array([-0.1, -0.01, 0, 0.01, 0.1])
+    theta = np.linspace(0, 2*np.pi, 20)
+    r, theta = np.meshgrid(r, theta)
+    dz = r*np.exp(1j*theta)
+    z = np.r_[1 + dz, 2 + dz].flatten()
+
+    dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z]
+    dataset = np.array(dataset)
+
+    FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check()
+
+
+@check_version(mpmath, '0.19')
+def test_loggamma_taylor():
+    # Test around the zeros at z = 1, 2.
+
+    r = np.logspace(-16, np.log10(LOGGAMMA_TAYLOR_RADIUS), 10)
+    theta = np.linspace(0, 2*np.pi, 20)
+    r, theta = np.meshgrid(r, theta)
+    dz = r*np.exp(1j*theta)
+    z = np.r_[1 + dz, 2 + dz].flatten()
+
+    dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z]
+    dataset = np.array(dataset)
+
+    FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# rgamma
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_rgamma_zeros():
+    # Test around the zeros at z = 0, -1, -2, ...,  -169. (After -169 we
+    # get values that are out of floating point range even when we're
+    # within 0.1 of the zero.)
+
+    # Can't use too many points here or the test takes forever.
+    dx = np.r_[-np.logspace(-1, -13, 3), 0, np.logspace(-13, -1, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = np.arange(0, -170, -1).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    with mpmath.workdps(100):
+        dataset = [(z0, complex(mpmath.rgamma(z0))) for z0 in z]
+
+    dataset = np.array(dataset)
+    FuncData(sc.rgamma, dataset, 0, 1, rtol=1e-12).check()
+
+
+# ------------------------------------------------------------------------------
+# digamma
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_digamma_roots():
+    # Test the special-cased roots for digamma.
+    root = mpmath.findroot(mpmath.digamma, 1.5)
+    roots = [float(root)]
+    root = mpmath.findroot(mpmath.digamma, -0.5)
+    roots.append(float(root))
+    roots = np.array(roots)
+
+    # If we test beyond a radius of 0.24 mpmath will take forever.
+    dx = np.r_[-0.24, -np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10), 0.24]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    z = (roots + np.dstack((dz,)*roots.size)).flatten()
+    with mpmath.workdps(30):
+        dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z]
+
+    dataset = np.array(dataset)
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check()
+
+
+@check_version(mpmath, '0.19')
+def test_digamma_negreal():
+    # Test digamma around the negative real axis. Don't do this in
+    # TestSystematic because the points need some jiggering so that
+    # mpmath doesn't take forever.
+
+    digamma = exception_to_nan(mpmath.digamma)
+
+    x = -np.logspace(300, -30, 100)
+    y = np.r_[-np.logspace(0, -3, 5), 0, np.logspace(-3, 0, 5)]
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    with mpmath.workdps(40):
+        dataset = [(z0, complex(digamma(z0))) for z0 in z]
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check()
+
+
+@check_version(mpmath, '0.19')
+def test_digamma_boundary():
+    # Check that there isn't a jump in accuracy when we switch from
+    # using the asymptotic series to the reflection formula.
+
+    x = -np.logspace(300, -30, 100)
+    y = np.array([-6.1, -5.9, 5.9, 6.1])
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    with mpmath.workdps(30):
+        dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z]
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# gammainc
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_gammainc_boundary():
+    # Test the transition to the asymptotic series.
+    small = 20
+    a = np.linspace(0.5*small, 2*small, 50)
+    x = a.copy()
+    a, x = np.meshgrid(a, x)
+    a, x = a.flatten(), x.flatten()
+    with mpmath.workdps(100):
+        dataset = [(a0, x0, float(mpmath.gammainc(a0, b=x0, regularized=True)))
+                   for a0, x0 in zip(a, x)]
+    dataset = np.array(dataset)
+
+    FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-12).check()
+
+
+# ------------------------------------------------------------------------------
+# spence
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_spence_circle():
+    # The trickiest region for spence is around the circle |z - 1| = 1,
+    # so test that region carefully.
+
+    def spence(z):
+        return complex(mpmath.polylog(2, 1 - z))
+
+    r = np.linspace(0.5, 1.5)
+    theta = np.linspace(0, 2*pi)
+    z = (1 + np.outer(r, np.exp(1j*theta))).flatten()
+    dataset = np.asarray([(z0, spence(z0)) for z0 in z])
+
+    FuncData(sc.spence, dataset, 0, 1, rtol=1e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# sinpi and cospi
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_sinpi_zeros():
+    eps = np.finfo(float).eps
+    dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = np.arange(-100, 100, 1).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    dataset = np.asarray([(z0, complex(mpmath.sinpi(z0)))
+                          for z0 in z])
+    FuncData(_sinpi, dataset, 0, 1, rtol=2*eps).check()
+
+
+@check_version(mpmath, '0.19')
+def test_cospi_zeros():
+    eps = np.finfo(float).eps
+    dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = (np.arange(-100, 100, 1) + 0.5).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    dataset = np.asarray([(z0, complex(mpmath.cospi(z0)))
+                          for z0 in z])
+
+    FuncData(_cospi, dataset, 0, 1, rtol=2*eps).check()
+
+
+# ------------------------------------------------------------------------------
+# ellipj
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_dn_quarter_period():
+    def dn(u, m):
+        return sc.ellipj(u, m)[2]
+
+    def mpmath_dn(u, m):
+        return float(mpmath.ellipfun("dn", u=u, m=m))
+
+    m = np.linspace(0, 1, 20)
+    du = np.r_[-np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10)]
+    dataset = []
+    for m0 in m:
+        u0 = float(mpmath.ellipk(m0))
+        for du0 in du:
+            p = u0 + du0
+            dataset.append((p, m0, mpmath_dn(p, m0)))
+    dataset = np.asarray(dataset)
+
+    FuncData(dn, dataset, (0, 1), 2, rtol=1e-10).check()
+
+
+# ------------------------------------------------------------------------------
+# Wright Omega
+# ------------------------------------------------------------------------------
+
+def _mpmath_wrightomega(z, dps):
+    with mpmath.workdps(dps):
+        z = mpmath.mpc(z)
+        unwind = mpmath.ceil((z.imag - mpmath.pi)/(2*mpmath.pi))
+        res = mpmath.lambertw(mpmath.exp(z), unwind)
+    return res
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_branch():
+    x = -np.logspace(10, 0, 25)
+    picut_above = [np.nextafter(np.pi, np.inf)]
+    picut_below = [np.nextafter(np.pi, -np.inf)]
+    npicut_above = [np.nextafter(-np.pi, np.inf)]
+    npicut_below = [np.nextafter(-np.pi, -np.inf)]
+    for i in range(50):
+        picut_above.append(np.nextafter(picut_above[-1], np.inf))
+        picut_below.append(np.nextafter(picut_below[-1], -np.inf))
+        npicut_above.append(np.nextafter(npicut_above[-1], np.inf))
+        npicut_below.append(np.nextafter(npicut_below[-1], -np.inf))
+    y = np.hstack((picut_above, picut_below, npicut_above, npicut_below))
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-8).check()
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_region1():
+    # This region gets less coverage in the TestSystematic test
+    x = np.linspace(-2, 1)
+    y = np.linspace(1, 2*np.pi)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check()
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_region2():
+    # This region gets less coverage in the TestSystematic test
+    x = np.linspace(-2, 1)
+    y = np.linspace(-2*np.pi, -1)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check()
+
+
+# ------------------------------------------------------------------------------
+# lambertw
+# ------------------------------------------------------------------------------
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_lambertw_smallz():
+    x, y = np.linspace(-1, 1, 25), np.linspace(-1, 1, 25)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(mpmath.lambertw(z0)))
+                          for z0 in z])
+
+    FuncData(sc.lambertw, dataset, 0, 1, rtol=1e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# Systematic tests
+# ------------------------------------------------------------------------------
+
+# The functions lpn, lpmn, clpmn, and sph_harm appearing below are
+# deprecated in favor of legendre_p_all, assoc_legendre_p_all,
+# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn),
+# and sph_harm_y respectively. The deprecated functions listed above are
+# implemented as shims around their respective replacements. The replacements
+# are tested separately, but tests for the deprecated functions remain to
+# verify the correctness of the shims.
+
+HYPERKW = dict(maxprec=200, maxterms=200)
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.17')
+class TestSystematic:
+
+    def test_airyai(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [Arg(-1e3, 1e3)])
+
+    def test_airyai_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [ComplexArg()])
+
+    def test_airyai_prime(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airyai_prime_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [ComplexArg()])
+
+    def test_airybi(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airybi_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [ComplexArg()])
+
+    def test_airybi_prime(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airybi_prime_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [ComplexArg()])
+
+    def test_bei(self):
+        assert_mpmath_equal(sc.bei,
+                            exception_to_nan(lambda z: mpmath.bei(0, z, **HYPERKW)),
+                            [Arg(-1e3, 1e3)])
+
+    def test_ber(self):
+        assert_mpmath_equal(sc.ber,
+                            exception_to_nan(lambda z: mpmath.ber(0, z, **HYPERKW)),
+                            [Arg(-1e3, 1e3)])
+
+    def test_bernoulli(self):
+        assert_mpmath_equal(lambda n: sc.bernoulli(int(n))[int(n)],
+                            lambda n: float(mpmath.bernoulli(int(n))),
+                            [IntArg(0, 13000)],
+                            rtol=1e-9, n=13000)
+
+    def test_besseli(self):
+        assert_mpmath_equal(
+            sc.iv,
+            exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg()],
+            atol=1e-270,
+        )
+
+    def test_besseli_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.iv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), ComplexArg()],
+        )
+
+    def test_besselj(self):
+        assert_mpmath_equal(
+            sc.jv,
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg(-1e3, 1e3)],
+            ignore_inf_sign=True,
+        )
+
+        # loss of precision at large arguments due to oscillation
+        assert_mpmath_equal(
+            sc.jv,
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg(-1e8, 1e8)],
+            ignore_inf_sign=True,
+            rtol=1e-5,
+        )
+
+    def test_besselj_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.jv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(), ComplexArg()]
+        )
+
+    def test_besselk(self):
+        assert_mpmath_equal(
+            sc.kv,
+            mpmath.besselk,
+            [Arg(-200, 200), Arg(0, np.inf)],
+            nan_ok=False,
+            rtol=1e-12,
+        )
+
+    def test_besselk_int(self):
+        assert_mpmath_equal(
+            sc.kn,
+            mpmath.besselk,
+            [IntArg(-200, 200), Arg(0, np.inf)],
+            nan_ok=False,
+            rtol=1e-12,
+        )
+
+    def test_besselk_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.kv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besselk(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), ComplexArg()],
+        )
+
+    def test_bessely(self):
+        def mpbessely(v, x):
+            r = float(mpmath.bessely(v, x, **HYPERKW))
+            if abs(r) > 1e305:
+                # overflowing to inf a bit earlier is OK
+                r = np.inf * np.sign(r)
+            if abs(r) == 0 and x == 0:
+                # invalid result from mpmath, point x=0 is a divergence
+                return np.nan
+            return r
+        assert_mpmath_equal(
+            sc.yv,
+            exception_to_nan(mpbessely),
+            [Arg(-1e100, 1e100), Arg(-1e8, 1e8)],
+            n=5000,
+        )
+
+    def test_bessely_complex(self):
+        def mpbessely(v, x):
+            r = complex(mpmath.bessely(v, x, **HYPERKW))
+            if abs(r) > 1e305:
+                # overflowing to inf a bit earlier is OK
+                with np.errstate(invalid='ignore'):
+                    r = np.inf * np.sign(r)
+            return r
+        assert_mpmath_equal(
+            lambda v, z: sc.yv(v.real, z),
+            exception_to_nan(mpbessely),
+            [Arg(), ComplexArg()],
+            n=15000,
+        )
+
+    def test_bessely_int(self):
+        def mpbessely(v, x):
+            r = float(mpmath.bessely(v, x))
+            if abs(r) == 0 and x == 0:
+                # invalid result from mpmath, point x=0 is a divergence
+                return np.nan
+            return r
+        assert_mpmath_equal(
+            lambda v, z: sc.yn(int(v), z),
+            exception_to_nan(mpbessely),
+            [IntArg(-1000, 1000), Arg(-1e8, 1e8)],
+        )
+
+    def test_beta(self):
+        bad_points = []
+
+        def beta(a, b, nonzero=False):
+            if a < -1e12 or b < -1e12:
+                # Function is defined here only at integers, but due
+                # to loss of precision this is numerically
+                # ill-defined. Don't compare values here.
+                return np.nan
+            if (a < 0 or b < 0) and (abs(float(a + b)) % 1) == 0:
+                # close to a zero of the function: mpmath and scipy
+                # will not round here the same, so the test needs to be
+                # run with an absolute tolerance
+                if nonzero:
+                    bad_points.append((float(a), float(b)))
+                    return np.nan
+            return mpmath.beta(a, b)
+
+        assert_mpmath_equal(
+            sc.beta,
+            lambda a, b: beta(a, b, nonzero=True),
+            [Arg(), Arg()],
+            dps=400,
+            ignore_inf_sign=True,
+        )
+
+        assert_mpmath_equal(
+            sc.beta,
+            beta,
+            np.array(bad_points),
+            dps=400,
+            ignore_inf_sign=True,
+            atol=1e-11,
+        )
+
+    def test_betainc(self):
+        assert_mpmath_equal(
+            sc.betainc,
+            time_limited()(
+                exception_to_nan(
+                    lambda a, b, x: mpmath.betainc(a, b, 0, x, regularized=True)
+                )
+            ),
+            [Arg(), Arg(), Arg()],
+        )
+
+    def test_betaincc(self):
+        assert_mpmath_equal(
+            sc.betaincc,
+            time_limited()(
+                exception_to_nan(
+                    lambda a, b, x: mpmath.betainc(a, b, x, 1, regularized=True)
+                )
+            ),
+            [Arg(), Arg(), Arg()],
+            dps=400,
+        )
+
+    def test_binom(self):
+        bad_points = []
+
+        def binomial(n, k, nonzero=False):
+            if abs(k) > 1e8*(abs(n) + 1):
+                # The binomial is rapidly oscillating in this region,
+                # and the function is numerically ill-defined. Don't
+                # compare values here.
+                return np.nan
+            if n < k and abs(float(n-k) - np.round(float(n-k))) < 1e-15:
+                # close to a zero of the function: mpmath and scipy
+                # will not round here the same, so the test needs to be
+                # run with an absolute tolerance
+                if nonzero:
+                    bad_points.append((float(n), float(k)))
+                    return np.nan
+            return mpmath.binomial(n, k)
+
+        assert_mpmath_equal(
+            sc.binom,
+            lambda n, k: binomial(n, k, nonzero=True),
+            [Arg(), Arg()],
+            dps=400,
+        )
+
+        assert_mpmath_equal(
+            sc.binom,
+            binomial,
+            np.array(bad_points),
+            dps=400,
+            atol=1e-14,
+        )
+
+    def test_chebyt_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_chebyt(int(n), x),
+            exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)),
+            [IntArg(), Arg()],
+            dps=50,
+        )
+
+    @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate")
+    def test_chebyt(self):
+        assert_mpmath_equal(
+            sc.eval_chebyt,
+            lambda n, x: time_limited()(
+                exception_to_nan(mpmath.chebyt)
+            )(n, x, **HYPERKW),
+            [Arg(-101, 101), Arg()],
+            n=10000,
+        )
+
+    def test_chebyu_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_chebyu(int(n), x),
+            exception_to_nan(lambda n, x: mpmath.chebyu(n, x, **HYPERKW)),
+            [IntArg(), Arg()],
+            dps=50,
+        )
+
+    @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate")
+    def test_chebyu(self):
+        assert_mpmath_equal(
+            sc.eval_chebyu,
+            lambda n, x: time_limited()(
+                exception_to_nan(mpmath.chebyu)
+            )(n, x, **HYPERKW),
+            [Arg(-101, 101), Arg()],
+        )
+
+    def test_chi(self):
+        def chi(x):
+            return sc.shichi(x)[1]
+        assert_mpmath_equal(chi, mpmath.chi, [Arg()])
+        # check asymptotic series cross-over
+        assert_mpmath_equal(chi, mpmath.chi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])])
+
+    def test_chi_complex(self):
+        def chi(z):
+            return sc.shichi(z)[1]
+        # chi oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            chi,
+            mpmath.chi,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-12,
+        )
+
+    def test_ci(self):
+        def ci(x):
+            return sc.sici(x)[1]
+        # oscillating function: limit range
+        assert_mpmath_equal(ci, mpmath.ci, [Arg(-1e8, 1e8)])
+
+    def test_ci_complex(self):
+        def ci(z):
+            return sc.sici(z)[1]
+        # ci oscillates as Re[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            ci,
+            mpmath.ci,
+            [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))],
+            rtol=1e-8,
+        )
+
+    def test_cospi(self):
+        eps = np.finfo(float).eps
+        assert_mpmath_equal(_cospi, mpmath.cospi, [Arg()], nan_ok=False, rtol=2*eps)
+
+    def test_cospi_complex(self):
+        assert_mpmath_equal(
+            _cospi,
+            mpmath.cospi,
+            [ComplexArg()],
+            nan_ok=False,
+            rtol=1e-13,
+        )
+
+    def test_digamma(self):
+        assert_mpmath_equal(
+            sc.digamma,
+            exception_to_nan(mpmath.digamma),
+            [Arg()],
+            rtol=1e-12,
+            dps=50,
+        )
+
+    def test_digamma_complex(self):
+        # Test on a cut plane because mpmath will hang. See
+        # test_digamma_negreal for tests on the negative real axis.
+        def param_filter(z):
+            return np.where((z.real < 0) & (np.abs(z.imag) < 1.12), False, True)
+
+        assert_mpmath_equal(
+            sc.digamma,
+            exception_to_nan(mpmath.digamma),
+            [ComplexArg()],
+            rtol=1e-13,
+            dps=40,
+            param_filter=param_filter
+        )
+
+    def test_e1(self):
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            [Arg()],
+            rtol=1e-14,
+        )
+
+    def test_e1_complex(self):
+        # E_1 oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-11,
+        )
+
+        # Check cross-over region
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            (np.linspace(-50, 50, 171)[:, None]
+             + np.r_[0, np.logspace(-3, 2, 61), -np.logspace(-3, 2, 11)]*1j).ravel(),
+            rtol=1e-11,
+        )
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            (np.linspace(-50, -35, 10000) + 0j),
+            rtol=1e-11,
+        )
+
+    def test_exprel(self):
+        assert_mpmath_equal(
+            sc.exprel,
+            lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'),
+            [Arg(a=-np.log(np.finfo(np.float64).max),
+                 b=np.log(np.finfo(np.float64).max))],
+        )
+        assert_mpmath_equal(
+            sc.exprel,
+            lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'),
+            np.array([1e-12, 1e-24, 0, 1e12, 1e24, np.inf]),
+            rtol=1e-11,
+        )
+        assert_(np.isinf(sc.exprel(np.inf)))
+        assert_(sc.exprel(-np.inf) == 0)
+
+    def test_expm1_complex(self):
+        # Oscillates as a function of Im[z], so limit range to avoid loss of precision
+        assert_mpmath_equal(
+            sc.expm1,
+            mpmath.expm1,
+            [ComplexArg(complex(-np.inf, -1e7), complex(np.inf, 1e7))],
+        )
+
+    def test_log1p_complex(self):
+        assert_mpmath_equal(
+            sc.log1p,
+            lambda x: mpmath.log(x+1),
+            [ComplexArg()],
+            dps=60,
+        )
+
+    def test_log1pmx(self):
+        assert_mpmath_equal(
+            _log1pmx,
+            lambda x: mpmath.log(x + 1) - x,
+            [Arg()],
+            dps=60,
+            rtol=1e-14,
+        )
+
+    def test_ei(self):
+        assert_mpmath_equal(sc.expi, mpmath.ei, [Arg()], rtol=1e-11)
+
+    def test_ei_complex(self):
+        # Ei oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            sc.expi,
+            mpmath.ei,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-9,
+        )
+
+    def test_ellipe(self):
+        assert_mpmath_equal(sc.ellipe, mpmath.ellipe, [Arg(b=1.0)])
+
+    def test_ellipeinc(self):
+        assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(-1e3, 1e3), Arg(b=1.0)])
+
+    def test_ellipeinc_largephi(self):
+        assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(), Arg()])
+
+    def test_ellipf(self):
+        assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(-1e3, 1e3), Arg()])
+
+    def test_ellipf_largephi(self):
+        assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(), Arg()])
+
+    def test_ellipk(self):
+        assert_mpmath_equal(sc.ellipk, mpmath.ellipk, [Arg(b=1.0)])
+        assert_mpmath_equal(
+            sc.ellipkm1,
+            lambda m: mpmath.ellipk(1 - m),
+            [Arg(a=0.0)],
+            dps=400,
+        )
+
+    def test_ellipkinc(self):
+        def ellipkinc(phi, m):
+            return mpmath.ellippi(0, phi, m)
+        assert_mpmath_equal(
+            sc.ellipkinc,
+            ellipkinc,
+            [Arg(-1e3, 1e3), Arg(b=1.0)],
+            ignore_inf_sign=True,
+        )
+
+    def test_ellipkinc_largephi(self):
+        def ellipkinc(phi, m):
+            return mpmath.ellippi(0, phi, m)
+        assert_mpmath_equal(
+            sc.ellipkinc,
+            ellipkinc,
+            [Arg(), Arg(b=1.0)],
+            ignore_inf_sign=True,
+        )
+
+    def test_ellipfun_sn(self):
+        def sn(u, m):
+            # mpmath doesn't get the zero at u = 0--fix that
+            if u == 0:
+                return 0
+            else:
+                return mpmath.ellipfun("sn", u=u, m=m)
+
+        # Oscillating function --- limit range of first argument; the
+        # loss of precision there is an expected numerical feature
+        # rather than an actual bug
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[0],
+            sn,
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_ellipfun_cn(self):
+        # see comment in ellipfun_sn
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[1],
+            lambda u, m: mpmath.ellipfun("cn", u=u, m=m),
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_ellipfun_dn(self):
+        # see comment in ellipfun_sn
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[2],
+            lambda u, m: mpmath.ellipfun("dn", u=u, m=m),
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_erf(self):
+        assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [Arg()])
+
+    def test_erf_complex(self):
+        assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [ComplexArg()], n=200)
+
+    def test_erfc(self):
+        assert_mpmath_equal(
+            sc.erfc,
+            exception_to_nan(lambda z: mpmath.erfc(z)),
+            [Arg()],
+            rtol=1e-13,
+        )
+
+    def test_erfc_complex(self):
+        assert_mpmath_equal(
+            sc.erfc,
+            exception_to_nan(lambda z: mpmath.erfc(z)),
+            [ComplexArg()],
+            n=200,
+        )
+
+    def test_erfi(self):
+        assert_mpmath_equal(sc.erfi, mpmath.erfi, [Arg()], n=200)
+
+    def test_erfi_complex(self):
+        assert_mpmath_equal(sc.erfi, mpmath.erfi, [ComplexArg()], n=200)
+
+    def test_ndtr(self):
+        assert_mpmath_equal(
+            sc.ndtr,
+            exception_to_nan(lambda z: mpmath.ncdf(z)),
+            [Arg()],
+            n=200,
+        )
+
+    def test_ndtr_complex(self):
+        assert_mpmath_equal(
+            sc.ndtr,
+            lambda z: mpmath.erfc(-z/np.sqrt(2.))/2.,
+            [ComplexArg(a=complex(-10000, -10000), b=complex(10000, 10000))],
+            n=400,
+        )
+
+    def test_log_ndtr(self):
+        assert_mpmath_equal(
+            sc.log_ndtr,
+            exception_to_nan(lambda z: mpmath.log(mpmath.ncdf(z))),
+            [Arg()], n=600, dps=300, rtol=1e-13,
+        )
+
+    def test_log_ndtr_complex(self):
+        assert_mpmath_equal(
+            sc.log_ndtr,
+            exception_to_nan(lambda z: mpmath.log(mpmath.erfc(-z/np.sqrt(2.))/2.)),
+            [ComplexArg(a=complex(-10000, -100), b=complex(10000, 100))],
+            n=200, dps=300,
+        )
+
+    def test_eulernum(self):
+        assert_mpmath_equal(
+            lambda n: sc.euler(n)[-1],
+            mpmath.eulernum,
+            [IntArg(1, 10000)],
+            n=10000,
+        )
+
+    def test_expint(self):
+        assert_mpmath_equal(
+            sc.expn,
+            mpmath.expint,
+            [IntArg(0, 200), Arg(0, np.inf)],
+            rtol=1e-13,
+            dps=160,
+        )
+
+    def test_fresnels(self):
+        def fresnels(x):
+            return sc.fresnel(x)[0]
+        assert_mpmath_equal(fresnels, mpmath.fresnels, [Arg()])
+
+    def test_fresnelc(self):
+        def fresnelc(x):
+            return sc.fresnel(x)[1]
+        assert_mpmath_equal(fresnelc, mpmath.fresnelc, [Arg()])
+
+    def test_gamma(self):
+        assert_mpmath_equal(sc.gamma, exception_to_nan(mpmath.gamma), [Arg()])
+
+    def test_gamma_complex(self):
+        assert_mpmath_equal(
+            sc.gamma,
+            exception_to_nan(mpmath.gamma),
+            [ComplexArg()],
+            rtol=5e-13,
+        )
+
+    def test_gammainc(self):
+        # Larger arguments are tested in test_data.py:test_local
+        assert_mpmath_equal(
+            sc.gammainc,
+            lambda z, b: mpmath.gammainc(z, b=b, regularized=True),
+            [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)],
+            nan_ok=False,
+            rtol=1e-11,
+        )
+
+    def test_gammaincc(self):
+        # Larger arguments are tested in test_data.py:test_local
+        assert_mpmath_equal(
+            sc.gammaincc,
+            lambda z, a: mpmath.gammainc(z, a=a, regularized=True),
+            [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)],
+            nan_ok=False,
+            rtol=1e-11,
+        )
+
+    def test_gammaln(self):
+        # The real part of loggamma is log(|gamma(z)|).
+        def f(z):
+            return mpmath.loggamma(z).real
+
+        assert_mpmath_equal(sc.gammaln, exception_to_nan(f), [Arg()])
+
+    @pytest.mark.xfail(run=False)
+    def test_gegenbauer(self):
+        assert_mpmath_equal(
+            sc.eval_gegenbauer,
+            exception_to_nan(mpmath.gegenbauer),
+            [Arg(-1e3, 1e3), Arg(), Arg()],
+        )
+
+    def test_gegenbauer_int(self):
+        # Redefine functions to deal with numerical + mpmath issues
+        def gegenbauer(n, a, x):
+            # Avoid overflow at large `a` (mpmath would need an even larger
+            # dps to handle this correctly, so just skip this region)
+            if abs(a) > 1e100:
+                return np.nan
+
+            # Deal with n=0, n=1 correctly; mpmath 0.17 doesn't do these
+            # always correctly
+            if n == 0:
+                r = 1.0
+            elif n == 1:
+                r = 2*a*x
+            else:
+                r = mpmath.gegenbauer(n, a, x)
+
+            # Mpmath 0.17 gives wrong results (spurious zero) in some cases, so
+            # compute the value by perturbing the result
+            if float(r) == 0 and a < -1 and float(a) == int(float(a)):
+                r = mpmath.gegenbauer(n, a + mpmath.mpf('1e-50'), x)
+                if abs(r) < mpmath.mpf('1e-50'):
+                    r = mpmath.mpf('0.0')
+
+            # Differing overflow thresholds in scipy vs. mpmath
+            if abs(r) > 1e270:
+                return np.inf
+            return r
+
+        def sc_gegenbauer(n, a, x):
+            r = sc.eval_gegenbauer(int(n), a, x)
+            # Differing overflow thresholds in scipy vs. mpmath
+            if abs(r) > 1e270:
+                return np.inf
+            return r
+        assert_mpmath_equal(
+            sc_gegenbauer,
+            exception_to_nan(gegenbauer),
+            [IntArg(0, 100), Arg(-1e9, 1e9), Arg()],
+            n=40000, dps=100, ignore_inf_sign=True, rtol=1e-6,
+        )
+
+        # Check the small-x expansion
+        assert_mpmath_equal(
+            sc_gegenbauer,
+            exception_to_nan(gegenbauer),
+            [IntArg(0, 100), Arg(), FixedArg(np.logspace(-30, -4, 30))],
+            dps=100, ignore_inf_sign=True,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_gegenbauer_complex(self):
+        assert_mpmath_equal(
+            lambda n, a, x: sc.eval_gegenbauer(int(n), a.real, x),
+            exception_to_nan(mpmath.gegenbauer),
+            [IntArg(0, 100), Arg(), ComplexArg()],
+        )
+
+    @nonfunctional_tooslow
+    def test_gegenbauer_complex_general(self):
+        assert_mpmath_equal(
+            lambda n, a, x: sc.eval_gegenbauer(n.real, a.real, x),
+            exception_to_nan(mpmath.gegenbauer),
+            [Arg(-1e3, 1e3), Arg(), ComplexArg()],
+        )
+
+    def test_hankel1(self):
+        assert_mpmath_equal(
+            sc.hankel1,
+            exception_to_nan(lambda v, x: mpmath.hankel1(v, x, **HYPERKW)),
+            [Arg(-1e20, 1e20), Arg()],
+        )
+
+    def test_hankel2(self):
+        assert_mpmath_equal(
+            sc.hankel2,
+            exception_to_nan(lambda v, x: mpmath.hankel2(v, x, **HYPERKW)),
+            [Arg(-1e20, 1e20), Arg()],
+        )
+
+    @pytest.mark.xfail(run=False, reason="issues at intermediately large orders")
+    def test_hermite(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_hermite(int(n), x),
+            exception_to_nan(mpmath.hermite),
+            [IntArg(0, 10000), Arg()],
+        )
+
+    # hurwitz: same as zeta
+
+    def test_hyp0f1(self):
+        # mpmath reports no convergence unless maxterms is large enough
+        KW = dict(maxprec=400, maxterms=1500)
+        # n=500 (non-xslow default) fails for one bad point
+        assert_mpmath_equal(
+            sc.hyp0f1,
+            lambda a, x: mpmath.hyp0f1(a, x, **KW),
+            [Arg(-1e7, 1e7), Arg(0, 1e5)],
+            n=5000,
+        )
+        # NB: The range of the second parameter ("z") is limited from below
+        # because of an overflow in the intermediate calculations. The way
+        # for fix it is to implement an asymptotic expansion for Bessel J
+        # (similar to what is implemented for Bessel I here).
+
+    def test_hyp0f1_complex(self):
+        assert_mpmath_equal(
+            lambda a, z: sc.hyp0f1(a.real, z),
+            exception_to_nan(lambda a, x: mpmath.hyp0f1(a, x, **HYPERKW)),
+            [Arg(-10, 10), ComplexArg(complex(-120, -120), complex(120, 120))],
+        )
+        # NB: The range of the first parameter ("v") are limited by an overflow
+        # in the intermediate calculations. Can be fixed by implementing an
+        # asymptotic expansion for Bessel functions for large order.
+
+    def test_hyp1f1(self):
+        def mpmath_hyp1f1(a, b, x):
+            try:
+                return mpmath.hyp1f1(a, b, x)
+            except ZeroDivisionError:
+                return np.inf
+
+        assert_mpmath_equal(
+            sc.hyp1f1,
+            mpmath_hyp1f1,
+            [Arg(-50, 50), Arg(1, 50, inclusive_a=False), Arg(-50, 50)],
+            n=500,
+            nan_ok=False,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_hyp1f1_complex(self):
+        assert_mpmath_equal(
+            inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)),
+            exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)),
+            [Arg(-1e3, 1e3), Arg(-1e3, 1e3), ComplexArg()],
+            n=2000,
+        )
+
+    @nonfunctional_tooslow
+    def test_hyp2f1_complex(self):
+        # SciPy's hyp2f1 seems to have performance and accuracy problems
+        assert_mpmath_equal(
+            lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x),
+            exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)),
+            [Arg(-1e2, 1e2), Arg(-1e2, 1e2), Arg(-1e2, 1e2), ComplexArg()],
+            n=10,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_hyperu(self):
+        assert_mpmath_equal(
+            sc.hyperu,
+            exception_to_nan(lambda a, b, x: mpmath.hyperu(a, b, x, **HYPERKW)),
+            [Arg(), Arg(), Arg()],
+        )
+
+    @pytest.mark.xfail_on_32bit("mpmath issue gh-342: "
+                                "unsupported operand mpz, long for pow")
+    def test_igam_fac(self):
+        def mp_igam_fac(a, x):
+            return mpmath.power(x, a)*mpmath.exp(-x)/mpmath.gamma(a)
+
+        assert_mpmath_equal(
+            _igam_fac,
+            mp_igam_fac,
+            [Arg(0, 1e14, inclusive_a=False), Arg(0, 1e14)],
+            rtol=1e-10,
+            dps=29,
+        )
+
+    def test_j0(self):
+        # The Bessel function at large arguments is j0(x) ~ cos(x + phi)/sqrt(x)
+        # and at large arguments the phase of the cosine loses precision.
+        #
+        # This is numerically expected behavior, so we compare only up to
+        # 1e8 = 1e15 * 1e-7
+        assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e3, 1e3)])
+        assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e8, 1e8)], rtol=1e-5)
+
+    def test_j1(self):
+        # See comment in test_j0
+        assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e3, 1e3)])
+        assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e8, 1e8)], rtol=1e-5)
+
+    @pytest.mark.xfail(run=False)
+    def test_jacobi(self):
+        assert_mpmath_equal(
+            sc.eval_jacobi,
+            exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)),
+            [Arg(), Arg(), Arg(), Arg()],
+        )
+        assert_mpmath_equal(
+            lambda n, b, c, x: sc.eval_jacobi(int(n), b, c, x),
+            exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)),
+            [IntArg(), Arg(), Arg(), Arg()],
+        )
+
+    def test_jacobi_int(self):
+        # Redefine functions to deal with numerical + mpmath issues
+        def jacobi(n, a, b, x):
+            # Mpmath does not handle n=0 case always correctly
+            if n == 0:
+                return 1.0
+            return mpmath.jacobi(n, a, b, x)
+        assert_mpmath_equal(
+            lambda n, a, b, x: sc.eval_jacobi(int(n), a, b, x),
+            lambda n, a, b, x: exception_to_nan(jacobi)(n, a, b, x, **HYPERKW),
+            [IntArg(), Arg(), Arg(), Arg()],
+            n=20000,
+            dps=50,
+        )
+
+    def test_kei(self):
+        def kei(x):
+            if x == 0:
+                # work around mpmath issue at x=0
+                return -pi/4
+            return exception_to_nan(mpmath.kei)(0, x, **HYPERKW)
+        assert_mpmath_equal(sc.kei, kei, [Arg(-1e30, 1e30)], n=1000)
+
+    def test_ker(self):
+        assert_mpmath_equal(
+            sc.ker,
+            exception_to_nan(lambda x: mpmath.ker(0, x, **HYPERKW)),
+            [Arg(-1e30, 1e30)],
+            n=1000,
+        )
+
+    @nonfunctional_tooslow
+    def test_laguerre(self):
+        assert_mpmath_equal(
+            trace_args(sc.eval_laguerre),
+            lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW),
+            [Arg(), Arg()],
+        )
+
+    def test_laguerre_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_laguerre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW),
+            [IntArg(), Arg()],
+            n=20000,
+        )
+
+    @pytest.mark.xfail_on_32bit("see gh-3551 for bad points")
+    def test_lambertw_real(self):
+        assert_mpmath_equal(
+            lambda x, k: sc.lambertw(x, int(k.real)),
+            lambda x, k: mpmath.lambertw(x, int(k.real)),
+            [ComplexArg(-np.inf, np.inf), IntArg(0, 10)],
+            rtol=1e-13, nan_ok=False,
+        )
+
+    def test_lanczos_sum_expg_scaled(self):
+        maxgamma = 171.624376956302725
+        e = np.exp(1)
+        g = 6.024680040776729583740234375
+
+        def gamma(x):
+            with np.errstate(over='ignore'):
+                fac = ((x + g - 0.5)/e)**(x - 0.5)
+                if fac != np.inf:
+                    res = fac*_lanczos_sum_expg_scaled(x)
+                else:
+                    fac = ((x + g - 0.5)/e)**(0.5*(x - 0.5))
+                    res = fac*_lanczos_sum_expg_scaled(x)
+                    res *= fac
+            return res
+
+        assert_mpmath_equal(
+            gamma,
+            mpmath.gamma,
+            [Arg(0, maxgamma, inclusive_a=False)],
+            rtol=1e-13,
+        )
+
+    @nonfunctional_tooslow
+    def test_legendre(self):
+        assert_mpmath_equal(sc.eval_legendre, mpmath.legendre, [Arg(), Arg()])
+
+    def test_legendre_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_legendre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW),
+            [IntArg(), Arg()],
+            n=20000,
+        )
+
+        # Check the small-x expansion
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_legendre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW),
+            [IntArg(), FixedArg(np.logspace(-30, -4, 20))],
+        )
+
+    def test_legenp(self):
+        def lpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    v = sc.lpmn(m, n, z)[0][-1,-1]
+            except ValueError:
+                return np.nan
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = np.inf * np.sign(v.real)
+            return v
+
+        def lpnm_2(n, m, z):
+            v = sc.lpmv(m, n, z)
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = np.inf * np.sign(v.real)
+            return v
+
+        def legenp(n, m, z):
+            if (z == 1 or z == -1) and int(n) == n:
+                # Special case (mpmath may give inf, we take the limit by
+                # continuity)
+                if m == 0:
+                    if n < 0:
+                        n = -n - 1
+                    return mpmath.power(mpmath.sign(z), n)
+                else:
+                    return 0
+
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+
+            typ = 2 if abs(z) <= 1 else 3
+            v = exception_to_nan(mpmath.legenp)(n, m, z, type=typ)
+
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = mpmath.inf * mpmath.sign(v.real)
+
+            return v
+
+        assert_mpmath_equal(lpnm, legenp, [IntArg(-100, 100), IntArg(-100, 100), Arg()])
+
+        assert_mpmath_equal(
+            lpnm_2,
+            legenp,
+            [IntArg(-100, 100), Arg(-100, 100), Arg(-1, 1)],
+            atol=1e-10,
+        )
+
+    def test_legenp_complex_2(self):
+        def clpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    return sc.clpmn(m.real, n.real, z, type=2)[0][-1,-1]
+            except ValueError:
+                return np.nan
+
+        def legenp(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=2)
+
+        # mpmath is quite slow here
+        x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3])
+        y = np.array([-1e3, -0.5, 0.5, 1.3])
+        z = (x[:,None] + 1j*y[None,:]).ravel()
+
+        assert_mpmath_equal(
+            clpnm,
+            legenp,
+            [FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg(z)],
+            rtol=1e-6,
+            n=500,
+        )
+
+    def test_legenp_complex_3(self):
+        def clpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    return sc.clpmn(m.real, n.real, z, type=3)[0][-1,-1]
+            except ValueError:
+                return np.nan
+
+        def legenp(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=3)
+
+        # mpmath is quite slow here
+        x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3])
+        y = np.array([-1e3, -0.5, 0.5, 1.3])
+        z = (x[:,None] + 1j*y[None,:]).ravel()
+
+        assert_mpmath_equal(
+            clpnm,
+            legenp,
+            [FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg(z)],
+            rtol=1e-6,
+            n=500,
+        )
+
+    @pytest.mark.xfail(run=False, reason="apparently picks wrong function at |z| > 1")
+    def test_legenq(self):
+        def lqnm(n, m, z):
+            return sc.lqmn(m, n, z)[0][-1,-1]
+
+        def legenq(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenq)(n, m, z, type=2)
+
+        assert_mpmath_equal(
+            lqnm,
+            legenq,
+            [IntArg(0, 100), IntArg(0, 100), Arg()],
+        )
+
+    @nonfunctional_tooslow
+    def test_legenq_complex(self):
+        def lqnm(n, m, z):
+            return sc.lqmn(int(m.real), int(n.real), z)[0][-1,-1]
+
+        def legenq(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenq)(int(n.real), int(m.real), z, type=2)
+
+        assert_mpmath_equal(
+            lqnm,
+            legenq,
+            [IntArg(0, 100), IntArg(0, 100), ComplexArg()],
+            n=100,
+        )
+
+    def test_lgam1p(self):
+        def param_filter(x):
+            # Filter the poles
+            return np.where((np.floor(x) == x) & (x <= 0), False, True)
+
+        def mp_lgam1p(z):
+            # The real part of loggamma is log(|gamma(z)|)
+            return mpmath.loggamma(1 + z).real
+
+        assert_mpmath_equal(
+            _lgam1p,
+            mp_lgam1p,
+            [Arg()],
+            rtol=1e-13,
+            dps=100,
+            param_filter=param_filter,
+        )
+
+    def test_loggamma(self):
+        def mpmath_loggamma(z):
+            try:
+                res = mpmath.loggamma(z)
+            except ValueError:
+                res = complex(np.nan, np.nan)
+            return res
+
+        assert_mpmath_equal(
+            sc.loggamma,
+            mpmath_loggamma,
+            [ComplexArg()],
+            nan_ok=False,
+            distinguish_nan_and_inf=False,
+            rtol=5e-14,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_pcfd(self):
+        def pcfd(v, x):
+            return sc.pbdv(v, x)[0]
+        assert_mpmath_equal(
+            pcfd,
+            exception_to_nan(lambda v, x: mpmath.pcfd(v, x, **HYPERKW)),
+            [Arg(), Arg()],
+        )
+
+    @pytest.mark.xfail(run=False, reason="it's not the same as the mpmath function --- "
+                                         "maybe different definition?")
+    def test_pcfv(self):
+        def pcfv(v, x):
+            return sc.pbvv(v, x)[0]
+        assert_mpmath_equal(
+            pcfv,
+            lambda v, x: time_limited()(exception_to_nan(mpmath.pcfv))(v, x, **HYPERKW),
+            [Arg(), Arg()],
+            n=1000,
+        )
+
+    def test_pcfw(self):
+        def pcfw(a, x):
+            return sc.pbwa(a, x)[0]
+
+        def dpcfw(a, x):
+            return sc.pbwa(a, x)[1]
+
+        def mpmath_dpcfw(a, x):
+            return mpmath.diff(mpmath.pcfw, (a, x), (0, 1))
+
+        # The Zhang and Jin implementation only uses Taylor series and
+        # is thus accurate in only a very small range.
+        assert_mpmath_equal(
+            pcfw,
+            mpmath.pcfw,
+            [Arg(-5, 5), Arg(-5, 5)],
+            rtol=2e-8,
+            n=100,
+        )
+
+        assert_mpmath_equal(
+            dpcfw,
+            mpmath_dpcfw,
+            [Arg(-5, 5), Arg(-5, 5)],
+            rtol=2e-9,
+            n=100,
+        )
+
+    @pytest.mark.xfail(run=False,
+                       reason="issues at large arguments (atol OK, rtol not) "
+                              "and = _pep440.Version("1.0.0"):
+            # no workarounds needed
+            mppoch = mpmath.rf
+        else:
+            def mppoch(a, m):
+                # deal with cases where the result in double precision
+                # hits exactly a non-positive integer, but the
+                # corresponding extended-precision mpf floats don't
+                if float(a + m) == int(a + m) and float(a + m) <= 0:
+                    a = mpmath.mpf(a)
+                    m = int(a + m) - a
+                return mpmath.rf(a, m)
+
+        assert_mpmath_equal(sc.poch, mppoch, [Arg(), Arg()], dps=400)
+
+    def test_sinpi(self):
+        eps = np.finfo(float).eps
+        assert_mpmath_equal(
+            _sinpi,
+            mpmath.sinpi,
+            [Arg()],
+            nan_ok=False,
+            rtol=2*eps,
+        )
+
+    def test_sinpi_complex(self):
+        assert_mpmath_equal(
+            _sinpi,
+            mpmath.sinpi,
+            [ComplexArg()],
+            nan_ok=False,
+            rtol=2e-14,
+        )
+
+    def test_shi(self):
+        def shi(x):
+            return sc.shichi(x)[0]
+        assert_mpmath_equal(shi, mpmath.shi, [Arg()])
+        # check asymptotic series cross-over
+        assert_mpmath_equal(shi, mpmath.shi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])])
+
+    def test_shi_complex(self):
+        def shi(z):
+            return sc.shichi(z)[0]
+        # shi oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            shi,
+            mpmath.shi,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-12,
+        )
+
+    def test_si(self):
+        def si(x):
+            return sc.sici(x)[0]
+        assert_mpmath_equal(si, mpmath.si, [Arg()])
+
+    def test_si_complex(self):
+        def si(z):
+            return sc.sici(z)[0]
+        # si oscillates as Re[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            si,
+            mpmath.si,
+            [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))],
+            rtol=1e-12,
+        )
+
+    def test_spence(self):
+        # mpmath uses a different convention for the dilogarithm
+        def dilog(x):
+            return mpmath.polylog(2, 1 - x)
+        # Spence has a branch cut on the negative real axis
+        assert_mpmath_equal(
+            sc.spence,
+            exception_to_nan(dilog),
+            [Arg(0, np.inf)],
+            rtol=1e-14,
+        )
+
+    def test_spence_complex(self):
+        def dilog(z):
+            return mpmath.polylog(2, 1 - z)
+        assert_mpmath_equal(
+            sc.spence,
+            exception_to_nan(dilog),
+            [ComplexArg()],
+            rtol=1e-14,
+        )
+
+    def test_spherharm(self):
+        def spherharm(l, m, theta, phi):
+            if m > l:
+                return np.nan
+            with suppress_warnings() as sup:
+                sup.filter(category=DeprecationWarning)
+                return sc.sph_harm(m, l, phi, theta)
+        assert_mpmath_equal(
+            spherharm,
+            mpmath.spherharm,
+            [IntArg(0, 100), IntArg(0, 100), Arg(a=0, b=pi), Arg(a=0, b=2*pi)],
+            atol=1e-8,
+            n=6000,
+            dps=150,
+        )
+
+    def test_struveh(self):
+        assert_mpmath_equal(
+            sc.struve,
+            exception_to_nan(mpmath.struveh),
+            [Arg(-1e4, 1e4), Arg(0, 1e4)],
+            rtol=5e-10,
+        )
+
+    def test_struvel(self):
+        def mp_struvel(v, z):
+            if v < 0 and z < -v and abs(v) > 1000:
+                # larger DPS needed for correct results
+                old_dps = mpmath.mp.dps
+                try:
+                    mpmath.mp.dps = 500
+                    return mpmath.struvel(v, z)
+                finally:
+                    mpmath.mp.dps = old_dps
+            return mpmath.struvel(v, z)
+
+        assert_mpmath_equal(
+            sc.modstruve,
+            exception_to_nan(mp_struvel),
+            [Arg(-1e4, 1e4), Arg(0, 1e4)],
+            rtol=5e-10,
+            ignore_inf_sign=True,
+        )
+
+    def test_wrightomega_real(self):
+        def mpmath_wrightomega_real(x):
+            return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
+
+        # For x < -1000 the Wright Omega function is just 0 to double
+        # precision, and for x > 1e21 it is just x to double
+        # precision.
+        assert_mpmath_equal(
+            sc.wrightomega,
+            mpmath_wrightomega_real,
+            [Arg(-1000, 1e21)],
+            rtol=5e-15,
+            atol=0,
+            nan_ok=False,
+        )
+
+    def test_wrightomega(self):
+        assert_mpmath_equal(
+            sc.wrightomega,
+            lambda z: _mpmath_wrightomega(z, 25),
+            [ComplexArg()],
+            rtol=1e-14,
+            nan_ok=False,
+        )
+
+    def test_hurwitz_zeta(self):
+        assert_mpmath_equal(
+            sc.zeta,
+            exception_to_nan(mpmath.zeta),
+            [Arg(a=1, b=1e10, inclusive_a=False), Arg(a=0, inclusive_a=False)],
+        )
+
+    def test_riemann_zeta(self):
+        assert_mpmath_equal(
+            sc.zeta,
+            lambda x: mpmath.zeta(x) if x != 1 else mpmath.inf,
+            [Arg(-100, 100)],
+            nan_ok=False,
+            rtol=5e-13,
+        )
+
+    def test_zetac(self):
+        assert_mpmath_equal(
+            sc.zetac,
+            lambda x: mpmath.zeta(x) - 1 if x != 1 else mpmath.inf,
+            [Arg(-100, 100)],
+            nan_ok=False,
+            dps=45,
+            rtol=5e-13,
+        )
+
+    def test_boxcox(self):
+
+        def mp_boxcox(x, lmbda):
+            x = mpmath.mp.mpf(x)
+            lmbda = mpmath.mp.mpf(lmbda)
+            if lmbda == 0:
+                return mpmath.mp.log(x)
+            else:
+                return mpmath.mp.powm1(x, lmbda) / lmbda
+
+        assert_mpmath_equal(
+            sc.boxcox,
+            exception_to_nan(mp_boxcox),
+            [Arg(a=0, inclusive_a=False), Arg()],
+            n=200,
+            dps=60,
+            rtol=1e-13,
+        )
+
+    def test_boxcox1p(self):
+
+        def mp_boxcox1p(x, lmbda):
+            x = mpmath.mp.mpf(x)
+            lmbda = mpmath.mp.mpf(lmbda)
+            one = mpmath.mp.mpf(1)
+            if lmbda == 0:
+                return mpmath.mp.log(one + x)
+            else:
+                return mpmath.mp.powm1(one + x, lmbda) / lmbda
+
+        assert_mpmath_equal(
+            sc.boxcox1p,
+            exception_to_nan(mp_boxcox1p),
+            [Arg(a=-1, inclusive_a=False), Arg()],
+            n=200,
+            dps=60,
+            rtol=1e-13,
+        )
+
+    def test_spherical_jn(self):
+        def mp_spherical_jn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_jn(int(n), z),
+            exception_to_nan(mp_spherical_jn),
+            [IntArg(0, 200), Arg(-1e8, 1e8)],
+            dps=300,
+            # underflow of `spherical_jn` is a bit premature; see gh-21629
+            param_filter=(None, lambda z: np.abs(z) > 1e-20),
+        )
+
+    def test_spherical_jn_complex(self):
+        def mp_spherical_jn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_jn(int(n.real), z),
+            exception_to_nan(mp_spherical_jn),
+            [IntArg(0, 200), ComplexArg()]
+        )
+
+    def test_spherical_yn(self):
+        def mp_spherical_yn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_yn(int(n), z),
+            exception_to_nan(mp_spherical_yn),
+            [IntArg(0, 200), Arg(-1e10, 1e10)],
+            dps=100,
+        )
+
+    def test_spherical_yn_complex(self):
+        def mp_spherical_yn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_yn(int(n.real), z),
+            exception_to_nan(mp_spherical_yn),
+            [IntArg(0, 200), ComplexArg()],
+        )
+
+    def test_spherical_in(self):
+        def mp_spherical_in(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_in(int(n), z),
+            exception_to_nan(mp_spherical_in),
+            [IntArg(0, 200), Arg()],
+            dps=200,
+            atol=10**(-278),
+        )
+
+    def test_spherical_in_complex(self):
+        def mp_spherical_in(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_in(int(n.real), z),
+            exception_to_nan(mp_spherical_in),
+            [IntArg(0, 200), ComplexArg()],
+        )
+
+    def test_spherical_kn(self):
+        def mp_spherical_kn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if mpmath.mpmathify(z).imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_kn(int(n), z),
+            exception_to_nan(mp_spherical_kn),
+            [IntArg(0, 150), Arg()],
+            dps=100,
+        )
+
+    @pytest.mark.xfail(run=False,
+                       reason="Accuracy issues near z = -1 inherited from kv.")
+    def test_spherical_kn_complex(self):
+        def mp_spherical_kn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_kn(int(n.real), z),
+            exception_to_nan(mp_spherical_kn),
+            [IntArg(0, 200), ComplexArg()],
+            dps=200,
+        )
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py
new file mode 100644
index 0000000000000000000000000000000000000000..122e6009bd71e77ae39f55da5cf056500ff526a9
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py
@@ -0,0 +1,48 @@
+import numpy as np
+import scipy.special as sc
+from numpy.testing import assert_almost_equal, assert_array_equal
+
+
+class TestPdtr:
+    def test(self):
+        val = sc.pdtr(0, 1)
+        assert_almost_equal(val, np.exp(-1))
+
+    def test_m_zero(self):
+        val = sc.pdtr([0, 1, 2], 0)
+        assert_array_equal(val, [1, 1, 1])
+
+    def test_rounding(self):
+        double_val = sc.pdtr([0.1, 1.1, 2.1], 1.0)
+        int_val = sc.pdtr([0, 1, 2], 1.0)
+        assert_array_equal(double_val, int_val)
+
+    def test_inf(self):
+        val = sc.pdtr(np.inf, 1.0)
+        assert_almost_equal(val, 1.0)
+
+    def test_domain(self):
+        val = sc.pdtr(-1.1, 1.0)
+        assert np.isnan(val)
+
+class TestPdtrc:
+    def test_value(self):
+        val = sc.pdtrc(0, 1)
+        assert_almost_equal(val, 1 - np.exp(-1))
+
+    def test_m_zero(self):
+        val = sc.pdtrc([0, 1, 2], 0.0)
+        assert_array_equal(val, [0, 0, 0])
+
+    def test_rounding(self):
+        double_val = sc.pdtrc([0.1, 1.1, 2.1], 1.0)
+        int_val = sc.pdtrc([0, 1, 2], 1.0)
+        assert_array_equal(double_val, int_val)
+
+    def test_inf(self):
+        val = sc.pdtrc(np.inf, 1.0)
+        assert_almost_equal(val, 0.0)
+
+    def test_domain(self):
+        val = sc.pdtrc(-1.1, 1.0)
+        assert np.isnan(val)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..89616b92329691ca76039fe11a7e08f7f3db1150
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py
@@ -0,0 +1,36 @@
+import pytest
+
+from scipy.special._testutils import MissingModule, check_version
+from scipy.special._mptestutils import mp_assert_allclose
+from scipy.special._precompute.utils import lagrange_inversion
+
+try:
+    import sympy
+except ImportError:
+    sympy = MissingModule('sympy')
+
+try:
+    import mpmath as mp
+except ImportError:
+    mp = MissingModule('mpmath')
+
+
+@pytest.mark.slow
+@check_version(sympy, '0.7')
+@check_version(mp, '0.19')
+class TestInversion:
+    @pytest.mark.xfail_on_32bit("rtol only 2e-9, see gh-6938")
+    def test_log(self):
+        with mp.workdps(30):
+            logcoeffs = mp.taylor(lambda x: mp.log(1 + x), 0, 10)
+            expcoeffs = mp.taylor(lambda x: mp.exp(x) - 1, 0, 10)
+            invlogcoeffs = lagrange_inversion(logcoeffs)
+            mp_assert_allclose(invlogcoeffs, expcoeffs)
+
+    @pytest.mark.xfail_on_32bit("rtol only 1e-15, see gh-6938")
+    def test_sin(self):
+        with mp.workdps(30):
+            sincoeffs = mp.taylor(mp.sin, 0, 10)
+            asincoeffs = mp.taylor(mp.asin, 0, 10)
+            invsincoeffs = lagrange_inversion(sincoeffs)
+            mp_assert_allclose(invsincoeffs, asincoeffs, atol=1e-30)
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc39c2eeaf43196d4bf25964a0c2aefec2c8c0b4
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py
@@ -0,0 +1,114 @@
+import os
+import pytest
+import scipy.special as sc
+import shutil
+import tempfile
+
+from uuid import uuid4
+
+from scipy.special._testutils import check_version
+from scipy.special._testutils import MissingModule
+
+try:
+    import cupy  # type: ignore
+except (ImportError, AttributeError):
+    cupy = MissingModule('cupy')
+
+
+def get_test_cases():
+    cases_source = [
+        (sc.beta, "cephes/beta.h", "out0 = xsf::cephes::beta(in0, in1)"),
+        (sc.binom, "binom.h", "out0 = xsf::binom(in0, in1)"),
+        (sc.digamma, "digamma.h", "xsf::digamma(in0)"),
+        (sc.expn, "cephes/expn.h", "out0 = xsf::cephes::expn(in0, in1)"),
+        (sc.hyp2f1, "hyp2f1.h", "out0 = xsf::hyp2f1(in0, in1, in2, in3)"),
+        (sc._ufuncs._lambertw, "lambertw.h", "out0 = xsf::lambertw(in0, in1, in2)"),
+        (sc.ellipkinc, "cephes/ellik.h", "out0 = xsf::cephes::ellik(in0, in1)"),
+        (sc.ellipeinc, "cephes/ellie.h", "out0 = xsf::cephes::ellie(in0, in1)"),
+        (sc.gdtrib, "cdflib.h", "out0 = xsf::gdtrib(in0, in1, in2)"),
+        (sc.sici, "sici.h", "xsf::sici(in0, &out0, &out1)"),
+        (sc.shichi, "sici.h", "xsf::shichi(in0, &out0, &out1)"),
+    ]
+
+    cases = []
+    for ufunc, header, routine in cases_source:
+        preamble = f"#include "
+        for signature in ufunc.types:
+            cases.append((signature, preamble, routine))
+    return cases
+
+
+dtype_map = {
+    "f": "float32",
+    "d": "float64",
+    "F": "complex64",
+    "D": "complex128",
+    "i": "int32",
+    "l": "int64",
+}
+
+
+def get_params(signature):
+    in_, out = signature.split("->")
+    in_params = []
+    out_params = []
+    for i, typecode in enumerate(in_):
+        in_params.append(f"{dtype_map[typecode]} in{i}")
+    for i, typecode in enumerate(out):
+        out_params.append(f"{dtype_map[typecode]} out{i}")
+    in_params = ", ".join(in_params)
+    out_params = ", ".join(out_params)
+    return in_params, out_params
+
+
+def get_sample_input(signature, xp):
+    dtype_map = {
+        "f": xp.float32,
+        "d": xp.float64,
+        "F": xp.complex64,
+        "D": xp.complex128,
+        "i": xp.int32,
+        "l": xp.int64,
+    }
+
+    in_, _ = signature.split("->")
+    args = []
+    for typecode in in_:
+        args.append(xp.zeros(2, dtype=dtype_map[typecode]))
+    return args
+
+
+@pytest.fixture(scope="module", autouse=True)
+def manage_cupy_cache():
+    # Temporarily change cupy kernel cache location so kernel cache will not be polluted
+    # by these tests. Remove temporary cache in teardown.
+    temp_cache_dir = tempfile.mkdtemp()
+    original_cache_dir = os.environ.get('CUPY_CACHE_DIR', None)
+    os.environ['CUPY_CACHE_DIR'] = temp_cache_dir
+
+    yield
+
+    if original_cache_dir is not None:
+        os.environ['CUPY_CACHE_DIR'] = original_cache_dir
+    else:
+        del os.environ['CUPY_CACHE_DIR']
+    shutil.rmtree(temp_cache_dir)
+
+
+@check_version(cupy, "13.0.0")
+@pytest.mark.parametrize("signature,preamble,routine", get_test_cases())
+@pytest.mark.xslow
+def test_compiles_in_cupy(signature, preamble, routine, manage_cupy_cache):
+    name = f"x{uuid4().hex}"
+    in_params, out_params = get_params(signature)
+
+    func = cupy.ElementwiseKernel(
+        in_params,
+        out_params,
+        routine,
+        name,
+        preamble=preamble,
+        options=(f"--include-path={sc._get_include()}", "-std=c++17")
+    )
+
+    _ = func(*get_sample_input(signature, cupy))
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h
new file mode 100644
index 0000000000000000000000000000000000000000..6a9b9ead9d7d458b47c5a51fd3104c9f72ff20a5
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h
@@ -0,0 +1,89 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ *
+ * Original authors: Pauli Virtanen, Eric Moore
+ */
+
+// Binomial coefficient
+
+#pragma once
+
+#include "config.h"
+
+#include "cephes/beta.h"
+#include "cephes/gamma.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline double binom(double n, double k) {
+    double kx, nx, num, den, dk, sgn;
+
+    if (n < 0) {
+        nx = std::floor(n);
+        if (n == nx) {
+            // Undefined
+            return std::numeric_limits::quiet_NaN();
+        }
+    }
+
+    kx = std::floor(k);
+    if (k == kx && (std::abs(n) > 1E-8 || n == 0)) {
+        /* Integer case: use multiplication formula for less rounding
+         * error for cases where the result is an integer.
+         *
+         * This cannot be used for small nonzero n due to loss of
+         * precision. */
+        nx = std::floor(n);
+        if (nx == n && kx > nx / 2 && nx > 0) {
+            // Reduce kx by symmetry
+            kx = nx - kx;
+        }
+
+        if (kx >= 0 && kx < 20) {
+            num = 1.0;
+            den = 1.0;
+            for (int i = 1; i < 1 + static_cast(kx); i++) {
+                num *= i + n - kx;
+                den *= i;
+                if (std::abs(num) > 1E50) {
+                    num /= den;
+                    den = 1.0;
+                }
+            }
+            return num / den;
+        }
+    }
+
+    // general case
+    if (n >= 1E10 * k and k > 0) {
+        // avoid under/overflows intermediate results
+        return std::exp(-cephes::lbeta(1 + n - k, 1 + k) - std::log(n + 1));
+    }
+    if (k > 1E8 * std::abs(n)) {
+        // avoid loss of precision
+        num = cephes::Gamma(1 + n) / std::abs(k) + cephes::Gamma(1 + n) * n / (2 * k * k); // + ...
+        num /= M_PI * std::pow(std::abs(k), n);
+        if (k > 0) {
+            kx = std::floor(k);
+            if (static_cast(kx) == kx) {
+                dk = k - kx;
+                sgn = (static_cast(kx) % 2 == 0) ? 1 : -1;
+            } else {
+                dk = k;
+                sgn = 1;
+            }
+            return num * std::sin((dk - n) * M_PI) * sgn;
+        }
+        kx = std::floor(k);
+        if (static_cast(kx) == kx) {
+            return 0;
+        }
+        return num * std::sin(k * M_PI);
+    }
+    return 1 / (n + 1) / cephes::beta(1 + n - k, 1 + k);
+}
+
+XSF_HOST_DEVICE inline float binom(float n, float k) {
+    return binom(static_cast(n), static_cast(k));
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h
new file mode 100644
index 0000000000000000000000000000000000000000..1ce5550efb6d2b13a45e22c0cbea7952bbd7938c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h
@@ -0,0 +1,100 @@
+
+#pragma once
+
+#include "cephes/igam.h"
+#include "config.h"
+#include "error.h"
+#include "tools.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline double gdtrib(double a, double p, double x) {
+    if (std::isnan(p) || std::isnan(a) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!((0 <= p) && (p <= 1))) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter p is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!(a > 0) || std::isinf(a)) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter a is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!(x >= 0) || std::isinf(x)) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter x is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        if (p == 0.0) {
+            set_error("gdtrib", SF_ERROR_DOMAIN, "Indeterminate result for (x, p) == (0, 0).");
+            return std::numeric_limits::quiet_NaN();
+        }
+        /* gdtrib(a, p, x) tends to 0 as x -> 0 when p > 0 */
+        return 0.0;
+    }
+    if (p == 0.0) {
+        /* gdtrib(a, p, x) tends to infinity as p -> 0 from the right when x > 0. */
+        set_error("gdtrib", SF_ERROR_SINGULAR, NULL);
+        return std::numeric_limits::infinity();
+    }
+    if (p == 1.0) {
+        /* gdtrib(a, p, x) tends to 0 as p -> 1.0 from the left when x > 0. */
+        return 0.0;
+    }
+    double q = 1.0 - p;
+    auto func = [a, p, q, x](double b) {
+	if (p <= q) {
+	    return cephes::igam(b, a * x) - p;
+	}
+	return q - cephes::igamc(b, a * x);
+    };
+    double lower_bound = std::numeric_limits::min();
+    double upper_bound = std::numeric_limits::max();
+    /* To explain the magic constants used below:
+     * 1.0 is the initial guess for the root. -0.875 is the initial step size
+     * for the leading bracket endpoint if the bracket search will proceed to the
+     * left, likewise 7.0 is the initial step size when the bracket search will
+     * proceed to the right. 0.125 is the scale factor for a left moving bracket
+     * search and 8.0 the scale factor for a right moving bracket search. These
+     * constants are chosen so that:
+     *
+     * 1. The scale factor and bracket endpoints remain powers of 2, allowing for
+     *    exact arithmetic, preventing roundoff error from causing numerical catastrophe
+     *    which could lead to unexpected results.
+     * 2. The bracket sizes remain constant in a relative sense. Each candidate bracket
+     *    will contain roughly the same number of floating point values. This means that
+     *    the number of necessary function evaluations in the worst case scenario for
+     *    Chandrupatla's algorithm will remain constant.
+     *
+     * false specifies that the function is not decreasing. 342 is equal to
+     * max(ceil(log_8(DBL_MAX)), ceil(log_(1/8)(DBL_MIN))). An upper bound for the
+     * number of iterations needed in this bracket search to check all normalized
+     * floating point values.
+     */
+    auto [xl, xr, f_xl, f_xr, bracket_status] = detail::bracket_root_for_cdf_inversion(
+        func, 1.0, lower_bound, upper_bound, -0.875, 7.0, 0.125, 8, false, 342
+    );
+    if (bracket_status == 1) {
+        set_error("gdtrib", SF_ERROR_UNDERFLOW, NULL);
+        return 0.0;
+    }
+    if (bracket_status == 2) {
+        set_error("gdtrib", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::infinity();
+    }
+    if (bracket_status >= 3) {
+        set_error("gdtrib", SF_ERROR_OTHER, "Computational Error");
+        return std::numeric_limits::quiet_NaN();
+    }
+    auto [result, root_status] = detail::find_root_chandrupatla(
+        func, xl, xr, f_xl, f_xr, std::numeric_limits::epsilon(), 1e-100, 100
+    );
+    if (root_status) {
+        /* The root finding return should only fail if there's a bug in our code. */
+        set_error("gdtrib", SF_ERROR_OTHER, "Computational Error, (%.17g, %.17g, %.17g)", a, p, x);
+        return std::numeric_limits::quiet_NaN();
+    }
+    return result;
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h
new file mode 100644
index 0000000000000000000000000000000000000000..8db31fa9b3830b1e561a27a349154fc96ab071d3
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h
@@ -0,0 +1,307 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     airy.c
+ *
+ *     Airy function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, ai, aip, bi, bip;
+ * int airy();
+ *
+ * airy( x, _&ai, _&aip, _&bi, _&bip );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Solution of the differential equation
+ *
+ *     y"(x) = xy.
+ *
+ * The function returns the two independent solutions Ai, Bi
+ * and their first derivatives Ai'(x), Bi'(x).
+ *
+ * Evaluation is by power series summation for small x,
+ * by rational minimax approximations for large x.
+ *
+ *
+ *
+ * ACCURACY:
+ * Error criterion is absolute when function <= 1, relative
+ * when function > 1, except * denotes relative error criterion.
+ * For large negative x, the absolute error increases as x^1.5.
+ * For large positive x, the relative error increases as x^1.5.
+ *
+ * Arithmetic  domain   function  # trials      peak         rms
+ * IEEE        -10, 0     Ai        10000       1.6e-15     2.7e-16
+ * IEEE          0, 10    Ai        10000       2.3e-14*    1.8e-15*
+ * IEEE        -10, 0     Ai'       10000       4.6e-15     7.6e-16
+ * IEEE          0, 10    Ai'       10000       1.8e-14*    1.5e-15*
+ * IEEE        -10, 10    Bi        30000       4.2e-15     5.3e-16
+ * IEEE        -10, 10    Bi'       30000       4.9e-15     7.3e-16
+ *
+ */
+/*							airy.c */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double airy_c1 = 0.35502805388781723926;
+        constexpr double airy_c2 = 0.258819403792806798405;
+        constexpr double MAXAIRY = 103.892;
+
+        constexpr double airy_AN[8] = {
+            3.46538101525629032477E-1, 1.20075952739645805542E1, 7.62796053615234516538E1, 1.68089224934630576269E2,
+            1.59756391350164413639E2,  7.05360906840444183113E1, 1.40264691163389668864E1, 9.99999999999999995305E-1,
+        };
+
+        constexpr double airy_AD[8] = {
+            5.67594532638770212846E-1, 1.47562562584847203173E1, 8.45138970141474626562E1, 1.77318088145400459522E2,
+            1.64234692871529701831E2,  7.14778400825575695274E1, 1.40959135607834029598E1, 1.00000000000000000470E0,
+        };
+
+        constexpr double airy_APN[8] = {
+            6.13759184814035759225E-1, 1.47454670787755323881E1, 8.20584123476060982430E1, 1.71184781360976385540E2,
+            1.59317847137141783523E2,  6.99778599330103016170E1, 1.39470856980481566958E1, 1.00000000000000000550E0,
+        };
+
+        constexpr double airy_APD[8] = {
+            3.34203677749736953049E-1, 1.11810297306158156705E1, 7.11727352147859965283E1, 1.58778084372838313640E2,
+            1.53206427475809220834E2,  6.86752304592780337944E1, 1.38498634758259442477E1, 9.99999999999999994502E-1,
+        };
+
+        constexpr double airy_BN16[5] = {
+            -2.53240795869364152689E-1, 5.75285167332467384228E-1,  -3.29907036873225371650E-1,
+            6.44404068948199951727E-2,  -3.82519546641336734394E-3,
+        };
+
+        constexpr double airy_BD16[5] = {
+            /* 1.00000000000000000000E0, */
+            -7.15685095054035237902E0, 1.06039580715664694291E1,   -5.23246636471251500874E0,
+            9.57395864378383833152E-1, -5.50828147163549611107E-2,
+        };
+
+        constexpr double airy_BPPN[5] = {
+            4.65461162774651610328E-1,  -1.08992173800493920734E0, 6.38800117371827987759E-1,
+            -1.26844349553102907034E-1, 7.62487844342109852105E-3,
+        };
+
+        constexpr double airy_BPPD[5] = {
+            /* 1.00000000000000000000E0, */
+            -8.70622787633159124240E0, 1.38993162704553213172E1,   -7.14116144616431159572E0,
+            1.34008595960680518666E0,  -7.84273211323341930448E-2,
+        };
+
+        constexpr double airy_AFN[9] = {
+            -1.31696323418331795333E-1, -6.26456544431912369773E-1, -6.93158036036933542233E-1,
+            -2.79779981545119124951E-1, -4.91900132609500318020E-2, -4.06265923594885404393E-3,
+            -1.59276496239262096340E-4, -2.77649108155232920844E-6, -1.67787698489114633780E-8,
+        };
+
+        constexpr double airy_AFD[9] = {
+            /* 1.00000000000000000000E0, */
+            1.33560420706553243746E1,  3.26825032795224613948E1,  2.67367040941499554804E1,
+            9.18707402907259625840E0,  1.47529146771666414581E0,  1.15687173795188044134E-1,
+            4.40291641615211203805E-3, 7.54720348287414296618E-5, 4.51850092970580378464E-7,
+        };
+
+        constexpr double airy_AGN[11] = {
+            1.97339932091685679179E-2, 3.91103029615688277255E-1, 1.06579897599595591108E0,   9.39169229816650230044E-1,
+            3.51465656105547619242E-1, 6.33888919628925490927E-2, 5.85804113048388458567E-3,  2.82851600836737019778E-4,
+            6.98793669997260967291E-6, 8.11789239554389293311E-8, 3.41551784765923618484E-10,
+        };
+
+        constexpr double airy_AGD[10] = {
+            /*  1.00000000000000000000E0, */
+            9.30892908077441974853E0,  1.98352928718312140417E1,  1.55646628932864612953E1,  5.47686069422975497931E0,
+            9.54293611618961883998E-1, 8.64580826352392193095E-2, 4.12656523824222607191E-3, 1.01259085116509135510E-4,
+            1.17166733214413521882E-6, 4.91834570062930015649E-9,
+        };
+
+        constexpr double airy_APFN[9] = {
+            1.85365624022535566142E-1, 8.86712188052584095637E-1, 9.87391981747398547272E-1,
+            4.01241082318003734092E-1, 7.10304926289631174579E-2, 5.90618657995661810071E-3,
+            2.33051409401776799569E-4, 4.08718778289035454598E-6, 2.48379932900442457853E-8,
+        };
+
+        constexpr double airy_APFD[9] = {
+            /*  1.00000000000000000000E0, */
+            1.47345854687502542552E1,  3.75423933435489594466E1,  3.14657751203046424330E1,
+            1.09969125207298778536E1,  1.78885054766999417817E0,  1.41733275753662636873E-1,
+            5.44066067017226003627E-3, 9.39421290654511171663E-5, 5.65978713036027009243E-7,
+        };
+
+        constexpr double airy_APGN[11] = {
+            -3.55615429033082288335E-2, -6.37311518129435504426E-1,  -1.70856738884312371053E0,
+            -1.50221872117316635393E0,  -5.63606665822102676611E-1,  -1.02101031120216891789E-1,
+            -9.48396695961445269093E-3, -4.60325307486780994357E-4,  -1.14300836484517375919E-5,
+            -1.33415518685547420648E-7, -5.63803833958893494476E-10,
+        };
+
+        constexpr double airy_APGD[11] = {
+            /*  1.00000000000000000000E0, */
+            9.85865801696130355144E0,  2.16401867356585941885E1,  1.73130776389749389525E1,  6.17872175280828766327E0,
+            1.08848694396321495475E0,  9.95005543440888479402E-2, 4.78468199683886610842E-3, 1.18159633322838625562E-4,
+            1.37480673554219441465E-6, 5.79912514929147598821E-9,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline int airy(double x, double *ai, double *aip, double *bi, double *bip) {
+        double z, zz, t, f, g, uf, ug, k, zeta, theta;
+        int domflg;
+
+        domflg = 0;
+        if (x > detail::MAXAIRY) {
+            *ai = 0;
+            *aip = 0;
+            *bi = std::numeric_limits::infinity();
+            *bip = std::numeric_limits::infinity();
+            return (-1);
+        }
+
+        if (x < -2.09) {
+            domflg = 15;
+            t = std::sqrt(-x);
+            zeta = -2.0 * x * t / 3.0;
+            t = std::sqrt(t);
+            k = detail::SQRT1OPI / t;
+            z = 1.0 / zeta;
+            zz = z * z;
+            uf = 1.0 + zz * polevl(zz, detail::airy_AFN, 8) / p1evl(zz, detail::airy_AFD, 9);
+            ug = z * polevl(zz, detail::airy_AGN, 10) / p1evl(zz, detail::airy_AGD, 10);
+            theta = zeta + 0.25 * M_PI;
+            f = std::sin(theta);
+            g = std::cos(theta);
+            *ai = k * (f * uf - g * ug);
+            *bi = k * (g * uf + f * ug);
+            uf = 1.0 + zz * polevl(zz, detail::airy_APFN, 8) / p1evl(zz, detail::airy_APFD, 9);
+            ug = z * polevl(zz, detail::airy_APGN, 10) / p1evl(zz, detail::airy_APGD, 10);
+            k = detail::SQRT1OPI * t;
+            *aip = -k * (g * uf + f * ug);
+            *bip = k * (f * uf - g * ug);
+            return (0);
+        }
+
+        if (x >= 2.09) { /* cbrt(9) */
+            domflg = 5;
+            t = std::sqrt(x);
+            zeta = 2.0 * x * t / 3.0;
+            g = std::exp(zeta);
+            t = std::sqrt(t);
+            k = 2.0 * t * g;
+            z = 1.0 / zeta;
+            f = polevl(z, detail::airy_AN, 7) / polevl(z, detail::airy_AD, 7);
+            *ai = detail::SQRT1OPI * f / k;
+            k = -0.5 * detail::SQRT1OPI * t / g;
+            f = polevl(z, detail::airy_APN, 7) / polevl(z, detail::airy_APD, 7);
+            *aip = f * k;
+
+            if (x > 8.3203353) { /* zeta > 16 */
+                f = z * polevl(z, detail::airy_BN16, 4) / p1evl(z, detail::airy_BD16, 5);
+                k = detail::SQRT1OPI * g;
+                *bi = k * (1.0 + f) / t;
+                f = z * polevl(z, detail::airy_BPPN, 4) / p1evl(z, detail::airy_BPPD, 5);
+                *bip = k * t * (1.0 + f);
+                return (0);
+            }
+        }
+
+        f = 1.0;
+        g = x;
+        t = 1.0;
+        uf = 1.0;
+        ug = x;
+        k = 1.0;
+        z = x * x * x;
+        while (t > detail::MACHEP) {
+            uf *= z;
+            k += 1.0;
+            uf /= k;
+            ug *= z;
+            k += 1.0;
+            ug /= k;
+            uf /= k;
+            f += uf;
+            k += 1.0;
+            ug /= k;
+            g += ug;
+            t = std::abs(uf / f);
+        }
+        uf = detail::airy_c1 * f;
+        ug = detail::airy_c2 * g;
+        if ((domflg & 1) == 0) {
+            *ai = uf - ug;
+        }
+        if ((domflg & 2) == 0) {
+            *bi = detail::SQRT3 * (uf + ug);
+        }
+
+        /* the deriviative of ai */
+        k = 4.0;
+        uf = x * x / 2.0;
+        ug = z / 3.0;
+        f = uf;
+        g = 1.0 + ug;
+        uf /= 3.0;
+        t = 1.0;
+
+        while (t > detail::MACHEP) {
+            uf *= z;
+            ug /= k;
+            k += 1.0;
+            ug *= z;
+            uf /= k;
+            f += uf;
+            k += 1.0;
+            ug /= k;
+            uf /= k;
+            g += ug;
+            k += 1.0;
+            t = std::abs(ug / g);
+        }
+
+        uf = detail::airy_c1 * f;
+        ug = detail::airy_c2 * g;
+        if ((domflg & 4) == 0) {
+            *aip = uf - ug;
+        }
+        if ((domflg & 8) == 0) {
+            *bip = detail::SQRT3 * (uf + ug);
+        };
+        return (0);
+    }
+
+    inline int airy(float xf, float *aif, float *aipf, float *bif, float *bipf) {
+        double ai;
+        double aip;
+        double bi;
+        double bip;
+        int res = cephes::airy(xf, &ai, &aip, &bi, &bip);
+
+        *aif = ai;
+        *aipf = aip;
+        *bif = bi;
+        *bipf = bip;
+        return res;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h
new file mode 100644
index 0000000000000000000000000000000000000000..d113b8b7d0f4ae4e7ad9da2faf66d3ab7406d736
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h
@@ -0,0 +1,51 @@
+/* Translated into C++ by SciPy developers in 2024.
+ *
+ * This was not part of the original cephes library.
+ */
+#pragma once
+
+#include "../config.h"
+#include "gamma.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+
+        constexpr double besselpoly_EPS = 1.0e-17;
+    }
+
+    XSF_HOST_DEVICE inline double besselpoly(double a, double lambda, double nu) {
+
+        int m, factor = 0;
+        double Sm, relerr, Sol;
+        double sum = 0.0;
+
+        /* Special handling for a = 0.0 */
+        if (a == 0.0) {
+            if (nu == 0.0) {
+                return 1.0 / (lambda + 1);
+            } else {
+                return 0.0;
+            }
+        }
+        /* Special handling for negative and integer nu */
+        if ((nu < 0) && (std::floor(nu) == nu)) {
+            nu = -nu;
+            factor = static_cast(nu) % 2;
+        }
+        Sm = std::exp(nu * std::log(a)) / (Gamma(nu + 1) * (lambda + nu + 1));
+        m = 0;
+        do {
+            sum += Sm;
+            Sol = Sm;
+            Sm *= -a * a * (lambda + nu + 1 + 2 * m) / ((nu + m + 1) * (m + 1) * (lambda + nu + 1 + 2 * m + 2));
+            m++;
+            relerr = std::abs((Sm - Sol) / Sm);
+        } while (relerr > detail::besselpoly_EPS && m < 1000);
+        if (!factor)
+            return sum;
+        else
+            return -sum;
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h
new file mode 100644
index 0000000000000000000000000000000000000000..437262793e8f94b229671978b23a638820ff1290
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h
@@ -0,0 +1,257 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     beta.c
+ *
+ *     Beta function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, y, beta();
+ *
+ * y = beta( a, b );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *                   -     -
+ *                  | (a) | (b)
+ * beta( a, b )  =  -----------.
+ *                     -
+ *                    | (a+b)
+ *
+ * For large arguments the logarithm of the function is
+ * evaluated using lgam(), then exponentiated.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,30       30000       8.1e-14     1.1e-14
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * beta overflow    log(beta) > MAXLOG       0.0
+ *                  a or b <0 integer        0.0
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE double beta(double, double);
+    XSF_HOST_DEVICE double lbeta(double, double);
+
+    namespace detail {
+        constexpr double beta_ASYMP_FACTOR = 1e6;
+
+        /*
+         * Asymptotic expansion for  ln(|B(a, b)|) for a > ASYMP_FACTOR*max(|b|, 1).
+         */
+        XSF_HOST_DEVICE inline double lbeta_asymp(double a, double b, int *sgn) {
+            double r = lgam_sgn(b, sgn);
+            r -= b * std::log(a);
+
+            r += b * (1 - b) / (2 * a);
+            r += b * (1 - b) * (1 - 2 * b) / (12 * a * a);
+            r += -b * b * (1 - b) * (1 - b) / (12 * a * a * a);
+
+            return r;
+        }
+
+        /*
+         * Special case for a negative integer argument
+         */
+
+        XSF_HOST_DEVICE inline double beta_negint(int a, double b) {
+            int sgn;
+            if (b == static_cast(b) && 1 - a - b > 0) {
+                sgn = (static_cast(b) % 2 == 0) ? 1 : -1;
+                return sgn * xsf::cephes::beta(1 - a - b, b);
+            } else {
+                set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+
+        XSF_HOST_DEVICE inline double lbeta_negint(int a, double b) {
+            double r;
+            if (b == static_cast(b) && 1 - a - b > 0) {
+                r = xsf::cephes::lbeta(1 - a - b, b);
+                return r;
+            } else {
+                set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double beta(double a, double b) {
+        double y;
+        int sign = 1;
+
+        if (a <= 0.0) {
+            if (a == std::floor(a)) {
+                if (a == static_cast(a)) {
+                    return detail::beta_negint(static_cast(a), b);
+                } else {
+                    goto overflow;
+                }
+            }
+        }
+
+        if (b <= 0.0) {
+            if (b == std::floor(b)) {
+                if (b == static_cast(b)) {
+                    return detail::beta_negint(static_cast(b), a);
+                } else {
+                    goto overflow;
+                }
+            }
+        }
+
+        if (std::abs(a) < std::abs(b)) {
+            y = a;
+            a = b;
+            b = y;
+        }
+
+        if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) {
+            /* Avoid loss of precision in lgam(a + b) - lgam(a) */
+            y = detail::lbeta_asymp(a, b, &sign);
+            return sign * std::exp(y);
+        }
+
+        y = a + b;
+        if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) {
+            int sgngam;
+            y = detail::lgam_sgn(y, &sgngam);
+            sign *= sgngam; /* keep track of the sign */
+            y = detail::lgam_sgn(b, &sgngam) - y;
+            sign *= sgngam;
+            y = detail::lgam_sgn(a, &sgngam) + y;
+            sign *= sgngam;
+            if (y > detail::MAXLOG) {
+                goto overflow;
+            }
+            return (sign * std::exp(y));
+        }
+
+        y = rgamma(y);
+        a = Gamma(a);
+        b = Gamma(b);
+        if (std::isinf(y)) {
+            goto overflow;
+	}
+
+        if (std::abs(std::abs(a*y) - 1.0) > std::abs(std::abs(b*y) - 1.0)) {
+            y = b * y;
+            y *= a;
+        } else {
+            y = a * y;
+            y *= b;
+        }
+
+        return (y);
+
+    overflow:
+        set_error("beta", SF_ERROR_OVERFLOW, NULL);
+        return (sign * std::numeric_limits::infinity());
+    }
+
+    /* Natural log of |beta|. */
+
+    XSF_HOST_DEVICE inline double lbeta(double a, double b) {
+        double y;
+        int sign;
+
+        sign = 1;
+
+        if (a <= 0.0) {
+            if (a == std::floor(a)) {
+                if (a == static_cast(a)) {
+                    return detail::lbeta_negint(static_cast(a), b);
+                } else {
+                    goto over;
+                }
+            }
+        }
+
+        if (b <= 0.0) {
+            if (b == std::floor(b)) {
+                if (b == static_cast(b)) {
+                    return detail::lbeta_negint(static_cast(b), a);
+                } else {
+                    goto over;
+                }
+            }
+        }
+
+        if (std::abs(a) < std::abs(b)) {
+            y = a;
+            a = b;
+            b = y;
+        }
+
+        if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) {
+            /* Avoid loss of precision in lgam(a + b) - lgam(a) */
+            y = detail::lbeta_asymp(a, b, &sign);
+            return y;
+        }
+
+        y = a + b;
+        if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) {
+            int sgngam;
+            y = detail::lgam_sgn(y, &sgngam);
+            sign *= sgngam; /* keep track of the sign */
+            y = detail::lgam_sgn(b, &sgngam) - y;
+            sign *= sgngam;
+            y = detail::lgam_sgn(a, &sgngam) + y;
+            sign *= sgngam;
+            return (y);
+        }
+
+        y = rgamma(y);
+        a = Gamma(a);
+        b = Gamma(b);
+        if (std::isinf(y)) {
+        over:
+            set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+            return (sign * std::numeric_limits::infinity());
+        }
+
+        if (std::abs(std::abs(a*y) - 1.0) > std::abs(std::abs(b*y) - 1.0)) {
+            y = b * y;
+            y *= a;
+        } else {
+            y = a * y;
+            y *= b;
+        }
+
+        if (y < 0) {
+            y = -y;
+        }
+
+        return (std::log(y));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h
new file mode 100644
index 0000000000000000000000000000000000000000..3e9fbd4eab45b24f1caa8b509c9d1d3c536867fe
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h
@@ -0,0 +1,131 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     cbrt.c
+ *
+ *     Cube root
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cbrt();
+ *
+ * y = cbrt( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the cube root of the argument, which may be negative.
+ *
+ * Range reduction involves determining the power of 2 of
+ * the argument.  A polynomial of degree 2 applied to the
+ * mantissa, and multiplication by the cube root of 1, 2, or 4
+ * approximates the root to within about 0.1%.  Then Newton's
+ * iteration is used three times to converge to an accurate
+ * result.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,1e308     30000      1.5e-16     5.0e-17
+ *
+ */
+/*							cbrt.c  */
+
+/*
+ * Cephes Math Library Release 2.2:  January, 1991
+ * Copyright 1984, 1991 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double CBRT2 = 1.2599210498948731647672;
+        constexpr double CBRT4 = 1.5874010519681994747517;
+        constexpr double CBRT2I = 0.79370052598409973737585;
+        constexpr double CBRT4I = 0.62996052494743658238361;
+
+        XSF_HOST_DEVICE inline double cbrt(double x) {
+            int e, rem, sign;
+            double z;
+
+            if (!std::isfinite(x)) {
+                return x;
+            }
+            if (x == 0) {
+                return (x);
+            }
+            if (x > 0) {
+                sign = 1;
+            } else {
+                sign = -1;
+                x = -x;
+            }
+
+            z = x;
+            /* extract power of 2, leaving
+             * mantissa between 0.5 and 1
+             */
+            x = std::frexp(x, &e);
+
+            /* Approximate cube root of number between .5 and 1,
+             * peak relative error = 9.2e-6
+             */
+            x = (((-1.3466110473359520655053e-1 * x + 5.4664601366395524503440e-1) * x - 9.5438224771509446525043e-1) *
+                     x +
+                 1.1399983354717293273738e0) *
+                    x +
+                4.0238979564544752126924e-1;
+
+            /* exponent divided by 3 */
+            if (e >= 0) {
+                rem = e;
+                e /= 3;
+                rem -= 3 * e;
+                if (rem == 1) {
+                    x *= CBRT2;
+                } else if (rem == 2) {
+                    x *= CBRT4;
+                }
+            }
+            /* argument less than 1 */
+            else {
+                e = -e;
+                rem = e;
+                e /= 3;
+                rem -= 3 * e;
+                if (rem == 1) {
+                    x *= CBRT2I;
+                } else if (rem == 2) {
+                    x *= CBRT4I;
+                }
+                e = -e;
+            }
+
+            /* multiply by power of 2 */
+            x = std::ldexp(x, e);
+
+            /* Newton iteration */
+            x -= (x - (z / (x * x))) * 0.33333333333333333333;
+            x -= (x - (z / (x * x))) * 0.33333333333333333333;
+
+            if (sign < 0)
+                x = -x;
+            return (x);
+        }
+    } // namespace detail
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h
new file mode 100644
index 0000000000000000000000000000000000000000..caaa74fc7b81015784608cc38aed5987ca145526
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h
@@ -0,0 +1,85 @@
+/*                                                     chbevl.c
+ *
+ *     Evaluate Chebyshev series
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int N;
+ * double x, y, coef[N], chebevl();
+ *
+ * y = chbevl( x, coef, N );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the series
+ *
+ *        N-1
+ *         - '
+ *  y  =   >   coef[i] T (x/2)
+ *         -            i
+ *        i=0
+ *
+ * of Chebyshev polynomials Ti at argument x/2.
+ *
+ * Coefficients are stored in reverse order, i.e. the zero
+ * order term is last in the array.  Note N is the number of
+ * coefficients, not the order.
+ *
+ * If coefficients are for the interval a to b, x must
+ * have been transformed to x -> 2(2x - b - a)/(b-a) before
+ * entering the routine.  This maps x from (a, b) to (-1, 1),
+ * over which the Chebyshev polynomials are defined.
+ *
+ * If the coefficients are for the inverted interval, in
+ * which (a, b) is mapped to (1/b, 1/a), the transformation
+ * required is x -> 2(2ab/x - b - a)/(b-a).  If b is infinity,
+ * this becomes x -> 4a/x - 1.
+ *
+ *
+ *
+ * SPEED:
+ *
+ * Taking advantage of the recurrence properties of the
+ * Chebyshev polynomials, the routine requires one more
+ * addition per loop than evaluating a nested polynomial of
+ * the same degree.
+ *
+ */
+/*							chbevl.c	*/
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE double chbevl(double x, const double array[], int n) {
+        double b0, b1, b2;
+        const double *p;
+        int i;
+
+        p = array;
+        b0 = *p++;
+        b1 = 0.0;
+        i = n - 1;
+
+        do {
+            b2 = b1;
+            b1 = b0;
+            b0 = x * b1 - b2 + *p++;
+        } while (--i);
+
+        return (0.5 * (b0 - b2));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h
new file mode 100644
index 0000000000000000000000000000000000000000..0a97def6d00baa18eaffaca73c92d7b6dd2b5e32
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h
@@ -0,0 +1,193 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     chdtr.c
+ *
+ *     Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double df, x, y, chdtr();
+ *
+ * y = chdtr( df, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the left hand tail (from 0 to x)
+ * of the Chi square probability density function with
+ * v degrees of freedom.
+ *
+ *
+ *                                  inf.
+ *                                    -
+ *                        1          | |  v/2-1  -t/2
+ *  P( x | v )   =   -----------     |   t      e     dt
+ *                    v/2  -       | |
+ *                   2    | (v/2)   -
+ *                                   x
+ *
+ * where x is the Chi-square variable.
+ *
+ * The incomplete Gamma integral is used, according to the
+ * formula
+ *
+ *     y = chdtr( v, x ) = igam( v/2.0, x/2.0 ).
+ *
+ *
+ * The arguments must both be positive.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igam().
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtr domain   x < 0 or v < 1        0.0
+ */
+/*							chdtrc()
+ *
+ *	Complemented Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, chdtrc();
+ *
+ * y = chdtrc( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the right hand tail (from x to
+ * infinity) of the Chi square probability density function
+ * with v degrees of freedom:
+ *
+ *
+ *                                  inf.
+ *                                    -
+ *                        1          | |  v/2-1  -t/2
+ *  P( x | v )   =   -----------     |   t      e     dt
+ *                    v/2  -       | |
+ *                   2    | (v/2)   -
+ *                                   x
+ *
+ * where x is the Chi-square variable.
+ *
+ * The incomplete Gamma integral is used, according to the
+ * formula
+ *
+ *	y = chdtr( v, x ) = igamc( v/2.0, x/2.0 ).
+ *
+ *
+ * The arguments must both be positive.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igamc().
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtrc domain  x < 0 or v < 1        0.0
+ */
+/*							chdtri()
+ *
+ *	Inverse of complemented Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double df, x, y, chdtri();
+ *
+ * x = chdtri( df, y );
+ *
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Finds the Chi-square argument x such that the integral
+ * from x to infinity of the Chi-square density is equal
+ * to the given cumulative probability y.
+ *
+ * This is accomplished using the inverse Gamma integral
+ * function and the relation
+ *
+ *    x/2 = igamci( df/2, y );
+ *
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igami.c.
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtri domain   y < 0 or y > 1        0.0
+ *                     v < 1
+ *
+ */
+
+/*                                                             chdtr() */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "igam.h"
+#include "igami.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE inline double chdtrc(double df, double x) {
+
+        if (x < 0.0)
+            return 1.0; /* modified by T. Oliphant */
+        return (igamc(df / 2.0, x / 2.0));
+    }
+
+    XSF_HOST_DEVICE inline double chdtr(double df, double x) {
+
+        if ((x < 0.0)) { /* || (df < 1.0) ) */
+            set_error("chdtr", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+        return (igam(df / 2.0, x / 2.0));
+    }
+
+    XSF_HOST_DEVICE double chdtri(double df, double y) {
+        double x;
+
+        if ((y < 0.0) || (y > 1.0)) { /* || (df < 1.0) ) */
+            set_error("chdtri", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        x = igamci(0.5 * df, y);
+        return (2.0 * x);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h
new file mode 100644
index 0000000000000000000000000000000000000000..d7b162c5efc8e11f407c6108d55c117820e9e76d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h
@@ -0,0 +1,87 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ *
+ * Since we support only IEEE-754 floating point numbers, conditional logic
+ * supporting other arithmetic types has been removed.
+ */
+
+/*
+ *
+ *
+ *                                                   const.c
+ *
+ *     Globally declared constants
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * extern double nameofconstant;
+ *
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * This file contains a number of mathematical constants and
+ * also some needed size parameters of the computer arithmetic.
+ * The values are supplied as arrays of hexadecimal integers
+ * for IEEE arithmetic, and in a normal decimal scientific notation for
+ * other machines.  The particular notation used is determined
+ * by a symbol (IBMPC, or UNK) defined in the include file
+ * mconf.h.
+ *
+ * The default size parameters are as follows.
+ *
+ * For UNK mode:
+ * MACHEP =  1.38777878078144567553E-17       2**-56
+ * MAXLOG =  8.8029691931113054295988E1       log(2**127)
+ * MINLOG = -8.872283911167299960540E1        log(2**-128)
+ *
+ * For IEEE arithmetic (IBMPC):
+ * MACHEP =  1.11022302462515654042E-16       2**-53
+ * MAXLOG =  7.09782712893383996843E2         log(2**1024)
+ * MINLOG = -7.08396418532264106224E2         log(2**-1022)
+ *
+ * The global symbols for mathematical constants are
+ * SQ2OPI =  7.9788456080286535587989E-1      sqrt( 2/pi )
+ * LOGSQ2 =  3.46573590279972654709E-1        log(2)/2
+ * THPIO4 =  2.35619449019234492885           3*pi/4
+ *
+ * These lists are subject to change.
+ */
+/*                                                     const.c */
+
+/*
+ * Cephes Math Library Release 2.3:  March, 1995
+ * Copyright 1984, 1995 by Stephen L. Moshier
+ */
+#pragma once
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr std::uint64_t MAXITER = 500;
+        constexpr double MACHEP = 1.11022302462515654042E-16;    // 2**-53
+        constexpr double MAXLOG = 7.09782712893383996732E2;      // log(DBL_MAX)
+        constexpr double MINLOG = -7.451332191019412076235E2;    // log 2**-1022
+        constexpr double SQRT1OPI = 5.64189583547756286948E-1;   // sqrt( 1/pi)
+        constexpr double SQRT2OPI = 7.9788456080286535587989E-1; // sqrt( 2/pi )
+        constexpr double SQRT2PI = 0.79788456080286535587989;    // sqrt(2pi)
+        constexpr double LOGSQ2 = 3.46573590279972654709E-1;     // log(2)/2
+        constexpr double THPIO4 = 2.35619449019234492885;        // 3*pi/4
+        constexpr double SQRT3 = 1.732050807568877293527;        // sqrt(3)
+        constexpr double PI180 = 1.74532925199432957692E-2;      // pi/180
+        constexpr double SQRTPI = 2.50662827463100050242E0;      // sqrt(pi)
+        constexpr double LOGPI = 1.14472988584940017414;         // log(pi)
+        constexpr double MAXGAM = 171.624376956302725;
+        constexpr double LOGSQRT2PI = 0.9189385332046727; // log(sqrt(pi))
+
+        // Following two added by SciPy developers.
+        // Euler's constant
+        constexpr double SCIPY_EULER = 0.577215664901532860606512090082402431;
+        // e as long double
+        constexpr long double SCIPY_El = 2.718281828459045235360287471352662498L;
+    } // namespace detail
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h
new file mode 100644
index 0000000000000000000000000000000000000000..a455599b4a95b3c69d23df188669e84deac4e31c
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h
@@ -0,0 +1,293 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellie.c
+ *
+ *     Incomplete elliptic integral of the second kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double phi, m, y, ellie();
+ *
+ * y = ellie( phi, m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *                 phi
+ *                  -
+ *                 | |
+ *                 |                   2
+ * E(phi_\m)  =    |    sqrt( 1 - m sin t ) dt
+ *                 |
+ *               | |
+ *                -
+ *                 0
+ *
+ * of amplitude phi and modulus m, using the arithmetic -
+ * geometric mean algorithm.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random arguments with phi in [-10, 10] and m in
+ * [0, 1].
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -10,10      150000       3.3e-15     1.4e-16
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987, 1993 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+/* Copyright 2014, Eric W. Moore */
+
+/*     Incomplete elliptic integral of second kind     */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "ellpe.h"
+#include "ellpk.h"
+#include "unity.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+
+        /* To calculate legendre's incomplete elliptical integral of the second kind for
+         * negative m, we use a power series in phi for small m*phi*phi, an asymptotic
+         * series in m for large m*phi*phi* and the relation to Carlson's symmetric
+         * integrals, R_F(x,y,z) and R_D(x,y,z).
+         *
+         * E(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0)
+         *             - m * sin(phi)^3 * R_D(cos(phi)^2, 1 - m * sin(phi)^2, 1.0) / 3
+         *
+         *           = R_F(c-1, c-m, c) - m * R_D(c-1, c-m, c) / 3
+         *
+         * where c = csc(phi)^2. We use the second form of this for (approximately)
+         * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we
+         * use the first form, accounting for the smallness of phi.
+         *
+         * The algorithm used is described in Carlson, B. C. Numerical computation of
+         * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227
+         * Most variable names reflect Carlson's usage.
+         *
+         * In this routine, we assume m < 0 and  0 > phi > pi/2.
+         */
+        XSF_HOST_DEVICE inline double ellie_neg_m(double phi, double m) {
+            double x, y, z, x1, y1, z1, ret, Q;
+            double A0f, Af, Xf, Yf, Zf, E2f, E3f, scalef;
+            double A0d, Ad, seriesn, seriesd, Xd, Yd, Zd, E2d, E3d, E4d, E5d, scaled;
+            int n = 0;
+            double mpp = (m * phi) * phi;
+
+            if (-mpp < 1e-6 && phi < -m) {
+                return phi + (mpp * phi * phi / 30.0 - mpp * mpp / 40.0 - mpp / 6.0) * phi;
+            }
+
+            if (-mpp > 1e6) {
+                double sm = std::sqrt(-m);
+                double sp = std::sin(phi);
+                double cp = std::cos(phi);
+
+                double a = -cosm1(phi);
+                double b1 = std::log(4 * sp * sm / (1 + cp));
+                double b = -(0.5 + b1) / 2.0 / m;
+                double c = (0.75 + cp / sp / sp - b1) / 16.0 / m / m;
+                return (a + b + c) * sm;
+            }
+
+            if (phi > 1e-153 && m > -1e200) {
+                double s = std::sin(phi);
+                double csc2 = 1.0 / s / s;
+                scalef = 1.0;
+                scaled = m / 3.0;
+                x = 1.0 / std::tan(phi) / std::tan(phi);
+                y = csc2 - m;
+                z = csc2;
+            } else {
+                scalef = phi;
+                scaled = mpp * phi / 3.0;
+                x = 1.0;
+                y = 1 - mpp;
+                z = 1.0;
+            }
+
+            if (x == y && x == z) {
+                return (scalef + scaled / x) / std::sqrt(x);
+            }
+
+            A0f = (x + y + z) / 3.0;
+            Af = A0f;
+            A0d = (x + y + 3.0 * z) / 5.0;
+            Ad = A0d;
+            x1 = x;
+            y1 = y;
+            z1 = z;
+            seriesd = 0.0;
+            seriesn = 1.0;
+            /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps,
+             * it is ~338.38. */
+
+            /* N.B. This will evaluate its arguments multiple times. */
+            Q = 400.0 * std::fmax(std::abs(A0f - x), std::fmax(std::abs(A0f - y), std::abs(A0f - z)));
+
+            while (Q > std::abs(Af) && Q > std::abs(Ad) && n <= 100) {
+                double sx = std::sqrt(x1);
+                double sy = std::sqrt(y1);
+                double sz = std::sqrt(z1);
+                double lam = sx * sy + sx * sz + sy * sz;
+                seriesd += seriesn / (sz * (z1 + lam));
+                x1 = (x1 + lam) / 4.0;
+                y1 = (y1 + lam) / 4.0;
+                z1 = (z1 + lam) / 4.0;
+                Af = (x1 + y1 + z1) / 3.0;
+                Ad = (Ad + lam) / 4.0;
+                n += 1;
+                Q /= 4.0;
+                seriesn /= 4.0;
+            }
+
+            Xf = (A0f - x) / Af / (1 << 2 * n);
+            Yf = (A0f - y) / Af / (1 << 2 * n);
+            Zf = -(Xf + Yf);
+
+            E2f = Xf * Yf - Zf * Zf;
+            E3f = Xf * Yf * Zf;
+
+            ret = scalef * (1.0 - E2f / 10.0 + E3f / 14.0 + E2f * E2f / 24.0 - 3.0 * E2f * E3f / 44.0) / sqrt(Af);
+
+            Xd = (A0d - x) / Ad / (1 << 2 * n);
+            Yd = (A0d - y) / Ad / (1 << 2 * n);
+            Zd = -(Xd + Yd) / 3.0;
+
+            E2d = Xd * Yd - 6.0 * Zd * Zd;
+            E3d = (3 * Xd * Yd - 8.0 * Zd * Zd) * Zd;
+            E4d = 3.0 * (Xd * Yd - Zd * Zd) * Zd * Zd;
+            E5d = Xd * Yd * Zd * Zd * Zd;
+
+            ret -= scaled *
+                   (1.0 - 3.0 * E2d / 14.0 + E3d / 6.0 + 9.0 * E2d * E2d / 88.0 - 3.0 * E4d / 22.0 -
+                    9.0 * E2d * E3d / 52.0 + 3.0 * E5d / 26.0) /
+                   (1 << 2 * n) / Ad / sqrt(Ad);
+            ret -= 3.0 * scaled * seriesd;
+            return ret;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellie(double phi, double m) {
+        double a, b, c, e, temp;
+        double lphi, t, E, denom, npio2;
+        int d, mod, sign;
+
+        if (std::isnan(phi) || std::isnan(m))
+            return std::numeric_limits::quiet_NaN();
+        if (m > 1.0)
+            return std::numeric_limits::quiet_NaN();
+        ;
+        if (std::isinf(phi))
+            return phi;
+        if (std::isinf(m))
+            return -m;
+        if (m == 0.0)
+            return (phi);
+        lphi = phi;
+        npio2 = std::floor(lphi / M_PI_2);
+        if (std::fmod(std::abs(npio2), 2.0) == 1.0)
+            npio2 += 1;
+        lphi = lphi - npio2 * M_PI_2;
+        if (lphi < 0.0) {
+            lphi = -lphi;
+            sign = -1;
+        } else {
+            sign = 1;
+        }
+        a = 1.0 - m;
+        E = ellpe(m);
+        if (a == 0.0) {
+            temp = std::sin(lphi);
+            goto done;
+        }
+        if (a > 1.0) {
+            temp = detail::ellie_neg_m(lphi, m);
+            goto done;
+        }
+
+        if (lphi < 0.135) {
+            double m11 = (((((-7.0 / 2816.0) * m + (5.0 / 1056.0)) * m - (7.0 / 2640.0)) * m + (17.0 / 41580.0)) * m -
+                          (1.0 / 155925.0)) *
+                         m;
+            double m9 = ((((-5.0 / 1152.0) * m + (1.0 / 144.0)) * m - (1.0 / 360.0)) * m + (1.0 / 5670.0)) * m;
+            double m7 = ((-m / 112.0 + (1.0 / 84.0)) * m - (1.0 / 315.0)) * m;
+            double m5 = (-m / 40.0 + (1.0 / 30)) * m;
+            double m3 = -m / 6.0;
+            double p2 = lphi * lphi;
+
+            temp = ((((m11 * p2 + m9) * p2 + m7) * p2 + m5) * p2 + m3) * p2 * lphi + lphi;
+            goto done;
+        }
+        t = std::tan(lphi);
+        b = std::sqrt(a);
+        /* Thanks to Brian Fitzgerald 
+         * for pointing out an instability near odd multiples of pi/2.  */
+        if (std::abs(t) > 10.0) {
+            /* Transform the amplitude */
+            e = 1.0 / (b * t);
+            /* ... but avoid multiple recursions.  */
+            if (std::abs(e) < 10.0) {
+                e = std::atan(e);
+                temp = E + m * std::sin(lphi) * std::sin(e) - ellie(e, m);
+                goto done;
+            }
+        }
+        c = std::sqrt(m);
+        a = 1.0;
+        d = 1;
+        e = 0.0;
+        mod = 0;
+
+        while (std::abs(c / a) > detail::MACHEP) {
+            temp = b / a;
+            lphi = lphi + atan(t * temp) + mod * M_PI;
+            denom = 1 - temp * t * t;
+            if (std::abs(denom) > 10 * detail::MACHEP) {
+                t = t * (1.0 + temp) / denom;
+                mod = (lphi + M_PI_2) / M_PI;
+            } else {
+                t = std::tan(lphi);
+                mod = static_cast(std::floor((lphi - std::atan(t)) / M_PI));
+            }
+            c = (a - b) / 2.0;
+            temp = std::sqrt(a * b);
+            a = (a + b) / 2.0;
+            b = temp;
+            d += d;
+            e += c * std::sin(lphi);
+        }
+
+        temp = E / ellpk(1.0 - m);
+        temp *= (std::atan(t) + mod * M_PI) / (d * a);
+        temp += e;
+
+    done:
+
+        if (sign < 0)
+            temp = -temp;
+        temp += npio2 * E;
+        return (temp);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h
new file mode 100644
index 0000000000000000000000000000000000000000..c05b3ec76c2e9a3acbc947842e0a849f5ba837e0
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h
@@ -0,0 +1,251 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellik.c
+ *
+ *     Incomplete elliptic integral of the first kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double phi, m, y, ellik();
+ *
+ * y = ellik( phi, m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *
+ *                phi
+ *                 -
+ *                | |
+ *                |           dt
+ * F(phi | m) =   |    ------------------
+ *                |                   2
+ *              | |    sqrt( 1 - m sin t )
+ *               -
+ *                0
+ *
+ * of amplitude phi and modulus m, using the arithmetic -
+ * geometric mean algorithm.
+ *
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random points with m in [0, 1] and phi as indicated.
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -10,10       200000      7.4e-16     1.0e-16
+ *
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+/* Copyright 2014, Eric W. Moore */
+
+/*     Incomplete elliptic integral of first kind      */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "ellpk.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* To calculate legendre's incomplete elliptical integral of the first kind for
+         * negative m, we use a power series in phi for small m*phi*phi, an asymptotic
+         * series in m for large m*phi*phi* and the relation to Carlson's symmetric
+         * integral of the first kind.
+         *
+         * F(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0)
+         *           = R_F(c-1, c-m, c)
+         *
+         * where c = csc(phi)^2. We use the second form of this for (approximately)
+         * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we
+         * use the first form, accounting for the smallness of phi.
+         *
+         * The algorithm used is described in Carlson, B. C. Numerical computation of
+         * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227
+         * Most variable names reflect Carlson's usage.
+         *
+         * In this routine, we assume m < 0 and  0 > phi > pi/2.
+         */
+        XSF_HOST_DEVICE inline double ellik_neg_m(double phi, double m) {
+            double x, y, z, x1, y1, z1, A0, A, Q, X, Y, Z, E2, E3, scale;
+            int n = 0;
+            double mpp = (m * phi) * phi;
+
+            if (-mpp < 1e-6 && phi < -m) {
+                return phi + (-mpp * phi * phi / 30.0 + 3.0 * mpp * mpp / 40.0 + mpp / 6.0) * phi;
+            }
+
+            if (-mpp > 4e7) {
+                double sm = std::sqrt(-m);
+                double sp = std::sin(phi);
+                double cp = std::cos(phi);
+
+                double a = std::log(4 * sp * sm / (1 + cp));
+                double b = -(1 + cp / sp / sp - a) / 4 / m;
+                return (a + b) / sm;
+            }
+
+            if (phi > 1e-153 && m > -1e305) {
+                double s = std::sin(phi);
+                double csc2 = 1.0 / (s * s);
+                scale = 1.0;
+                x = 1.0 / (std::tan(phi) * std::tan(phi));
+                y = csc2 - m;
+                z = csc2;
+            } else {
+                scale = phi;
+                x = 1.0;
+                y = 1 - m * scale * scale;
+                z = 1.0;
+            }
+
+            if (x == y && x == z) {
+                return scale / std::sqrt(x);
+            }
+
+            A0 = (x + y + z) / 3.0;
+            A = A0;
+            x1 = x;
+            y1 = y;
+            z1 = z;
+            /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps,
+             * it is ~338.38. */
+            Q = 400.0 * std::fmax(std::abs(A0 - x), std::fmax(std::abs(A0 - y), std::abs(A0 - z)));
+
+            while (Q > std::abs(A) && n <= 100) {
+                double sx = std::sqrt(x1);
+                double sy = std::sqrt(y1);
+                double sz = std::sqrt(z1);
+                double lam = sx * sy + sx * sz + sy * sz;
+                x1 = (x1 + lam) / 4.0;
+                y1 = (y1 + lam) / 4.0;
+                z1 = (z1 + lam) / 4.0;
+                A = (x1 + y1 + z1) / 3.0;
+                n += 1;
+                Q /= 4;
+            }
+            X = (A0 - x) / A / (1 << 2 * n);
+            Y = (A0 - y) / A / (1 << 2 * n);
+            Z = -(X + Y);
+
+            E2 = X * Y - Z * Z;
+            E3 = X * Y * Z;
+
+            return scale * (1.0 - E2 / 10.0 + E3 / 14.0 + E2 * E2 / 24.0 - 3.0 * E2 * E3 / 44.0) / sqrt(A);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellik(double phi, double m) {
+        double a, b, c, e, temp, t, K, denom, npio2;
+        int d, mod, sign;
+
+        if (std::isnan(phi) || std::isnan(m))
+            return std::numeric_limits::quiet_NaN();
+        if (m > 1.0)
+            return std::numeric_limits::quiet_NaN();
+        if (std::isinf(phi) || std::isinf(m)) {
+            if (std::isinf(m) && std::isfinite(phi))
+                return 0.0;
+            else if (std::isinf(phi) && std::isfinite(m))
+                return phi;
+            else
+                return std::numeric_limits::quiet_NaN();
+        }
+        if (m == 0.0)
+            return (phi);
+        a = 1.0 - m;
+        if (a == 0.0) {
+            if (std::abs(phi) >= (double) M_PI_2) {
+                set_error("ellik", SF_ERROR_SINGULAR, NULL);
+                return (std::numeric_limits::infinity());
+            }
+            /* DLMF 19.6.8, and 4.23.42 */
+            return std::asinh(std::tan(phi));
+        }
+        npio2 = floor(phi / M_PI_2);
+        if (std::fmod(std::abs(npio2), 2.0) == 1.0)
+            npio2 += 1;
+        if (npio2 != 0.0) {
+            K = ellpk(a);
+            phi = phi - npio2 * M_PI_2;
+        } else
+            K = 0.0;
+        if (phi < 0.0) {
+            phi = -phi;
+            sign = -1;
+        } else
+            sign = 0;
+        if (a > 1.0) {
+            temp = detail::ellik_neg_m(phi, m);
+            goto done;
+        }
+        b = std::sqrt(a);
+        t = std::tan(phi);
+        if (std::abs(t) > 10.0) {
+            /* Transform the amplitude */
+            e = 1.0 / (b * t);
+            /* ... but avoid multiple recursions.  */
+            if (std::abs(e) < 10.0) {
+                e = std::atan(e);
+                if (npio2 == 0)
+                    K = ellpk(a);
+                temp = K - ellik(e, m);
+                goto done;
+            }
+        }
+        a = 1.0;
+        c = std::sqrt(m);
+        d = 1;
+        mod = 0;
+
+        while (std::abs(c / a) > detail::MACHEP) {
+            temp = b / a;
+            phi = phi + atan(t * temp) + mod * M_PI;
+            denom = 1.0 - temp * t * t;
+            if (std::abs(denom) > 10 * detail::MACHEP) {
+                t = t * (1.0 + temp) / denom;
+                mod = (phi + M_PI_2) / M_PI;
+            } else {
+                t = std::tan(phi);
+                mod = static_cast(std::floor((phi - std::atan(t)) / M_PI));
+            }
+            c = (a - b) / 2.0;
+            temp = std::sqrt(a * b);
+            a = (a + b) / 2.0;
+            b = temp;
+            d += d;
+        }
+
+        temp = (std::atan(t) + mod * M_PI) / (d * a);
+
+    done:
+        if (sign < 0)
+            temp = -temp;
+        temp += npio2 * K;
+        return (temp);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h
new file mode 100644
index 0000000000000000000000000000000000000000..bc7c51f11acb13179aaffb301d052308722f8cfa
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h
@@ -0,0 +1,107 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellpe.c
+ *
+ *     Complete elliptic integral of the second kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double m, y, ellpe();
+ *
+ * y = ellpe( m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *            pi/2
+ *             -
+ *            | |                 2
+ * E(m)  =    |    sqrt( 1 - m sin t ) dt
+ *          | |
+ *           -
+ *            0
+ *
+ * Where m = 1 - m1, using the approximation
+ *
+ *      P(x)  -  x log x Q(x).
+ *
+ * Though there are no singularities, the argument m1 is used
+ * internally rather than m for compatibility with ellpk().
+ *
+ * E(1) = 1; E(0) = pi/2.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0, 1       10000       2.1e-16     7.3e-17
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * ellpe domain      x<0, x>1            0.0
+ *
+ */
+
+/*                                                     ellpe.c         */
+
+/* Elliptic integral of second kind */
+
+/*
+ * Cephes Math Library, Release 2.1:  February, 1989
+ * Copyright 1984, 1987, 1989 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ *
+ * Feb, 2002:  altered by Travis Oliphant
+ * so that it is called with argument m
+ * (which gets immediately converted to m1 = 1-m)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ellpe_P[] = {1.53552577301013293365E-4, 2.50888492163602060990E-3, 8.68786816565889628429E-3,
+                                      1.07350949056076193403E-2, 7.77395492516787092951E-3, 7.58395289413514708519E-3,
+                                      1.15688436810574127319E-2, 2.18317996015557253103E-2, 5.68051945617860553470E-2,
+                                      4.43147180560990850618E-1, 1.00000000000000000299E0};
+
+        constexpr double ellpe_Q[] = {3.27954898576485872656E-5, 1.00962792679356715133E-3, 6.50609489976927491433E-3,
+                                      1.68862163993311317300E-2, 2.61769742454493659583E-2, 3.34833904888224918614E-2,
+                                      4.27180926518931511717E-2, 5.85936634471101055642E-2, 9.37499997197644278445E-2,
+                                      2.49999999999888314361E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellpe(double x) {
+        x = 1.0 - x;
+        if (x <= 0.0) {
+            if (x == 0.0)
+                return (1.0);
+            set_error("ellpe", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+        if (x > 1.0) {
+            return ellpe(1.0 - 1 / x) * std::sqrt(x);
+        }
+        return (polevl(x, detail::ellpe_P, 10) - std::log(x) * (x * polevl(x, detail::ellpe_Q, 9)));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h
new file mode 100644
index 0000000000000000000000000000000000000000..39ebf7e80b193d385acb45feead4b91632830642
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h
@@ -0,0 +1,117 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellpk.c
+ *
+ *     Complete elliptic integral of the first kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double m1, y, ellpk();
+ *
+ * y = ellpk( m1 );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *
+ *            pi/2
+ *             -
+ *            | |
+ *            |           dt
+ * K(m)  =    |    ------------------
+ *            |                   2
+ *          | |    sqrt( 1 - m sin t )
+ *           -
+ *            0
+ *
+ * where m = 1 - m1, using the approximation
+ *
+ *     P(x)  -  log x Q(x).
+ *
+ * The argument m1 is used internally rather than m so that the logarithmic
+ * singularity at m = 1 will be shifted to the origin; this
+ * preserves maximum accuracy.
+ *
+ * K(0) = pi/2.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,1        30000       2.5e-16     6.8e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * ellpk domain       x<0, x>1           0.0
+ *
+ */
+
+/*                                                     ellpk.c */
+
+/*
+ * Cephes Math Library, Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ellpk_P[] = {1.37982864606273237150E-4, 2.28025724005875567385E-3, 7.97404013220415179367E-3,
+                                      9.85821379021226008714E-3, 6.87489687449949877925E-3, 6.18901033637687613229E-3,
+                                      8.79078273952743772254E-3, 1.49380448916805252718E-2, 3.08851465246711995998E-2,
+                                      9.65735902811690126535E-2, 1.38629436111989062502E0};
+
+        constexpr double ellpk_Q[] = {2.94078955048598507511E-5, 9.14184723865917226571E-4, 5.94058303753167793257E-3,
+                                      1.54850516649762399335E-2, 2.39089602715924892727E-2, 3.01204715227604046988E-2,
+                                      3.73774314173823228969E-2, 4.88280347570998239232E-2, 7.03124996963957469739E-2,
+                                      1.24999999999870820058E-1, 4.99999999999999999821E-1};
+
+        constexpr double ellpk_C1 = 1.3862943611198906188E0; /* log(4) */
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellpk(double x) {
+
+        if (x < 0.0) {
+            set_error("ellpk", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        if (x > 1.0) {
+            if (std::isinf(x)) {
+                return 0.0;
+            }
+            return ellpk(1 / x) / std::sqrt(x);
+        }
+
+        if (x > detail::MACHEP) {
+            return (polevl(x, detail::ellpk_P, 10) - std::log(x) * polevl(x, detail::ellpk_Q, 10));
+        } else {
+            if (x == 0.0) {
+                set_error("ellpk", SF_ERROR_SINGULAR, NULL);
+                return (std::numeric_limits::infinity());
+            } else {
+                return (detail::ellpk_C1 - 0.5 * std::log(x));
+            }
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h
new file mode 100644
index 0000000000000000000000000000000000000000..8b0b07eab7a94fb1519566da4ef9036fb67edec6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h
@@ -0,0 +1,260 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     expn.c
+ *
+ *             Exponential integral En
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int n;
+ * double x, y, expn();
+ *
+ * y = expn( n, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the exponential integral
+ *
+ *                 inf.
+ *                   -
+ *                  | |   -xt
+ *                  |    e
+ *      E (x)  =    |    ----  dt.
+ *       n          |      n
+ *                | |     t
+ *                 -
+ *                  1
+ *
+ *
+ * Both n and x must be nonnegative.
+ *
+ * The routine employs either a power series, a continued
+ * fraction, or an asymptotic formula depending on the
+ * relative values of n and x.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       10000       1.7e-15     3.6e-16
+ *
+ */
+
+/*                                                     expn.c  */
+
+/* Cephes Math Library Release 1.1:  March, 1985
+ * Copyright 1985 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */
+
+/* Sources
+ * [1] NIST, "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ */
+
+/* Scipy changes:
+ * - 09-10-2016: improved asymptotic expansion for large n
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "rgamma.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int expn_nA = 13;
+        constexpr double expn_A0[] = {1.00000000000000000};
+        constexpr double expn_A1[] = {1.00000000000000000};
+        constexpr double expn_A2[] = {-2.00000000000000000, 1.00000000000000000};
+        constexpr double expn_A3[] = {6.00000000000000000, -8.00000000000000000, 1.00000000000000000};
+        constexpr double expn_A4[] = {-24.0000000000000000, 58.0000000000000000, -22.0000000000000000,
+                                      1.00000000000000000};
+        constexpr double expn_A5[] = {120.000000000000000, -444.000000000000000, 328.000000000000000,
+                                      -52.0000000000000000, 1.00000000000000000};
+        constexpr double expn_A6[] = {-720.000000000000000, 3708.00000000000000,  -4400.00000000000000,
+                                      1452.00000000000000,  -114.000000000000000, 1.00000000000000000};
+        constexpr double expn_A7[] = {5040.00000000000000,  -33984.0000000000000, 58140.0000000000000,
+                                      -32120.0000000000000, 5610.00000000000000,  -240.000000000000000,
+                                      1.00000000000000000};
+        constexpr double expn_A8[] = {-40320.0000000000000, 341136.000000000000,  -785304.000000000000,
+                                      644020.000000000000,  -195800.000000000000, 19950.0000000000000,
+                                      -494.000000000000000, 1.00000000000000000};
+        constexpr double expn_A9[] = {362880.000000000000,  -3733920.00000000000, 11026296.0000000000,
+                                      -12440064.0000000000, 5765500.00000000000,  -1062500.00000000000,
+                                      67260.0000000000000,  -1004.00000000000000, 1.00000000000000000};
+        constexpr double expn_A10[] = {-3628800.00000000000, 44339040.0000000000,  -162186912.000000000,
+                                       238904904.000000000,  -155357384.000000000, 44765000.0000000000,
+                                       -5326160.00000000000, 218848.000000000000,  -2026.00000000000000,
+                                       1.00000000000000000};
+        constexpr double expn_A11[] = {39916800.0000000000,  -568356480.000000000, 2507481216.00000000,
+                                       -4642163952.00000000, 4002695088.00000000,  -1648384304.00000000,
+                                       314369720.000000000,  -25243904.0000000000, 695038.000000000000,
+                                       -4072.00000000000000, 1.00000000000000000};
+        constexpr double expn_A12[] = {-479001600.000000000, 7827719040.00000000,  -40788301824.0000000,
+                                       92199790224.0000000,  -101180433024.000000, 56041398784.0000000,
+                                       -15548960784.0000000, 2051482776.00000000,  -114876376.000000000,
+                                       2170626.00000000000,  -8166.00000000000000, 1.00000000000000000};
+        constexpr const double *expn_A[] = {expn_A0, expn_A1, expn_A2, expn_A3,  expn_A4,  expn_A5, expn_A6,
+                                            expn_A7, expn_A8, expn_A9, expn_A10, expn_A11, expn_A12};
+        constexpr int expn_Adegs[] = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
+
+        /* Asymptotic expansion for large n, DLMF 8.20(ii) */
+        XSF_HOST_DEVICE double expn_large_n(int n, double x) {
+            int k;
+            double p = n;
+            double lambda = x / p;
+            double multiplier = 1 / p / (lambda + 1) / (lambda + 1);
+            double fac = 1;
+            double res = 1; /* A[0] = 1 */
+            double expfac, term;
+
+            expfac = std::exp(-lambda * p) / (lambda + 1) / p;
+            if (expfac == 0) {
+                set_error("expn", SF_ERROR_UNDERFLOW, NULL);
+                return 0;
+            }
+
+            /* Do the k = 1 term outside the loop since A[1] = 1 */
+            fac *= multiplier;
+            res += fac;
+
+            for (k = 2; k < expn_nA; k++) {
+                fac *= multiplier;
+                term = fac * polevl(lambda, expn_A[k], expn_Adegs[k]);
+                res += term;
+                if (std::abs(term) < MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+
+            return expfac * res;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double expn(int n, double x) {
+        double ans, r, t, yk, xk;
+        double pk, pkm1, pkm2, qk, qkm1, qkm2;
+        double psi, z;
+        int i, k;
+        constexpr double big = 1.44115188075855872E+17;
+
+        if (std::isnan(x)) {
+            return std::numeric_limits::quiet_NaN();
+        } else if (n < 0 || x < 0) {
+            set_error("expn", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x > detail::MAXLOG) {
+            return (0.0);
+        }
+
+        if (x == 0.0) {
+            if (n < 2) {
+                set_error("expn", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            } else {
+                return (1.0 / (n - 1.0));
+            }
+        }
+
+        if (n == 0) {
+            return (std::exp(-x) / x);
+        }
+
+        /* Asymptotic expansion for large n, DLMF 8.20(ii) */
+        if (n > 50) {
+            ans = detail::expn_large_n(n, x);
+            return ans;
+        }
+
+        /* Continued fraction, DLMF 8.19.17 */
+        if (x > 1.0) {
+            k = 1;
+            pkm2 = 1.0;
+            qkm2 = x;
+            pkm1 = 1.0;
+            qkm1 = x + n;
+            ans = pkm1 / qkm1;
+
+            do {
+                k += 1;
+                if (k & 1) {
+                    yk = 1.0;
+                    xk = n + (k - 1) / 2;
+                } else {
+                    yk = x;
+                    xk = k / 2;
+                }
+                pk = pkm1 * yk + pkm2 * xk;
+                qk = qkm1 * yk + qkm2 * xk;
+                if (qk != 0) {
+                    r = pk / qk;
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else {
+                    t = 1.0;
+                }
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+                if (std::abs(pk) > big) {
+                    pkm2 /= big;
+                    pkm1 /= big;
+                    qkm2 /= big;
+                    qkm1 /= big;
+                }
+            } while (t > detail::MACHEP);
+
+            ans *= std::exp(-x);
+            return ans;
+        }
+
+        /* Power series expansion, DLMF 8.19.8 */
+        psi = -detail::SCIPY_EULER - std::log(x);
+        for (i = 1; i < n; i++) {
+            psi = psi + 1.0 / i;
+        }
+
+        z = -x;
+        xk = 0.0;
+        yk = 1.0;
+        pk = 1.0 - n;
+        if (n == 1) {
+            ans = 0.0;
+        } else {
+            ans = 1.0 / pk;
+        }
+        do {
+            xk += 1.0;
+            yk *= z / xk;
+            pk += 1.0;
+            if (pk != 0.0) {
+                ans += yk / pk;
+            }
+            if (ans != 0.0)
+                t = std::abs(yk / ans);
+            else
+                t = 1.0;
+        } while (t > detail::MACHEP);
+        k = xk;
+        t = n;
+        r = n - 1;
+        ans = (std::pow(z, r) * psi * rgamma(t)) - ans;
+        return ans;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..1ede1571a67ec9ce54bb6aa1afa1f17f5708f0c0
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h
@@ -0,0 +1,398 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*
+ *     Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, Gamma();
+ *
+ * y = Gamma( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Gamma function of the argument.  The result is
+ * correctly signed.
+ *
+ * Arguments |x| <= 34 are reduced by recurrence and the function
+ * approximated by a rational function of degree 6/7 in the
+ * interval (2,3).  Large arguments are handled by Stirling's
+ * formula. Large negative arguments are made positive using
+ * a reflection formula.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE    -170,-33      20000       2.3e-15     3.3e-16
+ *    IEEE     -33,  33     20000       9.4e-16     2.2e-16
+ *    IEEE      33, 171.6   20000       2.3e-15     3.2e-16
+ *
+ * Error for arguments outside the test range will be larger
+ * owing to error amplification by the exponential function.
+ *
+ */
+
+/*                                                     lgam()
+ *
+ *     Natural logarithm of Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, lgam();
+ *
+ * y = lgam( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the base e (2.718...) logarithm of the absolute
+ * value of the Gamma function of the argument.
+ *
+ * For arguments greater than 13, the logarithm of the Gamma
+ * function is approximated by the logarithmic version of
+ * Stirling's formula using a polynomial approximation of
+ * degree 4. Arguments between -33 and +33 are reduced by
+ * recurrence to the interval [2,3] of a rational approximation.
+ * The cosecant reflection formula is employed for arguments
+ * less than -33.
+ *
+ * Arguments greater than MAXLGM return INFINITY and an error
+ * message.  MAXLGM = 2.556348e305 for IEEE arithmetic.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *
+ * arithmetic      domain        # trials     peak         rms
+ *    IEEE    0, 3                 28000     5.4e-16     1.1e-16
+ *    IEEE    2.718, 2.556e305     40000     3.5e-16     8.3e-17
+ * The error criterion was relative when the function magnitude
+ * was greater than one but absolute when it was less than one.
+ *
+ * The following test used the relative error criterion, though
+ * at certain points the relative error could be much higher than
+ * indicated.
+ *    IEEE    -200, -4             10000     4.8e-16     1.3e-16
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.2:  July, 1992
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr double gamma_P[] = {1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2,
+                                      4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1,
+                                      9.99999999999999996796E-1};
+
+        constexpr double gamma_Q[] = {-2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3,
+                                      1.18139785222060435552E-2,  3.58236398605498653373E-2, -2.34591795718243348568E-1,
+                                      7.14304917030273074085E-2,  1.00000000000000000320E0};
+
+        /* Stirling's formula for the Gamma function */
+        constexpr double gamma_STIR[5] = {
+            7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3,
+            3.47222221605458667310E-3, 8.33333333333482257126E-2,
+        };
+
+        constexpr double MAXSTIR = 143.01608;
+
+        /* Gamma function computed by Stirling's formula.
+         * The polynomial STIR is valid for 33 <= x <= 172.
+         */
+        XSF_HOST_DEVICE inline double stirf(double x) {
+            double y, w, v;
+
+            if (x >= MAXGAM) {
+                return (std::numeric_limits::infinity());
+            }
+            w = 1.0 / x;
+            w = 1.0 + w * xsf::cephes::polevl(w, gamma_STIR, 4);
+            y = std::exp(x);
+            if (x > MAXSTIR) { /* Avoid overflow in pow() */
+                v = std::pow(x, 0.5 * x - 0.25);
+                y = v * (v / y);
+            } else {
+                y = std::pow(x, x - 0.5) / y;
+            }
+            y = SQRTPI * y * w;
+            return (y);
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double Gamma(double x) {
+        double p, q, z;
+        int i;
+        int sgngam = 1;
+
+        if (!std::isfinite(x)) {
+	    if (x > 0) {
+		// gamma(+inf) = +inf
+		return x;
+	    }
+	    // gamma(NaN) and gamma(-inf) both should equal NaN.
+            return std::numeric_limits::quiet_NaN();
+        }
+
+	if (x == 0) {
+	    /* For pole at zero, value depends on sign of zero.
+	     * +inf when approaching from right, -inf when approaching
+	     * from left. */
+	    return std::copysign(std::numeric_limits::infinity(), x);
+	}
+
+        q = std::abs(x);
+
+        if (q > 33.0) {
+            if (x < 0.0) {
+                p = std::floor(q);
+                if (p == q) {
+		    // x is a negative integer. This is a pole.
+                    set_error("Gamma", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::quiet_NaN());
+                }
+                i = p;
+                if ((i & 1) == 0) {
+                    sgngam = -1;
+                }
+                z = q - p;
+                if (z > 0.5) {
+                    p += 1.0;
+                    z = q - p;
+                }
+                z = q * sinpi(z);
+                if (z == 0.0) {
+                    return (sgngam * std::numeric_limits::infinity());
+                }
+                z = std::abs(z);
+                z = M_PI / (z * detail::stirf(q));
+            } else {
+                z = detail::stirf(x);
+            }
+            return (sgngam * z);
+        }
+
+        z = 1.0;
+        while (x >= 3.0) {
+            x -= 1.0;
+            z *= x;
+        }
+
+        while (x < 0.0) {
+            if (x > -1.E-9) {
+                goto small;
+            }
+            z /= x;
+            x += 1.0;
+        }
+
+        while (x < 2.0) {
+            if (x < 1.e-9) {
+                goto small;
+            }
+            z /= x;
+            x += 1.0;
+        }
+
+        if (x == 2.0) {
+            return (z);
+        }
+
+        x -= 2.0;
+        p = polevl(x, detail::gamma_P, 6);
+        q = polevl(x, detail::gamma_Q, 7);
+        return (z * p / q);
+
+    small:
+        if (x == 0.0) {
+	    /* For this to have happened, x must have started as a negative integer. */
+	    set_error("Gamma", SF_ERROR_SINGULAR, NULL);
+	    return (std::numeric_limits::quiet_NaN());
+        } else
+            return (z / ((1.0 + 0.5772156649015329 * x) * x));
+    }
+
+    namespace detail {
+        /* A[]: Stirling's formula expansion of log Gamma
+         * B[], C[]: log Gamma function between 2 and 3
+         */
+        constexpr double gamma_A[] = {8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4,
+                                      -2.77777777730099687205E-3, 8.33333333333331927722E-2};
+
+        constexpr double gamma_B[] = {-1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5,
+                                      -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5};
+
+        constexpr double gamma_C[] = {
+            /* 1.00000000000000000000E0, */
+            -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5,
+            -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6};
+
+        /* log( sqrt( 2*pi ) ) */
+        constexpr double LS2PI = 0.91893853320467274178;
+
+        constexpr double MAXLGM = 2.556348e305;
+
+        /* Disable optimizations for this function on 32 bit systems when compiling with GCC.
+         * We've found that enabling optimizations can result in degraded precision
+         * for this asymptotic approximation in that case. */
+#if defined(__GNUC__) && defined(__i386__)
+#pragma GCC push_options
+#pragma GCC optimize("00")
+#endif
+        XSF_HOST_DEVICE inline double lgam_large_x(double x) {
+            double q = (x - 0.5) * std::log(x) - x + LS2PI;
+            if (x > 1.0e8) {
+                return (q);
+            }
+            double p = 1.0 / (x * x);
+            p = ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333) / x;
+            return q + p;
+        }
+#if defined(__GNUC__) && defined(__i386__)
+#pragma GCC pop_options
+#endif
+
+        XSF_HOST_DEVICE inline double lgam_sgn(double x, int *sign) {
+            double p, q, u, w, z;
+            int i;
+
+            *sign = 1;
+
+            if (!std::isfinite(x)) {
+                return x;
+            }
+
+            if (x < -34.0) {
+                q = -x;
+                w = lgam_sgn(q, sign);
+                p = std::floor(q);
+                if (p == q) {
+                lgsing:
+                    set_error("lgam", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::infinity());
+                }
+                i = p;
+                if ((i & 1) == 0) {
+                    *sign = -1;
+                } else {
+                    *sign = 1;
+                }
+                z = q - p;
+                if (z > 0.5) {
+                    p += 1.0;
+                    z = p - q;
+                }
+                z = q * sinpi(z);
+                if (z == 0.0) {
+                    goto lgsing;
+                }
+                /*     z = log(M_PI) - log( z ) - w; */
+                z = LOGPI - std::log(z) - w;
+                return (z);
+            }
+
+            if (x < 13.0) {
+                z = 1.0;
+                p = 0.0;
+                u = x;
+                while (u >= 3.0) {
+                    p -= 1.0;
+                    u = x + p;
+                    z *= u;
+                }
+                while (u < 2.0) {
+                    if (u == 0.0) {
+                        goto lgsing;
+                    }
+                    z /= u;
+                    p += 1.0;
+                    u = x + p;
+                }
+                if (z < 0.0) {
+                    *sign = -1;
+                    z = -z;
+                } else {
+                    *sign = 1;
+                }
+                if (u == 2.0) {
+                    return (std::log(z));
+                }
+                p -= 2.0;
+                x = x + p;
+                p = x * polevl(x, gamma_B, 5) / p1evl(x, gamma_C, 6);
+                return (std::log(z) + p);
+            }
+
+            if (x > MAXLGM) {
+                return (*sign * std::numeric_limits::infinity());
+            }
+
+            if (x >= 1000.0) {
+                return lgam_large_x(x);
+            }
+
+            q = (x - 0.5) * std::log(x) - x + LS2PI;
+            p = 1.0 / (x * x);
+            return q + polevl(p, gamma_A, 4) / x;
+        }
+    } // namespace detail
+
+    /* Logarithm of Gamma function */
+    XSF_HOST_DEVICE inline double lgam(double x) {
+        int sign;
+        return detail::lgam_sgn(x, &sign);
+    }
+
+    /* Sign of the Gamma function */
+    XSF_HOST_DEVICE inline double gammasgn(double x) {
+        double fx;
+
+        if (std::isnan(x)) {
+            return x;
+        }
+        if (x > 0) {
+            return 1.0;
+	}
+	if (x == 0) {
+	    return std::copysign(1.0, x);
+	}
+	if (std::isinf(x)) {
+	    // x > 0 case handled, so x must be negative infinity.
+	    return std::numeric_limits::quiet_NaN();
+	}
+	fx = std::floor(x);
+	if (x - fx == 0.0) {
+	    return std::numeric_limits::quiet_NaN();
+	}
+	// sign of gamma for x in (-n, -n+1) for positive integer n is (-1)^n.
+	if (static_cast(fx) % 2) {
+	    return -1.0;
+	}
+	return 1.0;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h
new file mode 100644
index 0000000000000000000000000000000000000000..f9ec54bb20326552f5748ad9360dfecfbe18d660
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h
@@ -0,0 +1,596 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                      hyp2f1.c
+ *
+ *      Gauss hypergeometric function   F
+ *                                     2 1
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, c, x, y, hyp2f1();
+ *
+ * y = hyp2f1( a, b, c, x );
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *  hyp2f1( a, b, c, x )  =   F ( a, b; c; x )
+ *                           2 1
+ *
+ *           inf.
+ *            -   a(a+1)...(a+k) b(b+1)...(b+k)   k+1
+ *   =  1 +   >   -----------------------------  x   .
+ *            -         c(c+1)...(c+k) (k+1)!
+ *          k = 0
+ *
+ *  Cases addressed are
+ *      Tests and escapes for negative integer a, b, or c
+ *      Linear transformation if c - a or c - b negative integer
+ *      Special case c = a or c = b
+ *      Linear transformation for  x near +1
+ *      Transformation for x < -0.5
+ *      Psi function expansion if x > 0.5 and c - a - b integer
+ *      Conditionally, a recurrence on c to make c-a-b > 0
+ *
+ *      x < -1  AMS 15.3.7 transformation applied (Travis Oliphant)
+ *         valid for b,a,c,(b-a) != integer and (c-a),(c-b) != negative integer
+ *
+ * x >= 1 is rejected (unless special cases are present)
+ *
+ * The parameters a, b, c are considered to be integer
+ * valued if they are within 1.0e-14 of the nearest integer
+ * (1.0e-13 for IEEE arithmetic).
+ *
+ * ACCURACY:
+ *
+ *
+ *               Relative error (-1 < x < 1):
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      -1,7        230000      1.2e-11     5.2e-14
+ *
+ * Several special cases also tested with a, b, c in
+ * the range -7 to 7.
+ *
+ * ERROR MESSAGES:
+ *
+ * A "partial loss of precision" message is printed if
+ * the internally estimated relative error exceeds 1^-12.
+ * A "singularity" message is printed on overflow or
+ * in cases not addressed (such as x < -1).
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+#include "psi.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double hyp2f1_EPS = 1.0e-13;
+
+        constexpr double hyp2f1_ETHRESH = 1.0e-12;
+        constexpr std::uint64_t hyp2f1_MAXITER = 10000;
+
+        /* hys2f1 and hyp2f1ra depend on each other, so we need this prototype */
+        XSF_HOST_DEVICE double hyp2f1ra(double a, double b, double c, double x, double *loss);
+
+        /* Defining power series expansion of Gauss hypergeometric function */
+        /* The `loss` parameter estimates loss of significance */
+        XSF_HOST_DEVICE double hys2f1(double a, double b, double c, double x, double *loss) {
+            double f, g, h, k, m, s, u, umax;
+            std::uint64_t i;
+            int ib, intflag = 0;
+
+            if (std::abs(b) > std::abs(a)) {
+                /* Ensure that |a| > |b| ... */
+                f = b;
+                b = a;
+                a = f;
+            }
+
+            ib = std::round(b);
+
+            if (std::abs(b - ib) < hyp2f1_EPS && ib <= 0 && std::abs(b) < std::abs(a)) {
+                /* .. except when `b` is a smaller negative integer */
+                f = b;
+                b = a;
+                a = f;
+                intflag = 1;
+            }
+
+            if ((std::abs(a) > std::abs(c) + 1 || intflag) && std::abs(c - a) > 2 && std::abs(a) > 2) {
+                /* |a| >> |c| implies that large cancellation error is to be expected.
+                 *
+                 * We try to reduce it with the recurrence relations
+                 */
+                return hyp2f1ra(a, b, c, x, loss);
+            }
+
+            i = 0;
+            umax = 0.0;
+            f = a;
+            g = b;
+            h = c;
+            s = 1.0;
+            u = 1.0;
+            k = 0.0;
+            do {
+                if (std::abs(h) < hyp2f1_EPS) {
+                    *loss = 1.0;
+                    return std::numeric_limits::infinity();
+                }
+                m = k + 1.0;
+                u = u * ((f + k) * (g + k) * x / ((h + k) * m));
+                s += u;
+                k = std::abs(u); /* remember largest term summed */
+                if (k > umax)
+                    umax = k;
+                k = m;
+                if (++i > hyp2f1_MAXITER) { /* should never happen */
+                    *loss = 1.0;
+                    return (s);
+                }
+            } while (s == 0 || std::abs(u / s) > MACHEP);
+
+            /* return estimated relative error */
+            *loss = (MACHEP * umax) / fabs(s) + (MACHEP * i);
+
+            return (s);
+        }
+
+        /* Apply transformations for |x| near 1 then call the power series */
+        XSF_HOST_DEVICE double hyt2f1(double a, double b, double c, double x, double *loss) {
+            double p, q, r, s, t, y, w, d, err, err1;
+            double ax, id, d1, d2, e, y1;
+            int i, aid, sign;
+
+            int ia, ib, neg_int_a = 0, neg_int_b = 0;
+
+            ia = std::round(a);
+            ib = std::round(b);
+
+            if (a <= 0 && std::abs(a - ia) < hyp2f1_EPS) { /* a is a negative integer */
+                neg_int_a = 1;
+            }
+
+            if (b <= 0 && std::abs(b - ib) < hyp2f1_EPS) { /* b is a negative integer */
+                neg_int_b = 1;
+            }
+
+            err = 0.0;
+            s = 1.0 - x;
+            if (x < -0.5 && !(neg_int_a || neg_int_b)) {
+                if (b > a)
+                    y = std::pow(s, -a) * hys2f1(a, c - b, c, -x / s, &err);
+
+                else
+                    y = std::pow(s, -b) * hys2f1(c - a, b, c, -x / s, &err);
+
+                goto done;
+            }
+
+            d = c - a - b;
+            id = std::round(d); /* nearest integer to d */
+
+            if (x > 0.9 && !(neg_int_a || neg_int_b)) {
+                if (std::abs(d - id) > MACHEP) {
+                    int sgngam;
+
+                    /* test for integer c-a-b */
+                    /* Try the power series first */
+                    y = hys2f1(a, b, c, x, &err);
+                    if (err < hyp2f1_ETHRESH) {
+                        goto done;
+                    }
+                    /* If power series fails, then apply AMS55 #15.3.6 */
+                    q = hys2f1(a, b, 1.0 - d, s, &err);
+                    sign = 1;
+                    w = lgam_sgn(d, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(c - a, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(c - b, &sgngam);
+                    sign *= sgngam;
+                    q *= sign * std::exp(w);
+                    r = std::pow(s, d) * hys2f1(c - a, c - b, d + 1.0, s, &err1);
+                    sign = 1;
+                    w = lgam_sgn(-d, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(a, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(b, &sgngam);
+                    sign *= sgngam;
+                    r *= sign * std::exp(w);
+                    y = q + r;
+
+                    q = std::abs(q); /* estimate cancellation error */
+                    r = std::abs(r);
+                    if (q > r) {
+                        r = q;
+                    }
+                    err += err1 + (MACHEP * r) / y;
+
+                    y *= xsf::cephes::Gamma(c);
+                    goto done;
+                } else {
+                    /* Psi function expansion, AMS55 #15.3.10, #15.3.11, #15.3.12
+                     *
+                     * Although AMS55 does not explicitly state it, this expansion fails
+                     * for negative integer a or b, since the psi and Gamma functions
+                     * involved have poles.
+                     */
+
+                    if (id >= 0.0) {
+                        e = d;
+                        d1 = d;
+                        d2 = 0.0;
+                        aid = id;
+                    } else {
+                        e = -d;
+                        d1 = 0.0;
+                        d2 = d;
+                        aid = -id;
+                    }
+
+                    ax = std::log(s);
+
+                    /* sum for t = 0 */
+                    y = xsf::cephes::psi(1.0) + xsf::cephes::psi(1.0 + e) - xsf::cephes::psi(a + d1) -
+                        xsf::cephes::psi(b + d1) - ax;
+                    y *= xsf::cephes::rgamma(e + 1.0);
+
+                    p = (a + d1) * (b + d1) * s * xsf::cephes::rgamma(e + 2.0); /* Poch for t=1 */
+                    t = 1.0;
+                    do {
+                        r = xsf::cephes::psi(1.0 + t) + xsf::cephes::psi(1.0 + t + e) -
+                            xsf::cephes::psi(a + t + d1) - xsf::cephes::psi(b + t + d1) - ax;
+                        q = p * r;
+                        y += q;
+                        p *= s * (a + t + d1) / (t + 1.0);
+                        p *= (b + t + d1) / (t + 1.0 + e);
+                        t += 1.0;
+                        if (t > hyp2f1_MAXITER) { /* should never happen */
+                            set_error("hyp2f1", SF_ERROR_SLOW, NULL);
+                            *loss = 1.0;
+                            return std::numeric_limits::quiet_NaN();
+                        }
+                    } while (y == 0 || std::abs(q / y) > hyp2f1_EPS);
+
+                    if (id == 0.0) {
+                        y *= xsf::cephes::Gamma(c) / (xsf::cephes::Gamma(a) * xsf::cephes::Gamma(b));
+                        goto psidon;
+                    }
+
+                    y1 = 1.0;
+
+                    if (aid == 1)
+                        goto nosum;
+
+                    t = 0.0;
+                    p = 1.0;
+                    for (i = 1; i < aid; i++) {
+                        r = 1.0 - e + t;
+                        p *= s * (a + t + d2) * (b + t + d2) / r;
+                        t += 1.0;
+                        p /= t;
+                        y1 += p;
+                    }
+                nosum:
+                    p = xsf::cephes::Gamma(c);
+                    y1 *= xsf::cephes::Gamma(e) * p *
+                          (xsf::cephes::rgamma(a + d1) * xsf::cephes::rgamma(b + d1));
+
+                    y *= p * (xsf::cephes::rgamma(a + d2) * xsf::cephes::rgamma(b + d2));
+                    if ((aid & 1) != 0)
+                        y = -y;
+
+                    q = std::pow(s, id); /* s to the id power */
+                    if (id > 0.0)
+                        y *= q;
+                    else
+                        y1 *= q;
+
+                    y += y1;
+                psidon:
+                    goto done;
+                }
+            }
+
+            /* Use defining power series if no special cases */
+            y = hys2f1(a, b, c, x, &err);
+
+        done:
+            *loss = err;
+            return (y);
+        }
+
+        /*
+          15.4.2 Abramowitz & Stegun.
+        */
+        XSF_HOST_DEVICE double hyp2f1_neg_c_equal_bc(double a, double b, double x) {
+            double k;
+            double collector = 1;
+            double sum = 1;
+            double collector_max = 1;
+
+            if (!(std::abs(b) < 1e5)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            for (k = 1; k <= -b; k++) {
+                collector *= (a + k - 1) * x / k;
+                collector_max = std::fmax(std::abs(collector), collector_max);
+                sum += collector;
+            }
+
+            if (1e-16 * (1 + collector_max / std::abs(sum)) > 1e-7) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            return sum;
+        }
+
+        /*
+         * Evaluate hypergeometric function by two-term recurrence in `a`.
+         *
+         * This avoids some of the loss of precision in the strongly alternating
+         * hypergeometric series, and can be used to reduce the `a` and `b` parameters
+         * to smaller values.
+         *
+         * AMS55 #15.2.10
+         */
+        XSF_HOST_DEVICE double hyp2f1ra(double a, double b, double c, double x, double *loss) {
+            double f2, f1, f0;
+            int n;
+            double t, err, da;
+
+            /* Don't cross c or zero */
+            if ((c < 0 && a <= c) || (c >= 0 && a >= c)) {
+                da = std::round(a - c);
+            } else {
+                da = std::round(a);
+            }
+            t = a - da;
+
+            *loss = 0;
+
+            XSF_ASSERT(da != 0);
+
+            if (std::abs(da) > hyp2f1_MAXITER) {
+                /* Too expensive to compute this value, so give up */
+                set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+                *loss = 1.0;
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            if (da < 0) {
+                /* Recurse down */
+                f2 = 0;
+                f1 = hys2f1(t, b, c, x, &err);
+                *loss += err;
+                f0 = hys2f1(t - 1, b, c, x, &err);
+                *loss += err;
+                t -= 1;
+                for (n = 1; n < -da; ++n) {
+                    f2 = f1;
+                    f1 = f0;
+                    f0 = -(2 * t - c - t * x + b * x) / (c - t) * f1 - t * (x - 1) / (c - t) * f2;
+                    t -= 1;
+                }
+            } else {
+                /* Recurse up */
+                f2 = 0;
+                f1 = hys2f1(t, b, c, x, &err);
+                *loss += err;
+                f0 = hys2f1(t + 1, b, c, x, &err);
+                *loss += err;
+                t += 1;
+                for (n = 1; n < da; ++n) {
+                    f2 = f1;
+                    f1 = f0;
+                    f0 = -((2 * t - c - t * x + b * x) * f1 + (c - t) * f2) / (t * (x - 1));
+                    t += 1;
+                }
+            }
+
+            return f0;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double hyp2f1(double a, double b, double c, double x) {
+        double d, d1, d2, e;
+        double p, q, r, s, y, ax;
+        double ia, ib, ic, id, err;
+        double t1;
+        int i, aid;
+        int neg_int_a = 0, neg_int_b = 0;
+        int neg_int_ca_or_cb = 0;
+
+        err = 0.0;
+        ax = std::abs(x);
+        s = 1.0 - x;
+        ia = std::round(a); /* nearest integer to a */
+        ib = std::round(b);
+
+        if (x == 0.0) {
+            return 1.0;
+        }
+
+        d = c - a - b;
+        id = std::round(d);
+
+        if ((a == 0 || b == 0) && c != 0) {
+            return 1.0;
+        }
+
+        if (a <= 0 && std::abs(a - ia) < detail::hyp2f1_EPS) { /* a is a negative integer */
+            neg_int_a = 1;
+        }
+
+        if (b <= 0 && std::abs(b - ib) < detail::hyp2f1_EPS) { /* b is a negative integer */
+            neg_int_b = 1;
+        }
+
+        if (d <= -1 && !(std::abs(d - id) > detail::hyp2f1_EPS && s < 0) && !(neg_int_a || neg_int_b)) {
+            return std::pow(s, d) * hyp2f1(c - a, c - b, c, x);
+        }
+        if (d <= 0 && x == 1 && !(neg_int_a || neg_int_b))
+            goto hypdiv;
+
+        if (ax < 1.0 || x == -1.0) {
+            /* 2F1(a,b;b;x) = (1-x)**(-a) */
+            if (std::abs(b - c) < detail::hyp2f1_EPS) { /* b = c */
+                if (neg_int_b) {
+                    y = detail::hyp2f1_neg_c_equal_bc(a, b, x);
+                } else {
+                    y = std::pow(s, -a); /* s to the -a power */
+                }
+                goto hypdon;
+            }
+            if (std::abs(a - c) < detail::hyp2f1_EPS) { /* a = c */
+                y = std::pow(s, -b);                    /* s to the -b power */
+                goto hypdon;
+            }
+        }
+
+        if (c <= 0.0) {
+            ic = std::round(c);                          /* nearest integer to c */
+            if (std::abs(c - ic) < detail::hyp2f1_EPS) { /* c is a negative integer */
+                /* check if termination before explosion */
+                if (neg_int_a && (ia > ic))
+                    goto hypok;
+                if (neg_int_b && (ib > ic))
+                    goto hypok;
+                goto hypdiv;
+            }
+        }
+
+        if (neg_int_a || neg_int_b) /* function is a polynomial */
+            goto hypok;
+
+        t1 = std::abs(b - a);
+        if (x < -2.0 && std::abs(t1 - round(t1)) > detail::hyp2f1_EPS) {
+            /* This transform has a pole for b-a integer, and
+             * may produce large cancellation errors for |1/x| close 1
+             */
+            p = hyp2f1(a, 1 - c + a, 1 - b + a, 1.0 / x);
+            q = hyp2f1(b, 1 - c + b, 1 - a + b, 1.0 / x);
+            p *= std::pow(-x, -a);
+            q *= std::pow(-x, -b);
+            t1 = Gamma(c);
+            s = t1 * Gamma(b - a) * (rgamma(b) * rgamma(c - a));
+            y = t1 * Gamma(a - b) * (rgamma(a) * rgamma(c - b));
+            return s * p + y * q;
+        } else if (x < -1.0) {
+            if (std::abs(a) < std::abs(b)) {
+                return std::pow(s, -a) * hyp2f1(a, c - b, c, x / (x - 1));
+            } else {
+                return std::pow(s, -b) * hyp2f1(b, c - a, c, x / (x - 1));
+            }
+        }
+
+        if (ax > 1.0) /* series diverges  */
+            goto hypdiv;
+
+        p = c - a;
+        ia = std::round(p);                                         /* nearest integer to c-a */
+        if ((ia <= 0.0) && (std::abs(p - ia) < detail::hyp2f1_EPS)) /* negative int c - a */
+            neg_int_ca_or_cb = 1;
+
+        r = c - b;
+        ib = std::round(r);                                         /* nearest integer to c-b */
+        if ((ib <= 0.0) && (std::abs(r - ib) < detail::hyp2f1_EPS)) /* negative int c - b */
+            neg_int_ca_or_cb = 1;
+
+        id = std::round(d); /* nearest integer to d */
+        q = std::abs(d - id);
+
+        /* Thanks to Christian Burger 
+         * for reporting a bug here.  */
+        if (std::abs(ax - 1.0) < detail::hyp2f1_EPS) { /* |x| == 1.0   */
+            if (x > 0.0) {
+                if (neg_int_ca_or_cb) {
+                    if (d >= 0.0)
+                        goto hypf;
+                    else
+                        goto hypdiv;
+                }
+                if (d <= 0.0)
+                    goto hypdiv;
+                y = Gamma(c) * Gamma(d) * (rgamma(p) * rgamma(r));
+                goto hypdon;
+            }
+            if (d <= -1.0)
+                goto hypdiv;
+        }
+
+        /* Conditionally make d > 0 by recurrence on c
+         * AMS55 #15.2.27
+         */
+        if (d < 0.0) {
+            /* Try the power series first */
+            y = detail::hyt2f1(a, b, c, x, &err);
+            if (err < detail::hyp2f1_ETHRESH)
+                goto hypdon;
+            /* Apply the recurrence if power series fails */
+            err = 0.0;
+            aid = 2 - id;
+            e = c + aid;
+            d2 = hyp2f1(a, b, e, x);
+            d1 = hyp2f1(a, b, e + 1.0, x);
+            q = a + b + 1.0;
+            for (i = 0; i < aid; i++) {
+                r = e - 1.0;
+                y = (e * (r - (2.0 * e - q) * x) * d2 + (e - a) * (e - b) * x * d1) / (e * r * s);
+                e = r;
+                d1 = d2;
+                d2 = y;
+            }
+            goto hypdon;
+        }
+
+        if (neg_int_ca_or_cb) {
+            goto hypf; /* negative integer c-a or c-b */
+        }
+
+    hypok:
+        y = detail::hyt2f1(a, b, c, x, &err);
+
+    hypdon:
+        if (err > detail::hyp2f1_ETHRESH) {
+            set_error("hyp2f1", SF_ERROR_LOSS, NULL);
+            /*      printf( "Estimated err = %.2e\n", err ); */
+        }
+        return (y);
+
+        /* The transformation for c-a or c-b negative integer
+         * AMS55 #15.3.3
+         */
+    hypf:
+        y = std::pow(s, d) * detail::hys2f1(c - a, c - b, c, x, &err);
+        goto hypdon;
+
+        /* The alarm exit */
+    hypdiv:
+        set_error("hyp2f1", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::infinity();
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h
new file mode 100644
index 0000000000000000000000000000000000000000..18ebcff69ba4f9d9a7d5660aa8c63f858c56c7b3
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h
@@ -0,0 +1,361 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     hyperg.c
+ *
+ *     Confluent hypergeometric function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, x, y, hyperg();
+ *
+ * y = hyperg( a, b, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Computes the confluent hypergeometric function
+ *
+ *                          1           2
+ *                       a x    a(a+1) x
+ *   F ( a,b;x )  =  1 + ---- + --------- + ...
+ *  1 1                  b 1!   b(b+1) 2!
+ *
+ * Many higher transcendental functions are special cases of
+ * this power series.
+ *
+ * As is evident from the formula, b must not be a negative
+ * integer or zero unless a is an integer with 0 >= a > b.
+ *
+ * The routine attempts both a direct summation of the series
+ * and an asymptotic expansion.  In each case error due to
+ * roundoff, cancellation, and nonconvergence is estimated.
+ * The result with smaller estimated error is returned.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random points (a, b, x), all three variables
+ * ranging from 0 to 30.
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       1.8e-14     1.1e-15
+ *
+ * Larger errors can be observed when b is near a negative
+ * integer or zero.  Certain combinations of arguments yield
+ * serious cancellation error in the power series summation
+ * and also are not in the region of near convergence of the
+ * asymptotic series.  An error message is printed if the
+ * self-estimated relative error is greater than 1.0e-12.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* the `type` parameter determines what converging factor to use */
+        XSF_HOST_DEVICE inline double hyp2f0(double a, double b, double x, int type, double *err) {
+            double a0, alast, t, tlast, maxt;
+            double n, an, bn, u, sum, temp;
+
+            an = a;
+            bn = b;
+            a0 = 1.0e0;
+            alast = 1.0e0;
+            sum = 0.0;
+            n = 1.0e0;
+            t = 1.0e0;
+            tlast = 1.0e9;
+            maxt = 0.0;
+
+            do {
+                if (an == 0)
+                    goto pdone;
+                if (bn == 0)
+                    goto pdone;
+
+                u = an * (bn * x / n);
+
+                /* check for blowup */
+                temp = std::abs(u);
+                if ((temp > 1.0) && (maxt > (std::numeric_limits::max() / temp)))
+                    goto error;
+
+                a0 *= u;
+                t = std::abs(a0);
+
+                /* terminating condition for asymptotic series:
+                 * the series is divergent (if a or b is not a negative integer),
+                 * but its leading part can be used as an asymptotic expansion
+                 */
+                if (t > tlast)
+                    goto ndone;
+
+                tlast = t;
+                sum += alast; /* the sum is one term behind */
+                alast = a0;
+
+                if (n > 200)
+                    goto ndone;
+
+                an += 1.0e0;
+                bn += 1.0e0;
+                n += 1.0e0;
+                if (t > maxt)
+                    maxt = t;
+            } while (t > MACHEP);
+
+        pdone: /* series converged! */
+
+            /* estimate error due to roundoff and cancellation */
+            *err = std::abs(MACHEP * (n + maxt));
+
+            alast = a0;
+            goto done;
+
+        ndone: /* series did not converge */
+
+            /* The following "Converging factors" are supposed to improve accuracy,
+             * but do not actually seem to accomplish very much. */
+
+            n -= 1.0;
+            x = 1.0 / x;
+
+            switch (type) { /* "type" given as subroutine argument */
+            case 1:
+                alast *= (0.5 + (0.125 + 0.25 * b - 0.5 * a + 0.25 * x - 0.25 * n) / x);
+                break;
+
+            case 2:
+                alast *= 2.0 / 3.0 - b + 2.0 * a + x - n;
+                break;
+
+            default:;
+            }
+
+            /* estimate error due to roundoff, cancellation, and nonconvergence */
+            *err = MACHEP * (n + maxt) + std::abs(a0);
+
+        done:
+            sum += alast;
+            return (sum);
+
+            /* series blew up: */
+        error:
+            *err = std::numeric_limits::infinity();
+            set_error("hyperg", SF_ERROR_NO_RESULT, NULL);
+            return (sum);
+        }
+
+        /* asymptotic formula for hypergeometric function:
+         *
+         *        (    -a
+         *  --    ( |z|
+         * |  (b) ( -------- 2f0( a, 1+a-b, -1/x )
+         *        (  --
+         *        ( |  (b-a)
+         *
+         *
+         *                                x    a-b                     )
+         *                               e  |x|                        )
+         *                             + -------- 2f0( b-a, 1-a, 1/x ) )
+         *                                --                           )
+         *                               |  (a)                        )
+         */
+
+        XSF_HOST_DEVICE inline double hy1f1a(double a, double b, double x, double *err) {
+            double h1, h2, t, u, temp, acanc, asum, err1, err2;
+
+            if (x == 0) {
+                acanc = 1.0;
+                asum = std::numeric_limits::infinity();
+                goto adone;
+            }
+            temp = std::log(std::abs(x));
+            t = x + temp * (a - b);
+            u = -temp * a;
+
+            if (b > 0) {
+                temp = xsf::cephes::lgam(b);
+                t += temp;
+                u += temp;
+            }
+
+            h1 = hyp2f0(a, a - b + 1, -1.0 / x, 1, &err1);
+
+            temp = std::exp(u) * xsf::cephes::rgamma(b - a);
+            h1 *= temp;
+            err1 *= temp;
+
+            h2 = hyp2f0(b - a, 1.0 - a, 1.0 / x, 2, &err2);
+
+            if (a < 0)
+                temp = std::exp(t) * xsf::cephes::rgamma(a);
+            else
+                temp = std::exp(t - xsf::cephes::lgam(a));
+
+            h2 *= temp;
+            err2 *= temp;
+
+            if (x < 0.0)
+                asum = h1;
+            else
+                asum = h2;
+
+            acanc = std::abs(err1) + std::abs(err2);
+
+            if (b < 0) {
+                temp = xsf::cephes::Gamma(b);
+                asum *= temp;
+                acanc *= std::abs(temp);
+            }
+
+            if (asum != 0.0)
+                acanc /= std::abs(asum);
+
+            if (acanc != acanc)
+                /* nan */
+                acanc = 1.0;
+
+            if (std::isinf(asum))
+                /* infinity */
+                acanc = 0;
+
+            acanc *= 30.0; /* fudge factor, since error of asymptotic formula
+                            * often seems this much larger than advertised */
+        adone:
+            *err = acanc;
+            return (asum);
+        }
+
+        /* Power series summation for confluent hypergeometric function */
+        XSF_HOST_DEVICE inline double hy1f1p(double a, double b, double x, double *err) {
+            double n, a0, sum, t, u, temp, maxn;
+            double an, bn, maxt;
+            double y, c, sumc;
+
+            /* set up for power series summation */
+            an = a;
+            bn = b;
+            a0 = 1.0;
+            sum = 1.0;
+            c = 0.0;
+            n = 1.0;
+            t = 1.0;
+            maxt = 0.0;
+            *err = 1.0;
+
+            maxn = 200.0 + 2 * fabs(a) + 2 * fabs(b);
+
+            while (t > MACHEP) {
+                if (bn == 0) { /* check bn first since if both   */
+                    sf_error("hyperg", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::infinity()); /* an and bn are zero it is     */
+                }
+                if (an == 0) /* a singularity            */
+                    return (sum);
+                if (n > maxn) {
+                    /* too many terms; take the last one as error estimate */
+                    c = std::abs(c) + std::abs(t) * 50.0;
+                    goto pdone;
+                }
+                u = x * (an / (bn * n));
+
+                /* check for blowup */
+                temp = std::abs(u);
+                if ((temp > 1.0) && (maxt > (std::numeric_limits::max() / temp))) {
+                    *err = 1.0; /* blowup: estimate 100% error */
+                    return sum;
+                }
+
+                a0 *= u;
+
+                y = a0 - c;
+                sumc = sum + y;
+                c = (sumc - sum) - y;
+                sum = sumc;
+
+                t = std::abs(a0);
+
+                an += 1.0;
+                bn += 1.0;
+                n += 1.0;
+            }
+
+        pdone:
+
+            /* estimate error due to roundoff and cancellation */
+            if (sum != 0.0) {
+                *err = std::abs(c / sum);
+            } else {
+                *err = std::abs(c);
+            }
+
+            if (*err != *err) {
+                /* nan */
+                *err = 1.0;
+            }
+
+            return (sum);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double hyperg(double a, double b, double x) {
+        double asum, psum, acanc, pcanc, temp;
+
+        /* See if a Kummer transformation will help */
+        temp = b - a;
+        if (std::abs(temp) < 0.001 * std::abs(a))
+            return (exp(x) * hyperg(temp, b, -x));
+
+        /* Try power & asymptotic series, starting from the one that is likely OK */
+        if (std::abs(x) < 10 + std::abs(a) + std::abs(b)) {
+            psum = detail::hy1f1p(a, b, x, &pcanc);
+            if (pcanc < 1.0e-15)
+                goto done;
+            asum = detail::hy1f1a(a, b, x, &acanc);
+        } else {
+            psum = detail::hy1f1a(a, b, x, &pcanc);
+            if (pcanc < 1.0e-15)
+                goto done;
+            asum = detail::hy1f1p(a, b, x, &acanc);
+        }
+
+        /* Pick the result with less estimated error */
+
+        if (acanc < pcanc) {
+            pcanc = acanc;
+            psum = asum;
+        }
+
+    done:
+        if (pcanc > 1.0e-12)
+            set_error("hyperg", SF_ERROR_LOSS, NULL);
+
+        return (psum);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h
new file mode 100644
index 0000000000000000000000000000000000000000..f61e7b12fd22d92e741f53e2acee8a7f65278658
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h
@@ -0,0 +1,149 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     i0.c
+ *
+ *     Modified Bessel function of order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i0();
+ *
+ * y = i0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order zero of the
+ * argument.
+ *
+ * The function is defined as i0(x) = j0( ix ).
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       5.8e-16     1.4e-16
+ *
+ */
+/*							i0e.c
+ *
+ *	Modified Bessel function of order zero,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i0e();
+ *
+ * y = i0e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of order zero of the argument.
+ *
+ * The function is defined as i0e(x) = exp(-|x|) j0( ix ).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       5.4e-16     1.2e-16
+ * See i0().
+ *
+ */
+
+/*                                                     i0.c            */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "chbevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for exp(-x) I0(x)
+         * in the interval [0,8].
+         *
+         * lim(x->0){ exp(-x) I0(x) } = 1.
+         */
+        constexpr double i0_A[] = {
+            -4.41534164647933937950E-18, 3.33079451882223809783E-17,  -2.43127984654795469359E-16,
+            1.71539128555513303061E-15,  -1.16853328779934516808E-14, 7.67618549860493561688E-14,
+            -4.85644678311192946090E-13, 2.95505266312963983461E-12,  -1.72682629144155570723E-11,
+            9.67580903537323691224E-11,  -5.18979560163526290666E-10, 2.65982372468238665035E-9,
+            -1.30002500998624804212E-8,  6.04699502254191894932E-8,   -2.67079385394061173391E-7,
+            1.11738753912010371815E-6,   -4.41673835845875056359E-6,  1.64484480707288970893E-5,
+            -5.75419501008210370398E-5,  1.88502885095841655729E-4,   -5.76375574538582365885E-4,
+            1.63947561694133579842E-3,   -4.32430999505057594430E-3,  1.05464603945949983183E-2,
+            -2.37374148058994688156E-2,  4.93052842396707084878E-2,   -9.49010970480476444210E-2,
+            1.71620901522208775349E-1,   -3.04682672343198398683E-1,  6.76795274409476084995E-1};
+
+        /* Chebyshev coefficients for exp(-x) sqrt(x) I0(x)
+         * in the inverted interval [8,infinity].
+         *
+         * lim(x->inf){ exp(-x) sqrt(x) I0(x) } = 1/sqrt(2pi).
+         */
+        constexpr double i0_B[] = {
+            -7.23318048787475395456E-18, -4.83050448594418207126E-18, 4.46562142029675999901E-17,
+            3.46122286769746109310E-17,  -2.82762398051658348494E-16, -3.42548561967721913462E-16,
+            1.77256013305652638360E-15,  3.81168066935262242075E-15,  -9.55484669882830764870E-15,
+            -4.15056934728722208663E-14, 1.54008621752140982691E-14,  3.85277838274214270114E-13,
+            7.18012445138366623367E-13,  -1.79417853150680611778E-12, -1.32158118404477131188E-11,
+            -3.14991652796324136454E-11, 1.18891471078464383424E-11,  4.94060238822496958910E-10,
+            3.39623202570838634515E-9,   2.26666899049817806459E-8,   2.04891858946906374183E-7,
+            2.89137052083475648297E-6,   6.88975834691682398426E-5,   3.36911647825569408990E-3,
+            8.04490411014108831608E-1};
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double i0(double x) {
+        double y;
+
+        if (x < 0)
+            x = -x;
+        if (x <= 8.0) {
+            y = (x / 2.0) - 2.0;
+            return (std::exp(x) * chbevl(y, detail::i0_A, 30));
+        }
+
+        return (std::exp(x) * chbevl(32.0 / x - 2.0, detail::i0_B, 25) / sqrt(x));
+    }
+
+    XSF_HOST_DEVICE inline double i0e(double x) {
+        double y;
+
+        if (x < 0)
+            x = -x;
+        if (x <= 8.0) {
+            y = (x / 2.0) - 2.0;
+            return (chbevl(y, detail::i0_A, 30));
+        }
+
+        return (chbevl(32.0 / x - 2.0, detail::i0_B, 25) / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h
new file mode 100644
index 0000000000000000000000000000000000000000..49e2690391cf5af19ca36c72cbd38034920c1fd2
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h
@@ -0,0 +1,158 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     i1.c
+ *
+ *     Modified Bessel function of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i1();
+ *
+ * y = i1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order one of the
+ * argument.
+ *
+ * The function is defined as i1(x) = -i j1( ix ).
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.9e-15     2.1e-16
+ *
+ *
+ */
+/*							i1e.c
+ *
+ *	Modified Bessel function of order one,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i1e();
+ *
+ * y = i1e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of order one of the argument.
+ *
+ * The function is defined as i1(x) = -i exp(-|x|) j1( ix ).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       2.0e-15     2.0e-16
+ * See i1().
+ *
+ */
+
+/*                                                     i1.c 2          */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1985, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "chbevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for exp(-x) I1(x) / x
+         * in the interval [0,8].
+         *
+         * lim(x->0){ exp(-x) I1(x) / x } = 1/2.
+         */
+
+        constexpr double i1_A[] = {
+            2.77791411276104639959E-18,  -2.11142121435816608115E-17, 1.55363195773620046921E-16,
+            -1.10559694773538630805E-15, 7.60068429473540693410E-15,  -5.04218550472791168711E-14,
+            3.22379336594557470981E-13,  -1.98397439776494371520E-12, 1.17361862988909016308E-11,
+            -6.66348972350202774223E-11, 3.62559028155211703701E-10,  -1.88724975172282928790E-9,
+            9.38153738649577178388E-9,   -4.44505912879632808065E-8,  2.00329475355213526229E-7,
+            -8.56872026469545474066E-7,  3.47025130813767847674E-6,   -1.32731636560394358279E-5,
+            4.78156510755005422638E-5,   -1.61760815825896745588E-4,  5.12285956168575772895E-4,
+            -1.51357245063125314899E-3,  4.15642294431288815669E-3,   -1.05640848946261981558E-2,
+            2.47264490306265168283E-2,   -5.29459812080949914269E-2,  1.02643658689847095384E-1,
+            -1.76416518357834055153E-1,  2.52587186443633654823E-1};
+
+        /* Chebyshev coefficients for exp(-x) sqrt(x) I1(x)
+         * in the inverted interval [8,infinity].
+         *
+         * lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi).
+         */
+        constexpr double i1_B[] = {
+            7.51729631084210481353E-18,  4.41434832307170791151E-18,  -4.65030536848935832153E-17,
+            -3.20952592199342395980E-17, 2.96262899764595013876E-16,  3.30820231092092828324E-16,
+            -1.88035477551078244854E-15, -3.81440307243700780478E-15, 1.04202769841288027642E-14,
+            4.27244001671195135429E-14,  -2.10154184277266431302E-14, -4.08355111109219731823E-13,
+            -7.19855177624590851209E-13, 2.03562854414708950722E-12,  1.41258074366137813316E-11,
+            3.25260358301548823856E-11,  -1.89749581235054123450E-11, -5.58974346219658380687E-10,
+            -3.83538038596423702205E-9,  -2.63146884688951950684E-8,  -2.51223623787020892529E-7,
+            -3.88256480887769039346E-6,  -1.10588938762623716291E-4,  -9.76109749136146840777E-3,
+            7.78576235018280120474E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double i1(double x) {
+        double y, z;
+
+        z = std::abs(x);
+        if (z <= 8.0) {
+            y = (z / 2.0) - 2.0;
+            z = chbevl(y, detail::i1_A, 29) * z * std::exp(z);
+        } else {
+            z = std::exp(z) * chbevl(32.0 / z - 2.0, detail::i1_B, 25) / std::sqrt(z);
+        }
+        if (x < 0.0)
+            z = -z;
+        return (z);
+    }
+
+    /*                                                     i1e()   */
+
+    XSF_HOST_DEVICE inline double i1e(double x) {
+        double y, z;
+
+        z = std::abs(x);
+        if (z <= 8.0) {
+            y = (z / 2.0) - 2.0;
+            z = chbevl(y, detail::i1_A, 29) * z;
+        } else {
+            z = chbevl(32.0 / z - 2.0, detail::i1_B, 25) / std::sqrt(z);
+        }
+        if (x < 0.0)
+            z = -z;
+        return (z);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h
new file mode 100644
index 0000000000000000000000000000000000000000..dbe4f6519b13111d520306c5eec75bf811b02d0d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h
@@ -0,0 +1,421 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     igam.c
+ *
+ *     Incomplete Gamma integral
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, x, y, igam();
+ *
+ * y = igam( a, x );
+ *
+ * DESCRIPTION:
+ *
+ * The function is defined by
+ *
+ *                           x
+ *                            -
+ *                   1       | |  -t  a-1
+ *  igam(a,x)  =   -----     |   e   t   dt.
+ *                  -      | |
+ *                 | (a)    -
+ *                           0
+ *
+ *
+ * In this implementation both arguments must be positive.
+ * The integral is evaluated by either a power series or
+ * continued fraction expansion, depending on the relative
+ * values of a and x.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30       200000       3.6e-14     2.9e-15
+ *    IEEE      0,100      300000       9.9e-14     1.5e-14
+ */
+/*							igamc()
+ *
+ *	Complemented incomplete Gamma integral
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, x, y, igamc();
+ *
+ * y = igamc( a, x );
+ *
+ * DESCRIPTION:
+ *
+ * The function is defined by
+ *
+ *
+ *  igamc(a,x)   =   1 - igam(a,x)
+ *
+ *                            inf.
+ *                              -
+ *                     1       | |  -t  a-1
+ *               =   -----     |   e   t   dt.
+ *                    -      | |
+ *                   | (a)    -
+ *                             x
+ *
+ *
+ * In this implementation both arguments must be positive.
+ * The integral is evaluated by either a power series or
+ * continued fraction expansion, depending on the relative
+ * values of a and x.
+ *
+ * ACCURACY:
+ *
+ * Tested at random a, x.
+ *                a         x                      Relative error:
+ * arithmetic   domain   domain     # trials      peak         rms
+ *    IEEE     0.5,100   0,100      200000       1.9e-14     1.7e-15
+ *    IEEE     0.01,0.5  0,100      200000       1.4e-13     1.6e-15
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+
+/* Sources
+ * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ * [2] Maddock et. al., "Incomplete Gamma Functions",
+ *     https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/sf_gamma/igamma.html
+ */
+
+/* Scipy changes:
+ * - 05-01-2016: added asymptotic expansion for igam to improve the
+ *   a ~ x regime.
+ * - 06-19-2016: additional series expansion added for igamc to
+ *   improve accuracy at small arguments.
+ * - 06-24-2016: better choice of domain for the asymptotic series;
+ *   improvements in accuracy for the asymptotic series when a and x
+ *   are very close.
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "igam_asymp_coeff.h"
+#include "lanczos.h"
+#include "ndtr.h"
+#include "unity.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int igam_MAXITER = 2000;
+        constexpr int IGAM = 1;
+        constexpr int IGAMC = 0;
+        constexpr double igam_SMALL = 20;
+        constexpr double igam_LARGE = 200;
+        constexpr double igam_SMALLRATIO = 0.3;
+        constexpr double igam_LARGERATIO = 4.5;
+
+        constexpr double igam_big = 4.503599627370496e15;
+        constexpr double igam_biginv = 2.22044604925031308085e-16;
+
+        /* Compute
+         *
+         * x^a * exp(-x) / gamma(a)
+         *
+         * corrected from (15) and (16) in [2] by replacing exp(x - a) with
+         * exp(a - x).
+         */
+        XSF_HOST_DEVICE inline double igam_fac(double a, double x) {
+            double ax, fac, res, num;
+
+            if (std::abs(a - x) > 0.4 * std::abs(a)) {
+                ax = a * std::log(x) - x - xsf::cephes::lgam(a);
+                if (ax < -MAXLOG) {
+                    set_error("igam", SF_ERROR_UNDERFLOW, NULL);
+                    return 0.0;
+                }
+                return std::exp(ax);
+            }
+
+            fac = a + xsf::cephes::lanczos_g - 0.5;
+            res = std::sqrt(fac / std::exp(1)) / xsf::cephes::lanczos_sum_expg_scaled(a);
+
+            if ((a < 200) && (x < 200)) {
+                res *= std::exp(a - x) * std::pow(x / fac, a);
+            } else {
+                num = x - a - xsf::cephes::lanczos_g + 0.5;
+                res *= std::exp(a * xsf::cephes::log1pmx(num / fac) + x * (0.5 - xsf::cephes::lanczos_g) / fac);
+            }
+
+            return res;
+        }
+
+        /* Compute igamc using DLMF 8.9.2. */
+        XSF_HOST_DEVICE inline double igamc_continued_fraction(double a, double x) {
+            int i;
+            double ans, ax, c, yc, r, t, y, z;
+            double pk, pkm1, pkm2, qk, qkm1, qkm2;
+
+            ax = igam_fac(a, x);
+            if (ax == 0.0) {
+                return 0.0;
+            }
+
+            /* continued fraction */
+            y = 1.0 - a;
+            z = x + y + 1.0;
+            c = 0.0;
+            pkm2 = 1.0;
+            qkm2 = x;
+            pkm1 = x + 1.0;
+            qkm1 = z * x;
+            ans = pkm1 / qkm1;
+
+            for (i = 0; i < igam_MAXITER; i++) {
+                c += 1.0;
+                y += 1.0;
+                z += 2.0;
+                yc = y * c;
+                pk = pkm1 * z - pkm2 * yc;
+                qk = qkm1 * z - qkm2 * yc;
+                if (qk != 0) {
+                    r = pk / qk;
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else
+                    t = 1.0;
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+                if (std::abs(pk) > igam_big) {
+                    pkm2 *= igam_biginv;
+                    pkm1 *= igam_biginv;
+                    qkm2 *= igam_biginv;
+                    qkm1 *= igam_biginv;
+                }
+                if (t <= MACHEP) {
+                    break;
+                }
+            }
+
+            return (ans * ax);
+        }
+
+        /* Compute igam using DLMF 8.11.4. */
+        XSF_HOST_DEVICE inline double igam_series(double a, double x) {
+            int i;
+            double ans, ax, c, r;
+
+            ax = igam_fac(a, x);
+            if (ax == 0.0) {
+                return 0.0;
+            }
+
+            /* power series */
+            r = a;
+            c = 1.0;
+            ans = 1.0;
+
+            for (i = 0; i < igam_MAXITER; i++) {
+                r += 1.0;
+                c *= x / r;
+                ans += c;
+                if (c <= MACHEP * ans) {
+                    break;
+                }
+            }
+
+            return (ans * ax / a);
+        }
+
+        /* Compute igamc using DLMF 8.7.3. This is related to the series in
+         * igam_series but extra care is taken to avoid cancellation.
+         */
+        XSF_HOST_DEVICE inline double igamc_series(double a, double x) {
+            int n;
+            double fac = 1;
+            double sum = 0;
+            double term, logx;
+
+            for (n = 1; n < igam_MAXITER; n++) {
+                fac *= -x / n;
+                term = fac / (a + n);
+                sum += term;
+                if (std::abs(term) <= MACHEP * std::abs(sum)) {
+                    break;
+                }
+            }
+
+            logx = std::log(x);
+            term = -xsf::cephes::expm1(a * logx - xsf::cephes::lgam1p(a));
+            return term - std::exp(a * logx - xsf::cephes::lgam(a)) * sum;
+        }
+
+        /* Compute igam/igamc using DLMF 8.12.3/8.12.4. */
+        XSF_HOST_DEVICE inline double asymptotic_series(double a, double x, int func) {
+            int k, n, sgn;
+            int maxpow = 0;
+            double lambda = x / a;
+            double sigma = (x - a) / a;
+            double eta, res, ck, ckterm, term, absterm;
+            double absoldterm = std::numeric_limits::infinity();
+            double etapow[detail::igam_asymp_coeff_N] = {1};
+            double sum = 0;
+            double afac = 1;
+
+            if (func == detail::IGAM) {
+                sgn = -1;
+            } else {
+                sgn = 1;
+            }
+
+            if (lambda > 1) {
+                eta = std::sqrt(-2 * xsf::cephes::log1pmx(sigma));
+            } else if (lambda < 1) {
+                eta = -std::sqrt(-2 * xsf::cephes::log1pmx(sigma));
+            } else {
+                eta = 0;
+            }
+            res = 0.5 * xsf::cephes::erfc(sgn * eta * std::sqrt(a / 2));
+
+            for (k = 0; k < igam_asymp_coeff_K; k++) {
+                ck = igam_asymp_coeff_d[k][0];
+                for (n = 1; n < igam_asymp_coeff_N; n++) {
+                    if (n > maxpow) {
+                        etapow[n] = eta * etapow[n - 1];
+                        maxpow += 1;
+                    }
+                    ckterm = igam_asymp_coeff_d[k][n] * etapow[n];
+                    ck += ckterm;
+                    if (std::abs(ckterm) < MACHEP * std::abs(ck)) {
+                        break;
+                    }
+                }
+                term = ck * afac;
+                absterm = std::abs(term);
+                if (absterm > absoldterm) {
+                    break;
+                }
+                sum += term;
+                if (absterm < MACHEP * std::abs(sum)) {
+                    break;
+                }
+                absoldterm = absterm;
+                afac /= a;
+            }
+            res += sgn * std::exp(-0.5 * a * eta * eta) * sum / std::sqrt(2 * M_PI * a);
+
+            return res;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double igamc(double a, double x);
+
+    XSF_HOST_DEVICE inline double igam(double a, double x) {
+        double absxma_a;
+
+        if (x < 0 || a < 0) {
+            set_error("gammainc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        } else if (a == 0) {
+            if (x > 0) {
+                return 1;
+            } else {
+                return std::numeric_limits::quiet_NaN();
+            }
+        } else if (x == 0) {
+            /* Zero integration limit */
+            return 0;
+        } else if (std::isinf(a)) {
+            if (std::isinf(x)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+            return 0;
+        } else if (std::isinf(x)) {
+            return 1;
+        }
+
+        /* Asymptotic regime where a ~ x; see [2]. */
+        absxma_a = std::abs(x - a) / a;
+        if ((a > detail::igam_SMALL) && (a < detail::igam_LARGE) && (absxma_a < detail::igam_SMALLRATIO)) {
+            return detail::asymptotic_series(a, x, detail::IGAM);
+        } else if ((a > detail::igam_LARGE) && (absxma_a < detail::igam_LARGERATIO / std::sqrt(a))) {
+            return detail::asymptotic_series(a, x, detail::IGAM);
+        }
+
+        if ((x > 1.0) && (x > a)) {
+            return (1.0 - igamc(a, x));
+        }
+
+        return detail::igam_series(a, x);
+    }
+
+    XSF_HOST_DEVICE double igamc(double a, double x) {
+        double absxma_a;
+
+        if (x < 0 || a < 0) {
+            set_error("gammaincc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        } else if (a == 0) {
+            if (x > 0) {
+                return 0;
+            } else {
+                return std::numeric_limits::quiet_NaN();
+            }
+        } else if (x == 0) {
+            return 1;
+        } else if (std::isinf(a)) {
+            if (std::isinf(x)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+            return 1;
+        } else if (std::isinf(x)) {
+            return 0;
+        }
+
+        /* Asymptotic regime where a ~ x; see [2]. */
+        absxma_a = std::abs(x - a) / a;
+        if ((a > detail::igam_SMALL) && (a < detail::igam_LARGE) && (absxma_a < detail::igam_SMALLRATIO)) {
+            return detail::asymptotic_series(a, x, detail::IGAMC);
+        } else if ((a > detail::igam_LARGE) && (absxma_a < detail::igam_LARGERATIO / std::sqrt(a))) {
+            return detail::asymptotic_series(a, x, detail::IGAMC);
+        }
+
+        /* Everywhere else; see [2]. */
+        if (x > 1.1) {
+            if (x < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_continued_fraction(a, x);
+            }
+        } else if (x <= 0.5) {
+            if (-0.4 / std::log(x) < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_series(a, x);
+            }
+        } else {
+            if (x * 1.1 < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_series(a, x);
+            }
+        }
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h
new file mode 100644
index 0000000000000000000000000000000000000000..98404c65ebca79239022c0bae10cfe5e43c361c0
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h
@@ -0,0 +1,195 @@
+/* Translated into C++ by SciPy developers in 2024.  */
+
+/* This file was automatically generated by _precomp/gammainc.py.
+ * Do not edit it manually!
+ */
+#pragma once
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int igam_asymp_coeff_K = 25;
+        constexpr int igam_asymp_coeff_N = 25;
+
+        static const double igam_asymp_coeff_d[igam_asymp_coeff_K][igam_asymp_coeff_N] = {
+            {-3.3333333333333333e-1,  8.3333333333333333e-2,   -1.4814814814814815e-2,  1.1574074074074074e-3,
+             3.527336860670194e-4,    -1.7875514403292181e-4,  3.9192631785224378e-5,   -2.1854485106799922e-6,
+             -1.85406221071516e-6,    8.296711340953086e-7,    -1.7665952736826079e-7,  6.7078535434014986e-9,
+             1.0261809784240308e-8,   -4.3820360184533532e-9,  9.1476995822367902e-10,  -2.551419399494625e-11,
+             -5.8307721325504251e-11, 2.4361948020667416e-11,  -5.0276692801141756e-12, 1.1004392031956135e-13,
+             3.3717632624009854e-13,  -1.3923887224181621e-13, 2.8534893807047443e-14,  -5.1391118342425726e-16,
+             -1.9752288294349443e-15},
+            {-1.8518518518518519e-3,  -3.4722222222222222e-3,  2.6455026455026455e-3,   -9.9022633744855967e-4,
+             2.0576131687242798e-4,   -4.0187757201646091e-7,  -1.8098550334489978e-5,  7.6491609160811101e-6,
+             -1.6120900894563446e-6,  4.6471278028074343e-9,   1.378633446915721e-7,    -5.752545603517705e-8,
+             1.1951628599778147e-8,   -1.7543241719747648e-11, -1.0091543710600413e-9,  4.1627929918425826e-10,
+             -8.5639070264929806e-11, 6.0672151016047586e-14,  7.1624989648114854e-12,  -2.9331866437714371e-12,
+             5.9966963656836887e-13,  -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14,
+             -4.13125571381061e-15},
+            {4.1335978835978836e-3,   -2.6813271604938272e-3,  7.7160493827160494e-4,  2.0093878600823045e-6,
+             -1.0736653226365161e-4,  5.2923448829120125e-5,   -1.2760635188618728e-5, 3.4235787340961381e-8,
+             1.3721957309062933e-6,   -6.298992138380055e-7,   1.4280614206064242e-7,  -2.0477098421990866e-10,
+             -1.4092529910867521e-8,  6.228974084922022e-9,    -1.3670488396617113e-9, 9.4283561590146782e-13,
+             1.2872252400089318e-10,  -5.5645956134363321e-11, 1.1975935546366981e-11, -4.1689782251838635e-15,
+             -1.0940640427884594e-12, 4.6622399463901357e-13,  -9.905105763906906e-14, 1.8931876768373515e-17,
+             8.8592218725911273e-15},
+            {6.4943415637860082e-4,   2.2947209362139918e-4,   -4.6918949439525571e-4,  2.6772063206283885e-4,
+             -7.5618016718839764e-5,  -2.3965051138672967e-7,  1.1082654115347302e-5,   -5.6749528269915966e-6,
+             1.4230900732435884e-6,   -2.7861080291528142e-11, -1.6958404091930277e-7,  8.0994649053880824e-8,
+             -1.9111168485973654e-8,  2.3928620439808118e-12,  2.0620131815488798e-9,   -9.4604966618551322e-10,
+             2.1541049775774908e-10,  -1.388823336813903e-14,  -2.1894761681963939e-11, 9.7909989511716851e-12,
+             -2.1782191880180962e-12, 6.2088195734079014e-17,  2.126978363279737e-13,   -9.3446887915174333e-14,
+             2.0453671226782849e-14},
+            {-8.618882909167117e-4,   7.8403922172006663e-4,   -2.9907248030319018e-4, -1.4638452578843418e-6,
+             6.6414982154651222e-5,   -3.9683650471794347e-5,  1.1375726970678419e-5,  2.5074972262375328e-10,
+             -1.6954149536558306e-6,  8.9075075322053097e-7,   -2.2929348340008049e-7, 2.956794137544049e-11,
+             2.8865829742708784e-8,   -1.4189739437803219e-8,  3.4463580499464897e-9,  -2.3024517174528067e-13,
+             -3.9409233028046405e-10, 1.8602338968504502e-10,  -4.356323005056618e-11, 1.2786001016296231e-15,
+             4.6792750266579195e-12,  -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18,
+             -5.0453320690800944e-14},
+            {-3.3679855336635815e-4,  -6.9728137583658578e-5,  2.7727532449593921e-4,  -1.9932570516188848e-4,
+             6.7977804779372078e-5,   1.419062920643967e-7,    -1.3594048189768693e-5, 8.0184702563342015e-6,
+             -2.2914811765080952e-6,  -3.252473551298454e-10,  3.4652846491085265e-7,  -1.8447187191171343e-7,
+             4.8240967037894181e-8,   -1.7989466721743515e-14, -6.3061945000135234e-9, 3.1624176287745679e-9,
+             -7.8409242536974293e-10, 5.1926791652540407e-15,  9.3589442423067836e-11, -4.5134262161632782e-11,
+             1.0799129993116827e-11,  -3.661886712685252e-17,  -1.210902069055155e-12, 5.6807435849905643e-13,
+             -1.3249659916340829e-13},
+            {5.3130793646399222e-4,   -5.9216643735369388e-4,  2.7087820967180448e-4,   7.9023532326603279e-7,
+             -8.1539693675619688e-5,  5.6116827531062497e-5,   -1.8329116582843376e-5,  -3.0796134506033048e-9,
+             3.4651553688036091e-6,   -2.0291327396058604e-6,  5.7887928631490037e-7,   2.338630673826657e-13,
+             -8.8286007463304835e-8,  4.7435958880408128e-8,   -1.2545415020710382e-8,  8.6496488580102925e-14,
+             1.6846058979264063e-9,   -8.5754928235775947e-10, 2.1598224929232125e-10,  -7.6132305204761539e-16,
+             -2.6639822008536144e-11, 1.3065700536611057e-11,  -3.1799163902367977e-12, 4.7109761213674315e-18,
+             3.6902800842763467e-13},
+            {3.4436760689237767e-4,   5.1717909082605922e-5,   -3.3493161081142236e-4,  2.812695154763237e-4,
+             -1.0976582244684731e-4,  -1.2741009095484485e-7,  2.7744451511563644e-5,   -1.8263488805711333e-5,
+             5.7876949497350524e-6,   4.9387589339362704e-10,  -1.0595367014026043e-6,  6.1667143761104075e-7,
+             -1.7562973359060462e-7,  -1.2974473287015439e-12, 2.695423606288966e-8,    -1.4578352908731271e-8,
+             3.887645959386175e-9,    -3.8810022510194121e-17, -5.3279941738772867e-10, 2.7437977643314845e-10,
+             -6.9957960920705679e-11, 2.5899863874868481e-17,  8.8566890996696381e-12,  -4.403168815871311e-12,
+             1.0865561947091654e-12},
+            {-6.5262391859530942e-4, 8.3949872067208728e-4,   -4.3829709854172101e-4, -6.969091458420552e-7,
+             1.6644846642067548e-4,  -1.2783517679769219e-4,  4.6299532636913043e-5,  4.5579098679227077e-9,
+             -1.0595271125805195e-5, 6.7833429048651666e-6,   -2.1075476666258804e-6, -1.7213731432817145e-11,
+             3.7735877416110979e-7,  -2.1867506700122867e-7,  6.2202288040189269e-8,  6.5977038267330006e-16,
+             -9.5903864974256858e-9, 5.2132144922808078e-9,   -1.3991589583935709e-9, 5.382058999060575e-16,
+             1.9484714275467745e-10, -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18,
+             -3.3721464474854592e-12},
+            {-5.9676129019274625e-4, -7.2048954160200106e-5,  6.7823088376673284e-4,   -6.4014752602627585e-4,
+             2.7750107634328704e-4,  1.8197008380465151e-7,   -8.4795071170685032e-5,  6.105192082501531e-5,
+             -2.1073920183404862e-5, -8.8585890141255994e-10, 4.5284535953805377e-6,   -2.8427815022504408e-6,
+             8.7082341778646412e-7,  3.6886101871706965e-12,  -1.5344695190702061e-7,  8.862466778790695e-8,
+             -2.5184812301826817e-8, -1.0225912098215092e-14, 3.8969470758154777e-9,   -2.1267304792235635e-9,
+             5.7370135528051385e-10, -1.887749850169741e-19,  -8.0931538694657866e-11, 4.2382723283449199e-11,
+             -1.1002224534207726e-11},
+            {1.3324454494800656e-3,  -1.9144384985654775e-3, 1.1089369134596637e-3,   9.932404122642299e-7,
+             -5.0874501293093199e-4, 4.2735056665392884e-4,  -1.6858853767910799e-4,  -8.1301893922784998e-9,
+             4.5284402370562147e-5,  -3.127053674781734e-5,  1.044986828530338e-5,    4.8435226265680926e-11,
+             -2.1482565873456258e-6, 1.329369701097492e-6,   -4.0295693092101029e-7,  -1.7567877666323291e-13,
+             7.0145043163668257e-8,  -4.040787734999483e-8,  1.1474026743371963e-8,   3.9642746853563325e-18,
+             -1.7804938269892714e-9, 9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18,
+             3.7647749553543836e-11},
+            {1.579727660730835e-3,   1.6251626278391582e-4,   -2.0633421035543276e-3, 2.1389686185689098e-3,
+             -1.0108559391263003e-3, -3.9912705529919201e-7,  3.6235025084764691e-4,  -2.8143901463712154e-4,
+             1.0449513336495887e-4,  2.1211418491830297e-9,   -2.5779417251947842e-5, 1.7281818956040463e-5,
+             -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6,  -6.8693396379526735e-7,
+             2.0653236975414887e-7,  4.6714772409838506e-14,  -3.5609886164949055e-8, 2.0470855345905963e-8,
+             -5.8091738633283358e-9, -1.332821287582869e-16,  9.0354604391335133e-10, -4.9598782517330834e-10,
+             1.3481607129399749e-10},
+            {-4.0725121195140166e-3, 6.4033628338080698e-3,  -4.0410161081676618e-3, -2.183732802866233e-6,
+             2.1740441801254639e-3,  -1.9700440518418892e-3, 8.3595469747962458e-4,  1.9445447567109655e-8,
+             -2.5779387120421696e-4, 1.9009987368139304e-4,  -6.7696499937438965e-5, -1.4440629666426572e-10,
+             1.5712512518742269e-5,  -1.0304008744776893e-5, 3.304517767401387e-6,   7.9829760242325709e-13,
+             -6.4097794149313004e-7, 3.8894624761300056e-7,  -1.1618347644948869e-7, -2.816808630596451e-15,
+             1.9878012911297093e-8,  -1.1407719956357511e-8, 3.2355857064185555e-9,  4.1759468293455945e-20,
+             -5.0423112718105824e-10},
+            {-5.9475779383993003e-3, -5.4016476789260452e-4,  8.7910413550767898e-3,  -9.8576315587856125e-3,
+             5.0134695031021538e-3,  1.2807521786221875e-6,   -2.0626019342754683e-3, 1.7109128573523058e-3,
+             -6.7695312714133799e-4, -6.9011545676562133e-9,  1.8855128143995902e-4,  -1.3395215663491969e-4,
+             4.6263183033528039e-5,  4.0034230613321351e-11,  -1.0255652921494033e-5, 6.612086372797651e-6,
+             -2.0913022027253008e-6, -2.0951775649603837e-13, 3.9756029041993247e-7,  -2.3956211978815887e-7,
+             7.1182883382145864e-8,  8.925574873053455e-16,   -1.2101547235064676e-8, 6.9350618248334386e-9,
+             -1.9661464453856102e-9},
+            {1.7402027787522711e-2,  -2.9527880945699121e-2, 2.0045875571402799e-2,  7.0289515966903407e-6,
+             -1.2375421071343148e-2, 1.1976293444235254e-2,  -5.4156038466518525e-3, -6.3290893396418616e-8,
+             1.8855118129005065e-3,  -1.473473274825001e-3,  5.5515810097708387e-4,  5.2406834412550662e-10,
+             -1.4357913535784836e-4, 9.9181293224943297e-5,  -3.3460834749478311e-5, -3.5755837291098993e-12,
+             7.1560851960630076e-6,  -4.5516802628155526e-6, 1.4236576649271475e-6,  1.8803149082089664e-14,
+             -2.6623403898929211e-7, 1.5950642189595716e-7,  -4.7187514673841102e-8, -6.5107872958755177e-17,
+             7.9795091026746235e-9},
+            {3.0249124160905891e-2,  2.4817436002649977e-3,  -4.9939134373457022e-2, 5.9915643009307869e-2,
+             -3.2483207601623391e-2, -5.7212968652103441e-6, 1.5085251778569354e-2,  -1.3261324005088445e-2,
+             5.5515262632426148e-3,  3.0263182257030016e-8,  -1.7229548406756723e-3, 1.2893570099929637e-3,
+             -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4,  -7.7378565221244477e-5,
+             2.5625836246985201e-5,  1.0766165333192814e-12, -5.3246809282422621e-6, 3.349634863064464e-6,
+             -1.0381253128684018e-6, -5.608909920621128e-15, 1.9150821930676591e-7,  -1.1418365800203486e-7,
+             3.3654425209171788e-8},
+            {-9.9051020880159045e-2, 1.7954011706123486e-1,  -1.2989606383463778e-1, -3.1478872752284357e-5,
+             9.0510635276848131e-2,  -9.2828824411184397e-2, 4.4412112839877808e-2,  2.7779236316835888e-7,
+             -1.7229543805449697e-2, 1.4182925050891573e-2,  -5.6214161633747336e-3, -2.39598509186381e-9,
+             1.6029634366079908e-3,  -1.1606784674435773e-3, 4.1001337768153873e-4,  1.8365800754090661e-11,
+             -9.5844256563655903e-5, 6.3643062337764708e-5,  -2.076250624489065e-5,  -1.1806020912804483e-13,
+             4.2131808239120649e-6,  -2.6262241337012467e-6, 8.0770620494930662e-7,  6.0125912123632725e-16,
+             -1.4729737374018841e-7},
+            {-1.9994542198219728e-1, -1.5056113040026424e-2,  3.6470239469348489e-1,  -4.6435192311733545e-1,
+             2.6640934719197893e-1,  3.4038266027147191e-5,   -1.3784338709329624e-1, 1.276467178337056e-1,
+             -5.6213828755200985e-2, -1.753150885483011e-7,   1.9235592956768113e-2,  -1.5088821281095315e-2,
+             5.7401854451350123e-3,  1.0622382710310225e-9,   -1.5335082692563998e-3, 1.0819320643228214e-3,
+             -3.7372510193945659e-4, -6.6170909729031985e-12, 8.4263617380909628e-5,  -5.5150706827483479e-5,
+             1.7769536448348069e-5,  3.8827923210205533e-14,  -3.53513697488768e-6,   2.1865832130045269e-6,
+             -6.6812849447625594e-7},
+            {7.2438608504029431e-1,  -1.3918010932653375,    1.0654143352413968,     1.876173868950258e-4,
+             -8.2705501176152696e-1, 8.9352433347828414e-1,  -4.4971003995291339e-1, -1.6107401567546652e-6,
+             1.9235590165271091e-1,  -1.6597702160042609e-1, 6.8882222681814333e-2,  1.3910091724608687e-8,
+             -2.146911561508663e-2,  1.6228980898865892e-2,  -5.9796016172584256e-3, -1.1287469112826745e-10,
+             1.5167451119784857e-3,  -1.0478634293553899e-3, 3.5539072889126421e-4,  8.1704322111801517e-13,
+             -7.7773013442452395e-5, 5.0291413897007722e-5,  -1.6035083867000518e-5, 1.2469354315487605e-14,
+             3.1369106244517615e-6},
+            {1.6668949727276811,     1.165462765994632e-1,   -3.3288393225018906,    4.4692325482864037,
+             -2.6977693045875807,    -2.600667859891061e-4,  1.5389017615694539,     -1.4937962361134612,
+             6.8881964633233148e-1,  1.3077482004552385e-6,  -2.5762963325596288e-1, 2.1097676102125449e-1,
+             -8.3714408359219882e-2, -7.7920428881354753e-9, 2.4267923064833599e-2,  -1.7813678334552311e-2,
+             6.3970330388900056e-3,  4.9430807090480523e-11, -1.5554602758465635e-3, 1.0561196919903214e-3,
+             -3.5277184460472902e-4, 9.3002334645022459e-14, 7.5285855026557172e-5,  -4.8186515569156351e-5,
+             1.5227271505597605e-5},
+            {-6.6188298861372935,    1.3397985455142589e+1,  -1.0789350606845146e+1, -1.4352254537875018e-3,
+             9.2333694596189809,     -1.0456552819547769e+1, 5.5105526029033471,     1.2024439690716742e-5,
+             -2.5762961164755816,    2.3207442745387179,     -1.0045728797216284,    -1.0207833290021914e-7,
+             3.3975092171169466e-1,  -2.6720517450757468e-1, 1.0235252851562706e-1,  8.4329730484871625e-10,
+             -2.7998284958442595e-2, 2.0066274144976813e-2,  -7.0554368915086242e-3, 1.9402238183698188e-12,
+             1.6562888105449611e-3,  -1.1082898580743683e-3, 3.654545161310169e-4,   -5.1290032026971794e-11,
+             -7.6340103696869031e-5},
+            {-1.7112706061976095e+1, -1.1208044642899116,     3.7131966511885444e+1,  -5.2298271025348962e+1,
+             3.3058589696624618e+1,  2.4791298976200222e-3,   -2.061089403411526e+1,  2.088672775145582e+1,
+             -1.0045703956517752e+1, -1.2238783449063012e-5,  4.0770134274221141,     -3.473667358470195,
+             1.4329352617312006,     7.1359914411879712e-8,   -4.4797257159115612e-1, 3.4112666080644461e-1,
+             -1.2699786326594923e-1, -2.8953677269081528e-10, 3.3125776278259863e-2,  -2.3274087021036101e-2,
+             8.0399993503648882e-3,  -1.177805216235265e-9,   -1.8321624891071668e-3, 1.2108282933588665e-3,
+             -3.9479941246822517e-4},
+            {7.389033153567425e+1,   -1.5680141270402273e+2, 1.322177542759164e+2,   1.3692876877324546e-2,
+             -1.2366496885920151e+2, 1.4620689391062729e+2,  -8.0365587724865346e+1, -1.1259851148881298e-4,
+             4.0770132196179938e+1,  -3.8210340013273034e+1, 1.719522294277362e+1,   9.3519707955168356e-7,
+             -6.2716159907747034,    5.1168999071852637,     -2.0319658112299095,    -4.9507215582761543e-9,
+             5.9626397294332597e-1,  -4.4220765337238094e-1, 1.6079998700166273e-1,  -2.4733786203223402e-8,
+             -4.0307574759979762e-2, 2.7849050747097869e-2,  -9.4751858992054221e-3, 6.419922235909132e-6,
+             2.1250180774699461e-3},
+            {2.1216837098382522e+2,  1.3107863022633868e+1,  -4.9698285932871748e+2, 7.3121595266969204e+2,
+             -4.8213821720890847e+2, -2.8817248692894889e-2, 3.2616720302947102e+2,  -3.4389340280087117e+2,
+             1.7195193870816232e+2,  1.4038077378096158e-4,  -7.52594195897599e+1,   6.651969984520934e+1,
+             -2.8447519748152462e+1, -7.613702615875391e-7,  9.5402237105304373,     -7.5175301113311376,
+             2.8943997568871961,     -4.6612194999538201e-7, -8.0615149598794088e-1, 5.8483006570631029e-1,
+             -2.0845408972964956e-1, 1.4765818959305817e-4,  5.1000433863753019e-2,  -3.3066252141883665e-2,
+             1.5109265210467774e-2},
+            {-9.8959643098322368e+2, 2.1925555360905233e+3,  -1.9283586782723356e+3, -1.5925738122215253e-1,
+             1.9569985945919857e+3,  -2.4072514765081556e+3, 1.3756149959336496e+3,  1.2920735237496668e-3,
+             -7.525941715948055e+2,  7.3171668742208716e+2,  -3.4137023466220065e+2, -9.9857390260608043e-6,
+             1.3356313181291573e+2,  -1.1276295161252794e+2, 4.6310396098204458e+1,  -7.9237387133614756e-6,
+             -1.4510726927018646e+1, 1.1111771248100563e+1,  -4.1690817945270892,    3.1008219800117808e-3,
+             1.1220095449981468,     -7.6052379926149916e-1, 3.6262236505085254e-1,  2.216867741940747e-1,
+             4.8683443692930507e-1}};
+
+    } // namespace detail
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h
new file mode 100644
index 0000000000000000000000000000000000000000..ff82c35f682b04a250f6a86721312f860b3fe7cb
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h
@@ -0,0 +1,313 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*
+ * (C) Copyright John Maddock 2006.
+ * Use, modification and distribution are subject to the
+ * Boost Software License, Version 1.0. (See accompanying file
+ *  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "igam.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        XSF_HOST_DEVICE double find_inverse_s(double p, double q) {
+            /*
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             *
+             * See equation 32.
+             */
+            double s, t;
+            constexpr double a[4] = {0.213623493715853, 4.28342155967104, 11.6616720288968, 3.31125922108741};
+            constexpr double b[5] = {0.3611708101884203e-1, 1.27364489782223, 6.40691597760039, 6.61053765625462, 1};
+
+            if (p < 0.5) {
+                t = std::sqrt(-2 * std::log(p));
+            } else {
+                t = std::sqrt(-2 * std::log(q));
+            }
+            s = t - polevl(t, a, 3) / polevl(t, b, 4);
+            if (p < 0.5)
+                s = -s;
+            return s;
+        }
+
+        XSF_HOST_DEVICE inline double didonato_SN(double a, double x, unsigned N, double tolerance) {
+            /*
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             *
+             * See equation 34.
+             */
+            double sum = 1.0;
+
+            if (N >= 1) {
+                unsigned i;
+                double partial = x / (a + 1);
+
+                sum += partial;
+                for (i = 2; i <= N; ++i) {
+                    partial *= x / (a + i);
+                    sum += partial;
+                    if (partial < tolerance) {
+                        break;
+                    }
+                }
+            }
+            return sum;
+        }
+
+        XSF_HOST_DEVICE inline double find_inverse_gamma(double a, double p, double q) {
+            /*
+             * In order to understand what's going on here, you will
+             * need to refer to:
+             *
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             */
+            double result;
+
+            if (a == 1) {
+                if (q > 0.9) {
+                    result = -std::log1p(-p);
+                } else {
+                    result = -std::log(q);
+                }
+            } else if (a < 1) {
+                double g = xsf::cephes::Gamma(a);
+                double b = q * g;
+
+                if ((b > 0.6) || ((b >= 0.45) && (a >= 0.3))) {
+                    /* DiDonato & Morris Eq 21:
+                     *
+                     * There is a slight variation from DiDonato and Morris here:
+                     * the first form given here is unstable when p is close to 1,
+                     * making it impossible to compute the inverse of Q(a,x) for small
+                     * q. Fortunately the second form works perfectly well in this case.
+                     */
+                    double u;
+                    if ((b * q > 1e-8) && (q > 1e-5)) {
+                        u = std::pow(p * g * a, 1 / a);
+                    } else {
+                        u = std::exp((-q / a) - SCIPY_EULER);
+                    }
+                    result = u / (1 - (u / (a + 1)));
+                } else if ((a < 0.3) && (b >= 0.35)) {
+                    /* DiDonato & Morris Eq 22: */
+                    double t = std::exp(-SCIPY_EULER - b);
+                    double u = t * std::exp(t);
+                    result = t * std::exp(u);
+                } else if ((b > 0.15) || (a >= 0.3)) {
+                    /* DiDonato & Morris Eq 23: */
+                    double y = -std::log(b);
+                    double u = y - (1 - a) * std::log(y);
+                    result = y - (1 - a) * std::log(u) - std::log(1 + (1 - a) / (1 + u));
+                } else if (b > 0.1) {
+                    /* DiDonato & Morris Eq 24: */
+                    double y = -std::log(b);
+                    double u = y - (1 - a) * std::log(y);
+                    result = y - (1 - a) * std::log(u) -
+                             std::log((u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) / (u * u + (5 - a) * u + 2));
+                } else {
+                    /* DiDonato & Morris Eq 25: */
+                    double y = -std::log(b);
+                    double c1 = (a - 1) * std::log(y);
+                    double c1_2 = c1 * c1;
+                    double c1_3 = c1_2 * c1;
+                    double c1_4 = c1_2 * c1_2;
+                    double a_2 = a * a;
+                    double a_3 = a_2 * a;
+
+                    double c2 = (a - 1) * (1 + c1);
+                    double c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2);
+                    double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 +
+                                           (11 * a_2 - 46 * a + 47) / 6);
+                    double c5 = (a - 1) * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + (-3 * a_2 + 13 * a - 13) * c1_2 +
+                                           (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 +
+                                           (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12);
+
+                    double y_2 = y * y;
+                    double y_3 = y_2 * y;
+                    double y_4 = y_2 * y_2;
+                    result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4);
+                }
+            } else {
+                /* DiDonato and Morris Eq 31: */
+                double s = find_inverse_s(p, q);
+
+                double s_2 = s * s;
+                double s_3 = s_2 * s;
+                double s_4 = s_2 * s_2;
+                double s_5 = s_4 * s;
+                double ra = std::sqrt(a);
+
+                double w = a + s * ra + (s_2 - 1) / 3;
+                w += (s_3 - 7 * s) / (36 * ra);
+                w -= (3 * s_4 + 7 * s_2 - 16) / (810 * a);
+                w += (9 * s_5 + 256 * s_3 - 433 * s) / (38880 * a * ra);
+
+                if ((a >= 500) && (std::abs(1 - w / a) < 1e-6)) {
+                    result = w;
+                } else if (p > 0.5) {
+                    if (w < 3 * a) {
+                        result = w;
+                    } else {
+                        double D = std::fmax(2, a * (a - 1));
+                        double lg = xsf::cephes::lgam(a);
+                        double lb = std::log(q) + lg;
+                        if (lb < -D * 2.3) {
+                            /* DiDonato and Morris Eq 25: */
+                            double y = -lb;
+                            double c1 = (a - 1) * std::log(y);
+                            double c1_2 = c1 * c1;
+                            double c1_3 = c1_2 * c1;
+                            double c1_4 = c1_2 * c1_2;
+                            double a_2 = a * a;
+                            double a_3 = a_2 * a;
+
+                            double c2 = (a - 1) * (1 + c1);
+                            double c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2);
+                            double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 +
+                                                   (11 * a_2 - 46 * a + 47) / 6);
+                            double c5 =
+                                (a - 1) * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + (-3 * a_2 + 13 * a - 13) * c1_2 +
+                                           (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 +
+                                           (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12);
+
+                            double y_2 = y * y;
+                            double y_3 = y_2 * y;
+                            double y_4 = y_2 * y_2;
+                            result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4);
+                        } else {
+                            /* DiDonato and Morris Eq 33: */
+                            double u = -lb + (a - 1) * std::log(w) - std::log(1 + (1 - a) / (1 + w));
+                            result = -lb + (a - 1) * std::log(u) - std::log(1 + (1 - a) / (1 + u));
+                        }
+                    }
+                } else {
+                    double z = w;
+                    double ap1 = a + 1;
+                    double ap2 = a + 2;
+                    if (w < 0.15 * ap1) {
+                        /* DiDonato and Morris Eq 35: */
+                        double v = std::log(p) + xsf::cephes::lgam(ap1);
+                        z = std::exp((v + w) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2));
+                        z = std::exp((v + z - s) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2));
+                        z = std::exp((v + z - s) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2 * (1 + z / (a + 3))));
+                        z = std::exp((v + z - s) / a);
+                    }
+
+                    if ((z <= 0.01 * ap1) || (z > 0.7 * ap1)) {
+                        result = z;
+                    } else {
+                        /* DiDonato and Morris Eq 36: */
+                        double ls = std::log(didonato_SN(a, z, 100, 1e-4));
+                        double v = std::log(p) + xsf::cephes::lgam(ap1);
+                        z = std::exp((v + z - ls) / a);
+                        result = z * (1 - (a * std::log(z) - z - v + ls) / (a - z));
+                    }
+                }
+            }
+            return result;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double igamci(double a, double q);
+
+    XSF_HOST_DEVICE inline double igami(double a, double p) {
+        int i;
+        double x, fac, f_fp, fpp_fp;
+
+        if (std::isnan(a) || std::isnan(p)) {
+            return std::numeric_limits::quiet_NaN();
+            ;
+        } else if ((a < 0) || (p < 0) || (p > 1)) {
+            set_error("gammaincinv", SF_ERROR_DOMAIN, NULL);
+        } else if (p == 0.0) {
+            return 0.0;
+        } else if (p == 1.0) {
+            return std::numeric_limits::infinity();
+        } else if (p > 0.9) {
+            return igamci(a, 1 - p);
+        }
+
+        x = detail::find_inverse_gamma(a, p, 1 - p);
+        /* Halley's method */
+        for (i = 0; i < 3; i++) {
+            fac = detail::igam_fac(a, x);
+            if (fac == 0.0) {
+                return x;
+            }
+            f_fp = (igam(a, x) - p) * x / fac;
+            /* The ratio of the first and second derivatives simplifies */
+            fpp_fp = -1.0 + (a - 1) / x;
+            if (std::isinf(fpp_fp)) {
+                /* Resort to Newton's method in the case of overflow */
+                x = x - f_fp;
+            } else {
+                x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp);
+            }
+        }
+
+        return x;
+    }
+
+    XSF_HOST_DEVICE inline double igamci(double a, double q) {
+        int i;
+        double x, fac, f_fp, fpp_fp;
+
+        if (std::isnan(a) || std::isnan(q)) {
+            return std::numeric_limits::quiet_NaN();
+        } else if ((a < 0.0) || (q < 0.0) || (q > 1.0)) {
+            set_error("gammainccinv", SF_ERROR_DOMAIN, NULL);
+        } else if (q == 0.0) {
+            return std::numeric_limits::infinity();
+        } else if (q == 1.0) {
+            return 0.0;
+        } else if (q > 0.9) {
+            return igami(a, 1 - q);
+        }
+
+        x = detail::find_inverse_gamma(a, 1 - q, q);
+        for (i = 0; i < 3; i++) {
+            fac = detail::igam_fac(a, x);
+            if (fac == 0.0) {
+                return x;
+            }
+            f_fp = (igamc(a, x) - q) * x / (-fac);
+            fpp_fp = -1.0 + (a - 1) / x;
+            if (std::isinf(fpp_fp)) {
+                x = x - f_fp;
+            } else {
+                x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp);
+            }
+        }
+
+        return x;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h
new file mode 100644
index 0000000000000000000000000000000000000000..29236ef966e05f615920b381489e627950e78740
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h
@@ -0,0 +1,225 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     j0.c
+ *
+ *     Bessel function of order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, j0();
+ *
+ * y = j0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order zero of the argument.
+ *
+ * The domain is divided into the intervals [0, 5] and
+ * (5, infinity). In the first interval the following rational
+ * approximation is used:
+ *
+ *
+ *        2         2
+ * (w - r  ) (w - r  ) P (w) / Q (w)
+ *       1         2    3       8
+ *
+ *            2
+ * where w = x  and the two r's are zeros of the function.
+ *
+ * In the second interval, the Hankel asymptotic expansion
+ * is employed with two rational functions of degree 6/6
+ * and 7/7.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       60000       4.2e-16     1.1e-16
+ *
+ */
+/*							y0.c
+ *
+ *	Bessel function of the second kind, order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, y0();
+ *
+ * y = y0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of the second kind, of order
+ * zero, of the argument.
+ *
+ * The domain is divided into the intervals [0, 5] and
+ * (5, infinity). In the first interval a rational approximation
+ * R(x) is employed to compute
+ *   y0(x)  = R(x)  +   2 * log(x) * j0(x) / M_PI.
+ * Thus a call to j0() is required.
+ *
+ * In the second interval, the Hankel asymptotic expansion
+ * is employed with two rational functions of degree 6/6
+ * and 7/7.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *  Absolute error, when y0(x) < 1; else relative error:
+ *
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.3e-15     1.6e-16
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+
+/* Note: all coefficients satisfy the relative error criterion
+ * except YP, YQ which are designed for absolute error. */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double j0_PP[7] = {
+            7.96936729297347051624E-4, 8.28352392107440799803E-2, 1.23953371646414299388E0,  5.44725003058768775090E0,
+            8.74716500199817011941E0,  5.30324038235394892183E0,  9.99999999999999997821E-1,
+        };
+
+        constexpr double j0_PQ[7] = {
+            9.24408810558863637013E-4, 8.56288474354474431428E-2, 1.25352743901058953537E0, 5.47097740330417105182E0,
+            8.76190883237069594232E0,  5.30605288235394617618E0,  1.00000000000000000218E0,
+        };
+
+        constexpr double j0_QP[8] = {
+            -1.13663838898469149931E-2, -1.28252718670509318512E0, -1.95539544257735972385E1, -9.32060152123768231369E1,
+            -1.77681167980488050595E2,  -1.47077505154951170175E2, -5.14105326766599330220E1, -6.05014350600728481186E0,
+        };
+
+        constexpr double j0_QQ[7] = {
+            /*  1.00000000000000000000E0, */
+            6.43178256118178023184E1, 8.56430025976980587198E2, 3.88240183605401609683E3, 7.24046774195652478189E3,
+            5.93072701187316984827E3, 2.06209331660327847417E3, 2.42005740240291393179E2,
+        };
+
+        constexpr double j0_YP[8] = {
+            1.55924367855235737965E4,   -1.46639295903971606143E7,  5.43526477051876500413E9,
+            -9.82136065717911466409E11, 8.75906394395366999549E13,  -3.46628303384729719441E15,
+            4.42733268572569800351E16,  -1.84950800436986690637E16,
+        };
+
+        constexpr double j0_YQ[7] = {
+            /* 1.00000000000000000000E0, */
+            1.04128353664259848412E3,  6.26107330137134956842E5,  2.68919633393814121987E8,  8.64002487103935000337E10,
+            2.02979612750105546709E13, 3.17157752842975028269E15, 2.50596256172653059228E17,
+        };
+
+        /*  5.783185962946784521175995758455807035071 */
+        constexpr double j0_DR1 = 5.78318596294678452118E0;
+
+        /* 30.47126234366208639907816317502275584842 */
+        constexpr double j0_DR2 = 3.04712623436620863991E1;
+
+        constexpr double j0_RP[4] = {
+            -4.79443220978201773821E9,
+            1.95617491946556577543E12,
+            -2.49248344360967716204E14,
+            9.70862251047306323952E15,
+        };
+
+        constexpr double j0_RQ[8] = {
+            /* 1.00000000000000000000E0, */
+            4.99563147152651017219E2,  1.73785401676374683123E5,  4.84409658339962045305E7,  1.11855537045356834862E10,
+            2.11277520115489217587E12, 3.10518229857422583814E14, 3.18121955943204943306E16, 1.71086294081043136091E18,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double j0(double x) {
+        double w, z, p, q, xn;
+
+        if (x < 0) {
+            x = -x;
+        }
+
+        if (x <= 5.0) {
+            z = x * x;
+            if (x < 1.0e-5) {
+                return (1.0 - z / 4.0);
+            }
+
+            p = (z - detail::j0_DR1) * (z - detail::j0_DR2);
+            p = p * polevl(z, detail::j0_RP, 3) / p1evl(z, detail::j0_RQ, 8);
+            return (p);
+        }
+
+        w = 5.0 / x;
+        q = 25.0 / (x * x);
+        p = polevl(q, detail::j0_PP, 6) / polevl(q, detail::j0_PQ, 6);
+        q = polevl(q, detail::j0_QP, 7) / p1evl(q, detail::j0_QQ, 7);
+        xn = x - M_PI_4;
+        p = p * std::cos(xn) - w * q * std::sin(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+    /*                                                     y0() 2  */
+    /* Bessel function of second kind, order zero  */
+
+    /* Rational approximation coefficients YP[], YQ[] are used here.
+     * The function computed is  y0(x)  -  2 * log(x) * j0(x) / M_PI,
+     * whose value at x = 0 is  2 * ( log(0.5) + EUL ) / M_PI
+     * = 0.073804295108687225.
+     */
+
+    XSF_HOST_DEVICE inline double y0(double x) {
+        double w, z, p, q, xn;
+
+        if (x <= 5.0) {
+            if (x == 0.0) {
+                set_error("y0", SF_ERROR_SINGULAR, NULL);
+                return -std::numeric_limits::infinity();
+            } else if (x < 0.0) {
+                set_error("y0", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            z = x * x;
+            w = polevl(z, detail::j0_YP, 7) / p1evl(z, detail::j0_YQ, 7);
+            w += M_2_PI * std::log(x) * j0(x);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = 25.0 / (x * x);
+        p = polevl(z, detail::j0_PP, 6) / polevl(z, detail::j0_PQ, 6);
+        q = polevl(z, detail::j0_QP, 7) / p1evl(z, detail::j0_QQ, 7);
+        xn = x - M_PI_4;
+        p = p * std::sin(xn) + w * q * std::cos(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h
new file mode 100644
index 0000000000000000000000000000000000000000..46532249550d214723291f7ca9874bb4a31380ac
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h
@@ -0,0 +1,198 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     j1.c
+ *
+ *     Bessel function of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, j1();
+ *
+ * y = j1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order one of the argument.
+ *
+ * The domain is divided into the intervals [0, 8] and
+ * (8, infinity). In the first interval a 24 term Chebyshev
+ * expansion is used. In the second, the asymptotic
+ * trigonometric representation is employed using two
+ * rational functions of degree 5/5.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      0, 30       30000       2.6e-16     1.1e-16
+ *
+ *
+ */
+/*							y1.c
+ *
+ *	Bessel function of second kind of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, y1();
+ *
+ * y = y1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of the second kind of order one
+ * of the argument.
+ *
+ * The domain is divided into the intervals [0, 8] and
+ * (8, infinity). In the first interval a 25 term Chebyshev
+ * expansion is used, and a call to j1() is required.
+ * In the second, the asymptotic trigonometric representation
+ * is employed using two rational functions of degree 5/5.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      0, 30       30000       1.0e-15     1.3e-16
+ *
+ * (error criterion relative when |y1| > 1).
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * #define PIO4 .78539816339744830962
+ * #define THPIO4 2.35619449019234492885
+ * #define SQ2OPI .79788456080286535588
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double j1_RP[4] = {
+            -8.99971225705559398224E8,
+            4.52228297998194034323E11,
+            -7.27494245221818276015E13,
+            3.68295732863852883286E15,
+        };
+
+        constexpr double j1_RQ[8] = {
+            /* 1.00000000000000000000E0, */
+            6.20836478118054335476E2,  2.56987256757748830383E5,  8.35146791431949253037E7,  2.21511595479792499675E10,
+            4.74914122079991414898E12, 7.84369607876235854894E14, 8.95222336184627338078E16, 5.32278620332680085395E18,
+        };
+
+        constexpr double j1_PP[7] = {
+            7.62125616208173112003E-4, 7.31397056940917570436E-2, 1.12719608129684925192E0, 5.11207951146807644818E0,
+            8.42404590141772420927E0,  5.21451598682361504063E0,  1.00000000000000000254E0,
+        };
+
+        constexpr double j1_PQ[7] = {
+            5.71323128072548699714E-4, 6.88455908754495404082E-2, 1.10514232634061696926E0,  5.07386386128601488557E0,
+            8.39985554327604159757E0,  5.20982848682361821619E0,  9.99999999999999997461E-1,
+        };
+
+        constexpr double j1_QP[8] = {
+            5.10862594750176621635E-2, 4.98213872951233449420E0, 7.58238284132545283818E1, 3.66779609360150777800E2,
+            7.10856304998926107277E2,  5.97489612400613639965E2, 2.11688757100572135698E2, 2.52070205858023719784E1,
+        };
+
+        constexpr double j1_QQ[7] = {
+            /* 1.00000000000000000000E0, */
+            7.42373277035675149943E1, 1.05644886038262816351E3, 4.98641058337653607651E3, 9.56231892404756170795E3,
+            7.99704160447350683650E3, 2.82619278517639096600E3, 3.36093607810698293419E2,
+        };
+
+        constexpr double j1_YP[6] = {
+            1.26320474790178026440E9,   -6.47355876379160291031E11, 1.14509511541823727583E14,
+            -8.12770255501325109621E15, 2.02439475713594898196E17,  -7.78877196265950026825E17,
+        };
+
+        constexpr double j1_YQ[8] = {
+            /* 1.00000000000000000000E0, */
+            5.94301592346128195359E2,  2.35564092943068577943E5,  7.34811944459721705660E7,  1.87601316108706159478E10,
+            3.88231277496238566008E12, 6.20557727146953693363E14, 6.87141087355300489866E16, 3.97270608116560655612E18,
+        };
+
+        constexpr double j1_Z1 = 1.46819706421238932572E1;
+        constexpr double j1_Z2 = 4.92184563216946036703E1;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double j1(double x) {
+        double w, z, p, q, xn;
+
+        w = x;
+        if (x < 0) {
+            return -j1(-x);
+        }
+
+        if (w <= 5.0) {
+            z = x * x;
+            w = polevl(z, detail::j1_RP, 3) / p1evl(z, detail::j1_RQ, 8);
+            w = w * x * (z - detail::j1_Z1) * (z - detail::j1_Z2);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = w * w;
+        p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6);
+        q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7);
+        xn = x - detail::THPIO4;
+        p = p * std::cos(xn) - w * q * std::sin(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+    XSF_HOST_DEVICE inline double y1(double x) {
+        double w, z, p, q, xn;
+
+        if (x <= 5.0) {
+            if (x == 0.0) {
+                set_error("y1", SF_ERROR_SINGULAR, NULL);
+                return -std::numeric_limits::infinity();
+            } else if (x <= 0.0) {
+                set_error("y1", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            z = x * x;
+            w = x * (polevl(z, detail::j1_YP, 5) / p1evl(z, detail::j1_YQ, 8));
+            w += M_2_PI * (j1(x) * std::log(x) - 1.0 / x);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = w * w;
+        p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6);
+        q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7);
+        xn = x - detail::THPIO4;
+        p = p * std::sin(xn) + w * q * std::cos(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h
new file mode 100644
index 0000000000000000000000000000000000000000..db5272f27fb4e6619dafaa02f9fc2cd2b2f57f9e
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h
@@ -0,0 +1,715 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     jv.c
+ *
+ *     Bessel function of noninteger order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, jv();
+ *
+ * y = jv( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order v of the argument,
+ * where v is real.  Negative x is allowed if v is an integer.
+ *
+ * Several expansions are included: the ascending power
+ * series, the Hankel expansion, and two transitional
+ * expansions for large v.  If v is not too large, it
+ * is reduced by recurrence to a region of best accuracy.
+ * The transitional expansions give 12D accuracy for v > 500.
+ *
+ *
+ *
+ * ACCURACY:
+ * Results for integer v are indicated by *, where x and v
+ * both vary from -125 to +125.  Otherwise,
+ * x ranges from 0 to 125, v ranges as indicated by "domain."
+ * Error criterion is absolute, except relative when |jv()| > 1.
+ *
+ * arithmetic  v domain  x domain    # trials      peak       rms
+ *    IEEE      0,125     0,125      100000      4.6e-15    2.2e-16
+ *    IEEE   -125,0       0,125       40000      5.4e-11    3.7e-13
+ *    IEEE      0,500     0,500       20000      4.4e-15    4.0e-16
+ * Integer v:
+ *    IEEE   -125,125   -125,125      50000      3.5e-15*   1.9e-16*
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "airy.h"
+#include "cbrt.h"
+#include "rgamma.h"
+#include "j0.h"
+#include "j1.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double jv_BIG = 1.44115188075855872E+17;
+
+        /* Reduce the order by backward recurrence.
+         * AMS55 #9.1.27 and 9.1.73.
+         */
+
+        XSF_HOST_DEVICE inline double jv_recur(double *n, double x, double *newn, int cancel) {
+            double pkm2, pkm1, pk, qkm2, qkm1;
+
+            /* double pkp1; */
+            double k, ans, qk, xk, yk, r, t, kf;
+            constexpr double big = jv_BIG;
+            int nflag, ctr;
+            int miniter, maxiter;
+
+            /* Continued fraction for Jn(x)/Jn-1(x)
+             * AMS 9.1.73
+             *
+             *    x       -x^2      -x^2
+             * ------  ---------  ---------   ...
+             * 2 n +   2(n+1) +   2(n+2) +
+             *
+             * Compute it with the simplest possible algorithm.
+             *
+             * This continued fraction starts to converge when (|n| + m) > |x|.
+             * Hence, at least |x|-|n| iterations are necessary before convergence is
+             * achieved. There is a hard limit set below, m <= 30000, which is chosen
+             * so that no branch in `jv` requires more iterations to converge.
+             * The exact maximum number is (500/3.6)^2 - 500 ~ 19000
+             */
+
+            maxiter = 22000;
+            miniter = std::abs(x) - std::abs(*n);
+            if (miniter < 1) {
+                miniter = 1;
+            }
+
+            if (*n < 0.0) {
+                nflag = 1;
+            } else {
+                nflag = 0;
+            }
+
+        fstart:
+            pkm2 = 0.0;
+            qkm2 = 1.0;
+            pkm1 = x;
+            qkm1 = *n + *n;
+            xk = -x * x;
+            yk = qkm1;
+            ans = 0.0; /* ans=0.0 ensures that t=1.0 in the first iteration */
+            ctr = 0;
+            do {
+                yk += 2.0;
+                pk = pkm1 * yk + pkm2 * xk;
+                qk = qkm1 * yk + qkm2 * xk;
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+
+                /* check convergence */
+                if (qk != 0 && ctr > miniter)
+                    r = pk / qk;
+                else
+                    r = 0.0;
+
+                if (r != 0) {
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else {
+                    t = 1.0;
+                }
+
+                if (++ctr > maxiter) {
+                    set_error("jv", SF_ERROR_UNDERFLOW, NULL);
+                    goto done;
+                }
+                if (t < MACHEP) {
+                    goto done;
+                }
+
+                /* renormalize coefficients */
+                if (std::abs(pk) > big) {
+                    pkm2 /= big;
+                    pkm1 /= big;
+                    qkm2 /= big;
+                    qkm1 /= big;
+                }
+            } while (t > MACHEP);
+
+        done:
+            if (ans == 0)
+                ans = 1.0;
+
+            /* Change n to n-1 if n < 0 and the continued fraction is small */
+            if (nflag > 0) {
+                if (std::abs(ans) < 0.125) {
+                    nflag = -1;
+                    *n = *n - 1.0;
+                    goto fstart;
+                }
+            }
+
+            kf = *newn;
+
+            /* backward recurrence
+             *              2k
+             *  J   (x)  =  --- J (x)  -  J   (x)
+             *   k-1         x   k         k+1
+             */
+
+            pk = 1.0;
+            pkm1 = 1.0 / ans;
+            k = *n - 1.0;
+            r = 2 * k;
+            do {
+                pkm2 = (pkm1 * r - pk * x) / x;
+                /*      pkp1 = pk; */
+                pk = pkm1;
+                pkm1 = pkm2;
+                r -= 2.0;
+                /*
+                 * t = fabs(pkp1) + fabs(pk);
+                 * if( (k > (kf + 2.5)) && (fabs(pkm1) < 0.25*t) )
+                 * {
+                 * k -= 1.0;
+                 * t = x*x;
+                 * pkm2 = ( (r*(r+2.0)-t)*pk - r*x*pkp1 )/t;
+                 * pkp1 = pk;
+                 * pk = pkm1;
+                 * pkm1 = pkm2;
+                 * r -= 2.0;
+                 * }
+                 */
+                k -= 1.0;
+            } while (k > (kf + 0.5));
+
+            /* Take the larger of the last two iterates
+             * on the theory that it may have less cancellation error.
+             */
+
+            if (cancel) {
+                if ((kf >= 0.0) && (std::abs(pk) > std::abs(pkm1))) {
+                    k += 1.0;
+                    pkm2 = pk;
+                }
+            }
+            *newn = k;
+            return (pkm2);
+        }
+
+        /* Ascending power series for Jv(x).
+         * AMS55 #9.1.10.
+         */
+
+        XSF_HOST_DEVICE inline double jv_jvs(double n, double x) {
+            double t, u, y, z, k;
+            int ex, sgngam;
+
+            z = -x * x / 4.0;
+            u = 1.0;
+            y = u;
+            k = 1.0;
+            t = 1.0;
+
+            while (t > MACHEP) {
+                u *= z / (k * (n + k));
+                y += u;
+                k += 1.0;
+                if (y != 0)
+                    t = std::abs(u / y);
+            }
+            t = std::frexp(0.5 * x, &ex);
+            ex = ex * n;
+            if ((ex > -1023) && (ex < 1023) && (n > 0.0) && (n < (MAXGAM - 1.0))) {
+                t = std::pow(0.5 * x, n) * xsf::cephes::rgamma(n + 1.0);
+                y *= t;
+            } else {
+                t = n * std::log(0.5 * x) - lgam_sgn(n + 1.0, &sgngam);
+                if (y < 0) {
+                    sgngam = -sgngam;
+                    y = -y;
+                }
+                t += std::log(y);
+                if (t < -MAXLOG) {
+                    return (0.0);
+                }
+                if (t > MAXLOG) {
+                    set_error("Jv", SF_ERROR_OVERFLOW, NULL);
+                    return (std::numeric_limits::infinity());
+                }
+                y = sgngam * std::exp(t);
+            }
+            return (y);
+        }
+
+        /* Hankel's asymptotic expansion
+         * for large x.
+         * AMS55 #9.2.5.
+         */
+
+        XSF_HOST_DEVICE inline double jv_hankel(double n, double x) {
+            double t, u, z, k, sign, conv;
+            double p, q, j, m, pp, qq;
+            int flag;
+
+            m = 4.0 * n * n;
+            j = 1.0;
+            z = 8.0 * x;
+            k = 1.0;
+            p = 1.0;
+            u = (m - 1.0) / z;
+            q = u;
+            sign = 1.0;
+            conv = 1.0;
+            flag = 0;
+            t = 1.0;
+            pp = 1.0e38;
+            qq = 1.0e38;
+
+            while (t > MACHEP) {
+                k += 2.0;
+                j += 1.0;
+                sign = -sign;
+                u *= (m - k * k) / (j * z);
+                p += sign * u;
+                k += 2.0;
+                j += 1.0;
+                u *= (m - k * k) / (j * z);
+                q += sign * u;
+                t = std::abs(u / p);
+                if (t < conv) {
+                    conv = t;
+                    qq = q;
+                    pp = p;
+                    flag = 1;
+                }
+                /* stop if the terms start getting larger */
+                if ((flag != 0) && (t > conv)) {
+                    goto hank1;
+                }
+            }
+
+        hank1:
+            u = x - (0.5 * n + 0.25) * M_PI;
+            t = std::sqrt(2.0 / (M_PI * x)) * (pp * std::cos(u) - qq * std::sin(u));
+            return (t);
+        }
+
+        /* Asymptotic expansion for transition region,
+         * n large and x close to n.
+         * AMS55 #9.3.23.
+         */
+
+        constexpr double jv_PF2[] = {-9.0000000000000000000e-2, 8.5714285714285714286e-2};
+
+        constexpr double jv_PF3[] = {1.3671428571428571429e-1, -5.4920634920634920635e-2, -4.4444444444444444444e-3};
+
+        constexpr double jv_PF4[] = {1.3500000000000000000e-3, -1.6036054421768707483e-1, 4.2590187590187590188e-2,
+                                     2.7330447330447330447e-3};
+
+        constexpr double jv_PG1[] = {-2.4285714285714285714e-1, 1.4285714285714285714e-2};
+
+        constexpr double jv_PG2[] = {-9.0000000000000000000e-3, 1.9396825396825396825e-1, -1.1746031746031746032e-2};
+
+        constexpr double jv_PG3[] = {1.9607142857142857143e-2, -1.5983694083694083694e-1, 6.3838383838383838384e-3};
+
+        XSF_HOST_DEVICE inline double jv_jnt(double n, double x) {
+            double z, zz, z3;
+            double cbn, n23, cbtwo;
+            double ai, aip, bi, bip; /* Airy functions */
+            double nk, fk, gk, pp, qq;
+            double F[5], G[4];
+            int k;
+
+            cbn = cbrt(n);
+            z = (x - n) / cbn;
+            cbtwo = cbrt(2.0);
+
+            /* Airy function */
+            zz = -cbtwo * z;
+            xsf::cephes::airy(zz, &ai, &aip, &bi, &bip);
+
+            /* polynomials in expansion */
+            zz = z * z;
+            z3 = zz * z;
+            F[0] = 1.0;
+            F[1] = -z / 5.0;
+            F[2] = xsf::cephes::polevl(z3, jv_PF2, 1) * zz;
+            F[3] = xsf::cephes::polevl(z3, jv_PF3, 2);
+            F[4] = xsf::cephes::polevl(z3, jv_PF4, 3) * z;
+            G[0] = 0.3 * zz;
+            G[1] = xsf::cephes::polevl(z3, jv_PG1, 1);
+            G[2] = xsf::cephes::polevl(z3, jv_PG2, 2) * z;
+            G[3] = xsf::cephes::polevl(z3, jv_PG3, 2) * zz;
+
+            pp = 0.0;
+            qq = 0.0;
+            nk = 1.0;
+            n23 = cbrt(n * n);
+
+            for (k = 0; k <= 4; k++) {
+                fk = F[k] * nk;
+                pp += fk;
+                if (k != 4) {
+                    gk = G[k] * nk;
+                    qq += gk;
+                }
+                nk /= n23;
+            }
+
+            fk = cbtwo * ai * pp / cbn + cbrt(4.0) * aip * qq / n;
+            return (fk);
+        }
+
+        /* Asymptotic expansion for large n.
+         * AMS55 #9.3.35.
+         */
+
+        constexpr double jv_lambda[] = {1.0,
+                                        1.041666666666666666666667E-1,
+                                        8.355034722222222222222222E-2,
+                                        1.282265745563271604938272E-1,
+                                        2.918490264641404642489712E-1,
+                                        8.816272674437576524187671E-1,
+                                        3.321408281862767544702647E+0,
+                                        1.499576298686255465867237E+1,
+                                        7.892301301158651813848139E+1,
+                                        4.744515388682643231611949E+2,
+                                        3.207490090890661934704328E+3};
+
+        constexpr double jv_mu[] = {1.0,
+                                    -1.458333333333333333333333E-1,
+                                    -9.874131944444444444444444E-2,
+                                    -1.433120539158950617283951E-1,
+                                    -3.172272026784135480967078E-1,
+                                    -9.424291479571202491373028E-1,
+                                    -3.511203040826354261542798E+0,
+                                    -1.572726362036804512982712E+1,
+                                    -8.228143909718594444224656E+1,
+                                    -4.923553705236705240352022E+2,
+                                    -3.316218568547972508762102E+3};
+
+        constexpr double jv_P1[] = {-2.083333333333333333333333E-1, 1.250000000000000000000000E-1};
+
+        constexpr double jv_P2[] = {3.342013888888888888888889E-1, -4.010416666666666666666667E-1,
+                                    7.031250000000000000000000E-2};
+
+        constexpr double jv_P3[] = {-1.025812596450617283950617E+0, 1.846462673611111111111111E+0,
+                                    -8.912109375000000000000000E-1, 7.324218750000000000000000E-2};
+
+        constexpr double jv_P4[] = {4.669584423426247427983539E+0, -1.120700261622299382716049E+1,
+                                    8.789123535156250000000000E+0, -2.364086914062500000000000E+0,
+                                    1.121520996093750000000000E-1};
+
+        constexpr double jv_P5[] = {-2.8212072558200244877E1, 8.4636217674600734632E1,  -9.1818241543240017361E1,
+                                    4.2534998745388454861E1,  -7.3687943594796316964E0, 2.27108001708984375E-1};
+
+        constexpr double jv_P6[] = {2.1257013003921712286E2,  -7.6525246814118164230E2, 1.0599904525279998779E3,
+                                    -6.9957962737613254123E2, 2.1819051174421159048E2,  -2.6491430486951555525E1,
+                                    5.7250142097473144531E-1};
+
+        constexpr double jv_P7[] = {-1.9194576623184069963E3, 8.0617221817373093845E3,  -1.3586550006434137439E4,
+                                    1.1655393336864533248E4,  -5.3056469786134031084E3, 1.2009029132163524628E3,
+                                    -1.0809091978839465550E2, 1.7277275025844573975E0};
+
+        XSF_HOST_DEVICE inline double jv_jnx(double n, double x) {
+            double zeta, sqz, zz, zp, np;
+            double cbn, n23, t, z, sz;
+            double pp, qq, z32i, zzi;
+            double ak, bk, akl, bkl;
+            int sign, doa, dob, nflg, k, s, tk, tkp1, m;
+            double u[8];
+            double ai, aip, bi, bip;
+
+            /* Test for x very close to n. Use expansion for transition region if so. */
+            cbn = cbrt(n);
+            z = (x - n) / cbn;
+            if (std::abs(z) <= 0.7) {
+                return (jv_jnt(n, x));
+            }
+
+            z = x / n;
+            zz = 1.0 - z * z;
+            if (zz == 0.0) {
+                return (0.0);
+            }
+
+            if (zz > 0.0) {
+                sz = std::sqrt(zz);
+                t = 1.5 * (std::log((1.0 + sz) / z) - sz); /* zeta ** 3/2          */
+                zeta = cbrt(t * t);
+                nflg = 1;
+            } else {
+                sz = std::sqrt(-zz);
+                t = 1.5 * (sz - std::acos(1.0 / z));
+                zeta = -cbrt(t * t);
+                nflg = -1;
+            }
+            z32i = std::abs(1.0 / t);
+            sqz = cbrt(t);
+
+            /* Airy function */
+            n23 = cbrt(n * n);
+            t = n23 * zeta;
+
+            xsf::cephes::airy(t, &ai, &aip, &bi, &bip);
+
+            /* polynomials in expansion */
+            u[0] = 1.0;
+            zzi = 1.0 / zz;
+            u[1] = xsf::cephes::polevl(zzi, jv_P1, 1) / sz;
+            u[2] = xsf::cephes::polevl(zzi, jv_P2, 2) / zz;
+            u[3] = xsf::cephes::polevl(zzi, jv_P3, 3) / (sz * zz);
+            pp = zz * zz;
+            u[4] = xsf::cephes::polevl(zzi, jv_P4, 4) / pp;
+            u[5] = xsf::cephes::polevl(zzi, jv_P5, 5) / (pp * sz);
+            pp *= zz;
+            u[6] = xsf::cephes::polevl(zzi, jv_P6, 6) / pp;
+            u[7] = xsf::cephes::polevl(zzi, jv_P7, 7) / (pp * sz);
+
+            pp = 0.0;
+            qq = 0.0;
+            np = 1.0;
+            /* flags to stop when terms get larger */
+            doa = 1;
+            dob = 1;
+            akl = std::numeric_limits::infinity();
+            bkl = std::numeric_limits::infinity();
+
+            for (k = 0; k <= 3; k++) {
+                tk = 2 * k;
+                tkp1 = tk + 1;
+                zp = 1.0;
+                ak = 0.0;
+                bk = 0.0;
+                for (s = 0; s <= tk; s++) {
+                    if (doa) {
+                        if ((s & 3) > 1)
+                            sign = nflg;
+                        else
+                            sign = 1;
+                        ak += sign * jv_mu[s] * zp * u[tk - s];
+                    }
+
+                    if (dob) {
+                        m = tkp1 - s;
+                        if (((m + 1) & 3) > 1)
+                            sign = nflg;
+                        else
+                            sign = 1;
+                        bk += sign * jv_lambda[s] * zp * u[m];
+                    }
+                    zp *= z32i;
+                }
+
+                if (doa) {
+                    ak *= np;
+                    t = std::abs(ak);
+                    if (t < akl) {
+                        akl = t;
+                        pp += ak;
+                    } else
+                        doa = 0;
+                }
+
+                if (dob) {
+                    bk += jv_lambda[tkp1] * zp * u[0];
+                    bk *= -np / sqz;
+                    t = std::abs(bk);
+                    if (t < bkl) {
+                        bkl = t;
+                        qq += bk;
+                    } else
+                        dob = 0;
+                }
+                if (np < MACHEP)
+                    break;
+                np /= n * n;
+            }
+
+            /* normalizing factor ( 4*zeta/(1 - z**2) )**1/4    */
+            t = 4.0 * zeta / zz;
+            t = sqrt(sqrt(t));
+
+            t *= ai * pp / cbrt(n) + aip * qq / (n23 * n);
+            return (t);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double jv(double n, double x) {
+        double k, q, t, y, an;
+        int i, sign, nint;
+
+        nint = 0; /* Flag for integer n */
+        sign = 1; /* Flag for sign inversion */
+        an = std::abs(n);
+        y = std::floor(an);
+        if (y == an) {
+            nint = 1;
+            i = an - 16384.0 * std::floor(an / 16384.0);
+            if (n < 0.0) {
+                if (i & 1)
+                    sign = -sign;
+                n = an;
+            }
+            if (x < 0.0) {
+                if (i & 1)
+                    sign = -sign;
+                x = -x;
+            }
+            if (n == 0.0)
+                return (j0(x));
+            if (n == 1.0)
+                return (sign * j1(x));
+        }
+
+        if ((x < 0.0) && (y != an)) {
+            set_error("Jv", SF_ERROR_DOMAIN, NULL);
+            y = std::numeric_limits::quiet_NaN();
+            goto done;
+        }
+
+        if (x == 0 && n < 0 && !nint) {
+            set_error("Jv", SF_ERROR_OVERFLOW, NULL);
+            return std::numeric_limits::infinity() * rgamma(n + 1);
+        }
+
+        y = std::abs(x);
+
+        if (y * y < std::abs(n + 1) * detail::MACHEP) {
+            return std::pow(0.5 * x, n) * rgamma(n + 1);
+        }
+
+        k = 3.6 * std::sqrt(y);
+        t = 3.6 * std::sqrt(an);
+        if ((y < t) && (an > 21.0)) {
+            return (sign * detail::jv_jvs(n, x));
+        }
+        if ((an < k) && (y > 21.0))
+            return (sign * detail::jv_hankel(n, x));
+
+        if (an < 500.0) {
+            /* Note: if x is too large, the continued fraction will fail; but then the
+             * Hankel expansion can be used. */
+            if (nint != 0) {
+                k = 0.0;
+                q = detail::jv_recur(&n, x, &k, 1);
+                if (k == 0.0) {
+                    y = j0(x) / q;
+                    goto done;
+                }
+                if (k == 1.0) {
+                    y = j1(x) / q;
+                    goto done;
+                }
+            }
+
+            if (an > 2.0 * y)
+                goto rlarger;
+
+            if ((n >= 0.0) && (n < 20.0) && (y > 6.0) && (y < 20.0)) {
+                /* Recur backwards from a larger value of n */
+            rlarger:
+                k = n;
+
+                y = y + an + 1.0;
+                if (y < 30.0)
+                    y = 30.0;
+                y = n + std::floor(y - n);
+                q = detail::jv_recur(&y, x, &k, 0);
+                y = detail::jv_jvs(y, x) * q;
+                goto done;
+            }
+
+            if (k <= 30.0) {
+                k = 2.0;
+            } else if (k < 90.0) {
+                k = (3 * k) / 4;
+            }
+            if (an > (k + 3.0)) {
+                if (n < 0.0) {
+                    k = -k;
+                }
+                q = n - std::floor(n);
+                k = std::floor(k) + q;
+                if (n > 0.0) {
+                    q = detail::jv_recur(&n, x, &k, 1);
+                } else {
+                    t = k;
+                    k = n;
+                    q = detail::jv_recur(&t, x, &k, 1);
+                    k = t;
+                }
+                if (q == 0.0) {
+                    y = 0.0;
+                    goto done;
+                }
+            } else {
+                k = n;
+                q = 1.0;
+            }
+
+            /* boundary between convergence of
+             * power series and Hankel expansion
+             */
+            y = std::abs(k);
+            if (y < 26.0)
+                t = (0.0083 * y + 0.09) * y + 12.9;
+            else
+                t = 0.9 * y;
+
+            if (x > t)
+                y = detail::jv_hankel(k, x);
+            else
+                y = detail::jv_jvs(k, x);
+            if (n > 0.0)
+                y /= q;
+            else
+                y *= q;
+        }
+
+        else {
+            /* For large n, use the uniform expansion or the transitional expansion.
+             * But if x is of the order of n**2, these may blow up, whereas the
+             * Hankel expansion will then work.
+             */
+            if (n < 0.0) {
+                set_error("jv", SF_ERROR_LOSS, NULL);
+                y = std::numeric_limits::quiet_NaN();
+                goto done;
+            }
+            t = x / n;
+            t /= n;
+            if (t > 0.3)
+                y = detail::jv_hankel(n, x);
+            else
+                y = detail::jv_jnx(n, x);
+        }
+
+    done:
+        return (sign * y);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h
new file mode 100644
index 0000000000000000000000000000000000000000..f617b93c73009072498fe4f6f20671a9f83d84e1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h
@@ -0,0 +1,164 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     k0.c
+ *
+ *     Modified Bessel function, third kind, order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k0();
+ *
+ * y = k0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of the third kind
+ * of order zero of the argument.
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at 2000 random points between 0 and 8.  Peak absolute
+ * error (relative when K0 > 1) was 1.46e-14; rms, 4.26e-15.
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.2e-15     1.6e-16
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ *  K0 domain          x <= 0          INFINITY
+ *
+ */
+/*							k0e()
+ *
+ *	Modified Bessel function, third kind, order zero,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k0e();
+ *
+ * y = k0e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of the third kind of order zero of the argument.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.4e-15     1.4e-16
+ * See k0().
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "chbevl.h"
+#include "i0.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Chebyshev coefficients for K0(x) + log(x/2) I0(x)
+         * in the interval [0,2].  The odd order coefficients are all
+         * zero; only the even order coefficients are listed.
+         *
+         * lim(x->0){ K0(x) + log(x/2) I0(x) } = -EUL.
+         */
+
+        constexpr double k0_A[] = {1.37446543561352307156E-16, 4.25981614279661018399E-14, 1.03496952576338420167E-11,
+                                   1.90451637722020886025E-9,  2.53479107902614945675E-7,  2.28621210311945178607E-5,
+                                   1.26461541144692592338E-3,  3.59799365153615016266E-2,  3.44289899924628486886E-1,
+                                   -5.35327393233902768720E-1};
+
+        /* Chebyshev coefficients for exp(x) sqrt(x) K0(x)
+         * in the inverted interval [2,infinity].
+         *
+         * lim(x->inf){ exp(x) sqrt(x) K0(x) } = sqrt(pi/2).
+         */
+        constexpr double k0_B[] = {
+            5.30043377268626276149E-18,  -1.64758043015242134646E-17, 5.21039150503902756861E-17,
+            -1.67823109680541210385E-16, 5.51205597852431940784E-16,  -1.84859337734377901440E-15,
+            6.34007647740507060557E-15,  -2.22751332699166985548E-14, 8.03289077536357521100E-14,
+            -2.98009692317273043925E-13, 1.14034058820847496303E-12,  -4.51459788337394416547E-12,
+            1.85594911495471785253E-11,  -7.95748924447710747776E-11, 3.57739728140030116597E-10,
+            -1.69753450938905987466E-9,  8.57403401741422608519E-9,   -4.66048989768794782956E-8,
+            2.76681363944501510342E-7,   -1.83175552271911948767E-6,  1.39498137188764993662E-5,
+            -1.28495495816278026384E-4,  1.56988388573005337491E-3,   -3.14481013119645005427E-2,
+            2.44030308206595545468E0};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double k0(double x) {
+        double y, z;
+
+        if (x == 0.0) {
+            set_error("k0", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k0", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = chbevl(y, detail::k0_A, 10) - std::log(0.5 * x) * i0(x);
+            return (y);
+        }
+        z = 8.0 / x - 2.0;
+        y = std::exp(-x) * chbevl(z, detail::k0_B, 25) / std::sqrt(x);
+        return (y);
+    }
+
+    XSF_HOST_DEVICE double inline k0e(double x) {
+        double y;
+
+        if (x == 0.0) {
+            set_error("k0e", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k0e", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = chbevl(y, detail::k0_A, 10) - std::log(0.5 * x) * i0(x);
+            return (y * exp(x));
+        }
+
+        y = chbevl(8.0 / x - 2.0, detail::k0_B, 25) / std::sqrt(x);
+        return (y);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h
new file mode 100644
index 0000000000000000000000000000000000000000..96594fd9c345e6fd2ecf02a269601cd2d9592525
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h
@@ -0,0 +1,163 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     k1.c
+ *
+ *     Modified Bessel function, third kind, order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k1();
+ *
+ * y = k1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Computes the modified Bessel function of the third kind
+ * of order one of the argument.
+ *
+ * The range is partitioned into the two intervals [0,2] and
+ * (2, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.2e-15     1.6e-16
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * k1 domain          x <= 0          INFINITY
+ *
+ */
+/*							k1e.c
+ *
+ *	Modified Bessel function, third kind, order one,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k1e();
+ *
+ * y = k1e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of the third kind of order one of the argument:
+ *
+ *      k1e(x) = exp(x) * k1(x).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       7.8e-16     1.2e-16
+ * See k1().
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "chbevl.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Chebyshev coefficients for x(K1(x) - log(x/2) I1(x))
+         * in the interval [0,2].
+         *
+         * lim(x->0){ x(K1(x) - log(x/2) I1(x)) } = 1.
+         */
+
+        constexpr double k1_A[] = {
+            -7.02386347938628759343E-18, -2.42744985051936593393E-15, -6.66690169419932900609E-13,
+            -1.41148839263352776110E-10, -2.21338763073472585583E-8,  -2.43340614156596823496E-6,
+            -1.73028895751305206302E-4,  -6.97572385963986435018E-3,  -1.22611180822657148235E-1,
+            -3.53155960776544875667E-1,  1.52530022733894777053E0};
+
+        /* Chebyshev coefficients for exp(x) sqrt(x) K1(x)
+         * in the interval [2,infinity].
+         *
+         * lim(x->inf){ exp(x) sqrt(x) K1(x) } = sqrt(pi/2).
+         */
+        constexpr double k1_B[] = {
+            -5.75674448366501715755E-18, 1.79405087314755922667E-17,  -5.68946255844285935196E-17,
+            1.83809354436663880070E-16,  -6.05704724837331885336E-16, 2.03870316562433424052E-15,
+            -7.01983709041831346144E-15, 2.47715442448130437068E-14,  -8.97670518232499435011E-14,
+            3.34841966607842919884E-13,  -1.28917396095102890680E-12, 5.13963967348173025100E-12,
+            -2.12996783842756842877E-11, 9.21831518760500529508E-11,  -4.19035475934189648750E-10,
+            2.01504975519703286596E-9,   -1.03457624656780970260E-8,  5.74108412545004946722E-8,
+            -3.50196060308781257119E-7,  2.40648494783721712015E-6,   -1.93619797416608296024E-5,
+            1.95215518471351631108E-4,   -2.85781685962277938680E-3,  1.03923736576817238437E-1,
+            2.72062619048444266945E0};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double k1(double x) {
+        double y, z;
+
+        if (x == 0.0) {
+            set_error("k1", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k1", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        z = 0.5 * x;
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = std::log(z) * i1(x) + chbevl(y, detail::k1_A, 11) / x;
+            return (y);
+        }
+
+        return (std::exp(-x) * chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x));
+    }
+
+    XSF_HOST_DEVICE double k1e(double x) {
+        double y;
+
+        if (x == 0.0) {
+            set_error("k1e", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k1e", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = std::log(0.5 * x) * i1(x) + chbevl(y, detail::k1_A, 11) / x;
+            return (y * exp(x));
+        }
+
+        return (chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h
new file mode 100644
index 0000000000000000000000000000000000000000..31bc9fd7f735002f3381749f8d14c02545155c69
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h
@@ -0,0 +1,243 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     kn.c
+ *
+ *     Modified Bessel function, third kind, integer order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, kn();
+ * int n;
+ *
+ * y = kn( n, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of the third kind
+ * of order n of the argument.
+ *
+ * The range is partitioned into the two intervals [0,9.55] and
+ * (9.55, infinity).  An ascending power series is used in the
+ * low range, and an asymptotic expansion in the high range.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        90000       1.8e-8      3.0e-10
+ *
+ *  Error is high only near the crossover point x = 9.55
+ * between the two expansions used.
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * Algorithm for Kn.
+ *                        n-1
+ *                    -n   -  (n-k-1)!    2   k
+ * K (x)  =  0.5 (x/2)     >  -------- (-x /4)
+ *  n                      -     k!
+ *                        k=0
+ *
+ *                     inf.                                   2   k
+ *        n         n   -                                   (x /4)
+ *  + (-1)  0.5(x/2)    >  {p(k+1) + p(n+k+1) - 2log(x/2)} ---------
+ *                      -                                  k! (n+k)!
+ *                     k=0
+ *
+ * where  p(m) is the psi function: p(1) = -EUL and
+ *
+ *                       m-1
+ *                        -
+ *       p(m)  =  -EUL +  >  1/k
+ *                        -
+ *                       k=1
+ *
+ * For large x,
+ *                                          2        2     2
+ *                                       u-1     (u-1 )(u-3 )
+ * K (z)  =  sqrt(pi/2z) exp(-z) { 1 + ------- + ------------ + ...}
+ *  v                                        1            2
+ *                                     1! (8z)     2! (8z)
+ * asymptotically, where
+ *
+ *            2
+ *     u = 4 v .
+ *
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int kn_MAXFAC = 31;
+
+    }
+
+    XSF_HOST_DEVICE inline double kn(int nn, double x) {
+        double k, kf, nk1f, nkf, zn, t, s, z0, z;
+        double ans, fn, pn, pk, zmn, tlg, tox;
+        int i, n;
+
+        if (nn < 0)
+            n = -nn;
+        else
+            n = nn;
+
+        if (n > detail::kn_MAXFAC) {
+        overf:
+            set_error("kn", SF_ERROR_OVERFLOW, NULL);
+            return (std::numeric_limits::infinity());
+        }
+
+        if (x <= 0.0) {
+            if (x < 0.0) {
+                set_error("kn", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            } else {
+                set_error("kn", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+
+        if (x > 9.55)
+            goto asymp;
+
+        ans = 0.0;
+        z0 = 0.25 * x * x;
+        fn = 1.0;
+        pn = 0.0;
+        zmn = 1.0;
+        tox = 2.0 / x;
+
+        if (n > 0) {
+            /* compute factorial of n and psi(n) */
+            pn = -detail::SCIPY_EULER;
+            k = 1.0;
+            for (i = 1; i < n; i++) {
+                pn += 1.0 / k;
+                k += 1.0;
+                fn *= k;
+            }
+
+            zmn = tox;
+
+            if (n == 1) {
+                ans = 1.0 / x;
+            } else {
+                nk1f = fn / n;
+                kf = 1.0;
+                s = nk1f;
+                z = -z0;
+                zn = 1.0;
+                for (i = 1; i < n; i++) {
+                    nk1f = nk1f / (n - i);
+                    kf = kf * i;
+                    zn *= z;
+                    t = nk1f * zn / kf;
+                    s += t;
+                    if ((std::numeric_limits::max() - std::abs(t)) < std::abs(s)) {
+                        goto overf;
+                    }
+                    if ((tox > 1.0) && ((std::numeric_limits::max() / tox) < zmn)) {
+                        goto overf;
+                    }
+                    zmn *= tox;
+                }
+                s *= 0.5;
+                t = std::abs(s);
+                if ((zmn > 1.0) && ((std::numeric_limits::max() / zmn) < t)) {
+                    goto overf;
+                }
+                if ((t > 1.0) && ((std::numeric_limits::max() / t) < zmn)) {
+                    goto overf;
+                }
+                ans = s * zmn;
+            }
+        }
+
+        tlg = 2.0 * log(0.5 * x);
+        pk = -detail::SCIPY_EULER;
+        if (n == 0) {
+            pn = pk;
+            t = 1.0;
+        } else {
+            pn = pn + 1.0 / n;
+            t = 1.0 / fn;
+        }
+        s = (pk + pn - tlg) * t;
+        k = 1.0;
+        do {
+            t *= z0 / (k * (k + n));
+            pk += 1.0 / k;
+            pn += 1.0 / (k + n);
+            s += (pk + pn - tlg) * t;
+            k += 1.0;
+        } while (fabs(t / s) > detail::MACHEP);
+
+        s = 0.5 * s / zmn;
+        if (n & 1) {
+            s = -s;
+        }
+        ans += s;
+
+        return (ans);
+
+        /* Asymptotic expansion for Kn(x) */
+        /* Converges to 1.4e-17 for x > 18.4 */
+
+    asymp:
+
+        if (x > detail::MAXLOG) {
+            set_error("kn", SF_ERROR_UNDERFLOW, NULL);
+            return (0.0);
+        }
+        k = n;
+        pn = 4.0 * k * k;
+        pk = 1.0;
+        z0 = 8.0 * x;
+        fn = 1.0;
+        t = 1.0;
+        s = t;
+        nkf = std::numeric_limits::infinity();
+        i = 0;
+        do {
+            z = pn - pk * pk;
+            t = t * z / (fn * z0);
+            nk1f = std::abs(t);
+            if ((i >= n) && (nk1f > nkf)) {
+                goto adone;
+            }
+            nkf = nk1f;
+            s += t;
+            fn += 1.0;
+            pk += 2.0;
+            i += 1;
+        } while (std::abs(t / s) > detail::MACHEP);
+
+    adone:
+        ans = std::exp(-x) * std::sqrt(M_PI / (2.0 * x)) * s;
+        return (ans);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h
new file mode 100644
index 0000000000000000000000000000000000000000..a8cbbe1d693f99e96d74cd40a1a15e32b8035871
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h
@@ -0,0 +1,112 @@
+/*  (C) Copyright John Maddock 2006.
+ *  Use, modification and distribution are subject to the
+ *  Boost Software License, Version 1.0. (See accompanying file
+ *  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+
+/* Both lanczos.h and lanczos.c were formed from Boost's lanczos.hpp
+ *
+ * Scipy changes:
+ * - 06-22-2016: Removed all code not related to double precision and
+ *   ported to c for use in Cephes. Note that the order of the
+ *   coefficients is reversed to match the behavior of polevl.
+ */
+
+/*
+ * Optimal values for G for each N are taken from
+ * https://web.viu.ca/pughg/phdThesis/phdThesis.pdf,
+ * as are the theoretical error bounds.
+ *
+ * Constants calculated using the method described by Godfrey
+ * https://my.fit.edu/~gabdo/gamma.txt and elaborated by Toth at
+ * https://www.rskey.org/gamma.htm using NTL::RR at 1000 bit precision.
+ */
+
+/*
+ * Lanczos Coefficients for N=13 G=6.024680040776729583740234375
+ * Max experimental error (with arbitrary precision arithmetic) 1.196214e-17
+ * Generated with compiler: Microsoft Visual C++ version 8.0 on Win32 at Mar 23 2006
+ *
+ * Use for double precision.
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double lanczos_num[] = {
+            2.506628274631000270164908177133837338626, 210.8242777515793458725097339207133627117,
+            8071.672002365816210638002902272250613822, 186056.2653952234950402949897160456992822,
+            2876370.628935372441225409051620849613599, 31426415.58540019438061423162831820536287,
+            248874557.8620541565114603864132294232163, 1439720407.311721673663223072794912393972,
+            6039542586.35202800506429164430729792107,  17921034426.03720969991975575445893111267,
+            35711959237.35566804944018545154716670596, 42919803642.64909876895789904700198885093,
+            23531376880.41075968857200767445163675473};
+
+        constexpr double lanczos_denom[] = {1,        66,        1925,      32670,     357423,   2637558, 13339535,
+                                            45995730, 105258076, 150917976, 120543840, 39916800, 0};
+
+        constexpr double lanczos_sum_expg_scaled_num[] = {
+            0.006061842346248906525783753964555936883222, 0.5098416655656676188125178644804694509993,
+            19.51992788247617482847860966235652136208,    449.9445569063168119446858607650988409623,
+            6955.999602515376140356310115515198987526,    75999.29304014542649875303443598909137092,
+            601859.6171681098786670226533699352302507,    3481712.15498064590882071018964774556468,
+            14605578.08768506808414169982791359218571,    43338889.32467613834773723740590533316085,
+            86363131.28813859145546927288977868422342,    103794043.1163445451906271053616070238554,
+            56906521.91347156388090791033559122686859};
+
+        constexpr double lanczos_sum_expg_scaled_denom[] = {
+            1, 66, 1925, 32670, 357423, 2637558, 13339535, 45995730, 105258076, 150917976, 120543840, 39916800, 0};
+
+        constexpr double lanczos_sum_near_1_d[] = {
+            0.3394643171893132535170101292240837927725e-9,  -0.2499505151487868335680273909354071938387e-8,
+            0.8690926181038057039526127422002498960172e-8,  -0.1933117898880828348692541394841204288047e-7,
+            0.3075580174791348492737947340039992829546e-7,  -0.2752907702903126466004207345038327818713e-7,
+            -0.1515973019871092388943437623825208095123e-5, 0.004785200610085071473880915854204301886437,
+            -0.1993758927614728757314233026257810172008,    1.483082862367253753040442933770164111678,
+            -3.327150580651624233553677113928873034916,     2.208709979316623790862569924861841433016};
+
+        constexpr double lanczos_sum_near_2_d[] = {
+            0.1009141566987569892221439918230042368112e-8,  -0.7430396708998719707642735577238449585822e-8,
+            0.2583592566524439230844378948704262291927e-7,  -0.5746670642147041587497159649318454348117e-7,
+            0.9142922068165324132060550591210267992072e-7,  -0.8183698410724358930823737982119474130069e-7,
+            -0.4506604409707170077136555010018549819192e-5, 0.01422519127192419234315002746252160965831,
+            -0.5926941084905061794445733628891024027949,    4.408830289125943377923077727900630927902,
+            -9.8907772644920670589288081640128194231,       6.565936202082889535528455955485877361223};
+
+        XSF_HOST_DEVICE double lanczos_sum(double x) { return ratevl(x, lanczos_num, 12, lanczos_denom, 12); }
+
+        XSF_HOST_DEVICE double lanczos_sum_near_1(double dx) {
+            double result = 0;
+            unsigned k;
+
+            for (k = 1; k <= 12; ++k) {
+                result += (-lanczos_sum_near_1_d[k - 1] * dx) / (k * dx + k * k);
+            }
+            return result;
+        }
+
+        XSF_HOST_DEVICE double lanczos_sum_near_2(double dx) {
+            double result = 0;
+            double x = dx + 2;
+            unsigned k;
+
+            for (k = 1; k <= 12; ++k) {
+                result += (-lanczos_sum_near_2_d[k - 1] * dx) / (x + k * x + k * k - 1);
+            }
+            return result;
+        }
+    } // namespace detail
+
+    constexpr double lanczos_g = 6.024680040776729583740234375;
+    XSF_HOST_DEVICE double lanczos_sum_expg_scaled(double x) {
+        return ratevl(x, detail::lanczos_sum_expg_scaled_num, 12, detail::lanczos_sum_expg_scaled_denom, 12);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h
new file mode 100644
index 0000000000000000000000000000000000000000..a3611d26ba44a78ab69736f9c69fe5dd4d2bc538
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h
@@ -0,0 +1,275 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ndtr.c
+ *
+ *     Normal distribution function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, ndtr();
+ *
+ * y = ndtr( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the Gaussian probability density
+ * function, integrated from minus infinity to x:
+ *
+ *                            x
+ *                             -
+ *                   1        | |          2
+ *    ndtr(x)  = ---------    |    exp( - t /2 ) dt
+ *               sqrt(2pi)  | |
+ *                           -
+ *                          -inf.
+ *
+ *             =  ( 1 + erf(z) ) / 2
+ *             =  erfc(z) / 2
+ *
+ * where z = x/sqrt(2). Computation is via the functions
+ * erf and erfc.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -13,0        30000       3.4e-14     6.7e-15
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition         value returned
+ * erfc underflow    x > 37.519379347       0.0
+ *
+ */
+/*							erf.c
+ *
+ *	Error function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, erf();
+ *
+ * y = erf( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * The integral is
+ *
+ *                           x
+ *                            -
+ *                 2         | |          2
+ *   erf(x)  =  --------     |    exp( - t  ) dt.
+ *              sqrt(pi)   | |
+ *                          -
+ *                           0
+ *
+ * For 0 <= |x| < 1, erf(x) = x * P4(x**2)/Q5(x**2); otherwise
+ * erf(x) = 1 - erfc(x).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,1         30000       3.7e-16     1.0e-16
+ *
+ */
+/*							erfc.c
+ *
+ *	Complementary error function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, erfc();
+ *
+ * y = erfc( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *  1 - erf(x) =
+ *
+ *                           inf.
+ *                             -
+ *                  2         | |          2
+ *   erfc(x)  =  --------     |    exp( - t  ) dt
+ *               sqrt(pi)   | |
+ *                           -
+ *                            x
+ *
+ *
+ * For small x, erfc(x) = 1 - erf(x); otherwise rational
+ * approximations are computed.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,26.6417   30000       5.7e-14     1.5e-14
+ */
+
+/*
+ * Cephes Math Library Release 2.2:  June, 1992
+ * Copyright 1984, 1987, 1988, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ndtr_P[] = {2.46196981473530512524E-10, 5.64189564831068821977E-1, 7.46321056442269912687E0,
+                                     4.86371970985681366614E1,   1.96520832956077098242E2,  5.26445194995477358631E2,
+                                     9.34528527171957607540E2,   1.02755188689515710272E3,  5.57535335369399327526E2};
+
+        constexpr double ndtr_Q[] = {
+            /* 1.00000000000000000000E0, */
+            1.32281951154744992508E1, 8.67072140885989742329E1, 3.54937778887819891062E2, 9.75708501743205489753E2,
+            1.82390916687909736289E3, 2.24633760818710981792E3, 1.65666309194161350182E3, 5.57535340817727675546E2};
+
+        constexpr double ndtr_R[] = {5.64189583547755073984E-1, 1.27536670759978104416E0, 5.01905042251180477414E0,
+                                     6.16021097993053585195E0,  7.40974269950448939160E0, 2.97886665372100240670E0};
+
+        constexpr double ndtr_S[] = {
+            /* 1.00000000000000000000E0, */
+            2.26052863220117276590E0, 9.39603524938001434673E0, 1.20489539808096656605E1,
+            1.70814450747565897222E1, 9.60896809063285878198E0, 3.36907645100081516050E0};
+
+        constexpr double ndtr_T[] = {9.60497373987051638749E0, 9.00260197203842689217E1, 2.23200534594684319226E3,
+                                     7.00332514112805075473E3, 5.55923013010394962768E4};
+
+        constexpr double ndtr_U[] = {
+            /* 1.00000000000000000000E0, */
+            3.35617141647503099647E1, 5.21357949780152679795E2, 4.59432382970980127987E3, 2.26290000613890934246E4,
+            4.92673942608635921086E4};
+
+        constexpr double ndtri_UTHRESH = 37.519379347;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double erf(double x);
+
+    XSF_HOST_DEVICE inline double erfc(double a) {
+        double p, q, x, y, z;
+
+        if (std::isnan(a)) {
+            set_error("erfc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (a < 0.0) {
+            x = -a;
+        } else {
+            x = a;
+        }
+
+        if (x < 1.0) {
+            return 1.0 - erf(a);
+        }
+
+        z = -a * a;
+
+        if (z < -detail::MAXLOG) {
+            goto under;
+        }
+
+        z = std::exp(z);
+
+        if (x < 8.0) {
+            p = polevl(x, detail::ndtr_P, 8);
+            q = p1evl(x, detail::ndtr_Q, 8);
+        } else {
+            p = polevl(x, detail::ndtr_R, 5);
+            q = p1evl(x, detail::ndtr_S, 6);
+        }
+        y = (z * p) / q;
+
+        if (a < 0) {
+            y = 2.0 - y;
+        }
+
+        if (y != 0.0) {
+            return y;
+        }
+
+    under:
+        set_error("erfc", SF_ERROR_UNDERFLOW, NULL);
+        if (a < 0) {
+            return 2.0;
+        } else {
+            return 0.0;
+        }
+    }
+
+    XSF_HOST_DEVICE inline double erf(double x) {
+        double y, z;
+
+        if (std::isnan(x)) {
+            set_error("erf", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x < 0.0) {
+            return -erf(-x);
+        }
+
+        if (std::abs(x) > 1.0) {
+            return (1.0 - erfc(x));
+        }
+        z = x * x;
+
+        y = x * polevl(z, detail::ndtr_T, 4) / p1evl(z, detail::ndtr_U, 5);
+        return y;
+    }
+
+    XSF_HOST_DEVICE inline double ndtr(double a) {
+        double x, y, z;
+
+        if (std::isnan(a)) {
+            set_error("ndtr", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        x = a * M_SQRT1_2;
+        z = std::abs(x);
+
+        if (z < 1.0) {
+            y = 0.5 + 0.5 * erf(x);
+        } else {
+            y = 0.5 * erfc(z);
+            if (x > 0) {
+                y = 1.0 - y;
+            }
+        }
+
+        return y;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h
new file mode 100644
index 0000000000000000000000000000000000000000..add3a995f38870cad5155b5fda1730e4fcbf1ee3
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h
@@ -0,0 +1,85 @@
+/*
+ * Pochhammer symbol (a)_m = gamma(a + m) / gamma(a)
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "gamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        XSF_HOST_DEVICE inline double is_nonpos_int(double x) {
+            return x <= 0 && x == std::ceil(x) && std::abs(x) < 1e13;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double poch(double a, double m) {
+        double r = 1.0;
+
+        /*
+         * 1. Reduce magnitude of `m` to |m| < 1 by using recurrence relations.
+         *
+         * This may end up in over/underflow, but then the function itself either
+         * diverges or goes to zero. In case the remainder goes to the opposite
+         * direction, we end up returning 0*INF = NAN, which is OK.
+         */
+
+        /* Recurse down */
+        while (m >= 1.0) {
+            if (a + m == 1) {
+                break;
+            }
+            m -= 1.0;
+            r *= (a + m);
+            if (!std::isfinite(r) || r == 0) {
+                break;
+            }
+        }
+
+        /* Recurse up */
+        while (m <= -1.0) {
+            if (a + m == 0) {
+                break;
+            }
+            r /= (a + m);
+            m += 1.0;
+            if (!std::isfinite(r) || r == 0) {
+                break;
+            }
+        }
+
+        /*
+         * 2. Evaluate function with reduced `m`
+         *
+         * Now either `m` is not big, or the `r` product has over/underflown.
+         * If so, the function itself does similarly.
+         */
+
+        if (m == 0) {
+            /* Easy case */
+            return r;
+        } else if (a > 1e4 && std::abs(m) <= 1) {
+            /* Avoid loss of precision */
+            return r * std::pow(a, m) *
+                   (1 + m * (m - 1) / (2 * a) + m * (m - 1) * (m - 2) * (3 * m - 1) / (24 * a * a) +
+                    m * m * (m - 1) * (m - 1) * (m - 2) * (m - 3) / (48 * a * a * a));
+        }
+
+        /* Check for infinity */
+        if (detail::is_nonpos_int(a + m) && !detail::is_nonpos_int(a) && a + m != m) {
+            return std::numeric_limits::infinity();
+        }
+
+        /* Check for zero */
+        if (!detail::is_nonpos_int(a + m) && detail::is_nonpos_int(a)) {
+            return 0;
+        }
+
+        return r * std::exp(lgam(a + m) - lgam(a)) * gammasgn(a + m) * gammasgn(a);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h
new file mode 100644
index 0000000000000000000000000000000000000000..912a506cfb6c0d5fe75ead2d14576ddd57698788
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h
@@ -0,0 +1,167 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     polevl.c
+ *                                                     p1evl.c
+ *
+ *     Evaluate polynomial
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int N;
+ * double x, y, coef[N+1], polevl[];
+ *
+ * y = polevl( x, coef, N );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates polynomial of degree N:
+ *
+ *                     2          N
+ * y  =  C  + C x + C x  +...+ C x
+ *        0    1     2          N
+ *
+ * Coefficients are stored in reverse order:
+ *
+ * coef[0] = C  , ..., coef[N] = C  .
+ *            N                   0
+ *
+ * The function p1evl() assumes that c_N = 1.0 so that coefficent
+ * is omitted from the array.  Its calling arguments are
+ * otherwise the same as polevl().
+ *
+ *
+ * SPEED:
+ *
+ * In the interest of speed, there are no checks for out
+ * of bounds arithmetic.  This routine is used by most of
+ * the functions in the library.  Depending on available
+ * equipment features, the user may wish to rewrite the
+ * program in microcode or assembly language.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.1:  December, 1988
+ * Copyright 1984, 1987, 1988 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+
+/* Sources:
+ * [1] Holin et. al., "Polynomial and Rational Function Evaluation",
+ *     https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/roots/rational.html
+ */
+
+/* Scipy changes:
+ * - 06-23-2016: add code for evaluating rational functions
+ */
+
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+    XSF_HOST_DEVICE inline double polevl(double x, const double coef[], int N) {
+        double ans;
+        int i;
+        const double *p;
+
+        p = coef;
+        ans = *p++;
+        i = N;
+
+        do {
+            ans = ans * x + *p++;
+        } while (--i);
+
+        return (ans);
+    }
+
+    /*                                                     p1evl() */
+    /*                                          N
+     * Evaluate polynomial when coefficient of x  is 1.0.
+     * That is, C_{N} is assumed to be 1, and that coefficient
+     * is not included in the input array coef.
+     * coef must have length N and contain the polynomial coefficients
+     * stored as
+     *     coef[0] = C_{N-1}
+     *     coef[1] = C_{N-2}
+     *          ...
+     *     coef[N-2] = C_1
+     *     coef[N-1] = C_0
+     * Otherwise same as polevl.
+     */
+
+    XSF_HOST_DEVICE inline double p1evl(double x, const double coef[], int N) {
+        double ans;
+        const double *p;
+        int i;
+
+        p = coef;
+        ans = x + *p++;
+        i = N - 1;
+
+        do
+            ans = ans * x + *p++;
+        while (--i);
+
+        return (ans);
+    }
+
+    /* Evaluate a rational function. See [1]. */
+
+    /* The function ratevl is only used once in cephes/lanczos.h. */
+    XSF_HOST_DEVICE inline double ratevl(double x, const double num[], int M, const double denom[], int N) {
+        int i, dir;
+        double y, num_ans, denom_ans;
+        double absx = std::abs(x);
+        const double *p;
+
+        if (absx > 1) {
+            /* Evaluate as a polynomial in 1/x. */
+            dir = -1;
+            p = num + M;
+            y = 1 / x;
+        } else {
+            dir = 1;
+            p = num;
+            y = x;
+        }
+
+        /* Evaluate the numerator */
+        num_ans = *p;
+        p += dir;
+        for (i = 1; i <= M; i++) {
+            num_ans = num_ans * y + *p;
+            p += dir;
+        }
+
+        /* Evaluate the denominator */
+        if (absx > 1) {
+            p = denom + N;
+        } else {
+            p = denom;
+        }
+
+        denom_ans = *p;
+        p += dir;
+        for (i = 1; i <= N; i++) {
+            denom_ans = denom_ans * y + *p;
+            p += dir;
+        }
+
+        if (absx > 1) {
+            i = M - N;
+            return std::pow(x, i) * num_ans / denom_ans;
+        } else {
+            return num_ans / denom_ans;
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h
new file mode 100644
index 0000000000000000000000000000000000000000..c028e9ea14e0066c3b8c13d2c26c2773e61f767a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h
@@ -0,0 +1,194 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     psi.c
+ *
+ *     Psi (digamma) function
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, psi();
+ *
+ * y = psi( x );
+ *
+ *
+ * DESCRIPTION:
+ *
+ *              d      -
+ *   psi(x)  =  -- ln | (x)
+ *              dx
+ *
+ * is the logarithmic derivative of the gamma function.
+ * For integer x,
+ *                   n-1
+ *                    -
+ * psi(n) = -EUL  +   >  1/k.
+ *                    -
+ *                   k=1
+ *
+ * This formula is used for 0 < n <= 10.  If x is negative, it
+ * is transformed to a positive argument by the reflection
+ * formula  psi(1-x) = psi(x) + pi cot(pi x).
+ * For general positive x, the argument is made greater than 10
+ * using the recurrence  psi(x+1) = psi(x) + 1/x.
+ * Then the following asymptotic expansion is applied:
+ *
+ *                           inf.   B
+ *                            -      2k
+ * psi(x) = log(x) - 1/2x -   >   -------
+ *                            -        2k
+ *                           k=1   2k x
+ *
+ * where the B2k are Bernoulli numbers.
+ *
+ * ACCURACY:
+ *    Relative error (except absolute when |psi| < 1):
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       1.3e-15     1.4e-16
+ *    IEEE      -30,0       40000       1.5e-15     2.2e-16
+ *
+ * ERROR MESSAGES:
+ *     message         condition      value returned
+ * psi singularity    x integer <=0      INFINITY
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * Code for the rational approximation on [1, 2] is:
+ *
+ * (C) Copyright John Maddock 2006.
+ * Use, modification and distribution are subject to the
+ * Boost Software License, Version 1.0. (See accompanying file
+ * LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr double psi_A[] = {8.33333333333333333333E-2,  -2.10927960927960927961E-2, 7.57575757575757575758E-3,
+                                    -4.16666666666666666667E-3, 3.96825396825396825397E-3,  -8.33333333333333333333E-3,
+                                    8.33333333333333333333E-2};
+
+        constexpr float psi_Y = 0.99558162689208984f;
+
+        constexpr double psi_root1 = 1569415565.0 / 1073741824.0;
+        constexpr double psi_root2 = (381566830.0 / 1073741824.0) / 1073741824.0;
+        constexpr double psi_root3 = 0.9016312093258695918615325266959189453125e-19;
+
+        constexpr double psi_P[] = {-0.0020713321167745952, -0.045251321448739056, -0.28919126444774784,
+                                    -0.65031853770896507,   -0.32555031186804491,  0.25479851061131551};
+        constexpr double psi_Q[] = {-0.55789841321675513e-6,
+                                    0.0021284987017821144,
+                                    0.054151797245674225,
+                                    0.43593529692665969,
+                                    1.4606242909763515,
+                                    2.0767117023730469,
+                                    1.0};
+
+        XSF_HOST_DEVICE double digamma_imp_1_2(double x) {
+            /*
+             * Rational approximation on [1, 2] taken from Boost.
+             *
+             * Now for the approximation, we use the form:
+             *
+             * digamma(x) = (x - root) * (Y + R(x-1))
+             *
+             * Where root is the location of the positive root of digamma,
+             * Y is a constant, and R is optimised for low absolute error
+             * compared to Y.
+             *
+             * Maximum Deviation Found:               1.466e-18
+             * At double precision, max error found:  2.452e-17
+             */
+            double r, g;
+
+            g = x - psi_root1;
+            g -= psi_root2;
+            g -= psi_root3;
+            r = xsf::cephes::polevl(x - 1.0, psi_P, 5) / xsf::cephes::polevl(x - 1.0, psi_Q, 6);
+
+            return g * psi_Y + g * r;
+        }
+
+        XSF_HOST_DEVICE double psi_asy(double x) {
+            double y, z;
+
+            if (x < 1.0e17) {
+                z = 1.0 / (x * x);
+                y = z * xsf::cephes::polevl(z, psi_A, 6);
+            } else {
+                y = 0.0;
+            }
+
+            return std::log(x) - (0.5 / x) - y;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double psi(double x) {
+        double y = 0.0;
+        double q, r;
+        int i, n;
+
+        if (std::isnan(x)) {
+            return x;
+        } else if (x == std::numeric_limits::infinity()) {
+            return x;
+        } else if (x == -std::numeric_limits::infinity()) {
+            return std::numeric_limits::quiet_NaN();
+        } else if (x == 0) {
+            set_error("psi", SF_ERROR_SINGULAR, NULL);
+            return std::copysign(std::numeric_limits::infinity(), -x);
+        } else if (x < 0.0) {
+            /* argument reduction before evaluating tan(pi * x) */
+            r = std::modf(x, &q);
+            if (r == 0.0) {
+                set_error("psi", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            y = -M_PI / std::tan(M_PI * r);
+            x = 1.0 - x;
+        }
+
+        /* check for positive integer up to 10 */
+        if ((x <= 10.0) && (x == std::floor(x))) {
+            n = static_cast(x);
+            for (i = 1; i < n; i++) {
+                y += 1.0 / i;
+            }
+            y -= detail::SCIPY_EULER;
+            return y;
+        }
+
+        /* use the recurrence relation to move x into [1, 2] */
+        if (x < 1.0) {
+            y -= 1.0 / x;
+            x += 1.0;
+        } else if (x < 10.0) {
+            while (x > 2.0) {
+                x -= 1.0;
+                y += 1.0 / x;
+            }
+        }
+        if ((1.0 <= x) && (x <= 2.0)) {
+            y += detail::digamma_imp_1_2(x);
+            return y;
+        }
+
+        /* x is large, use the asymptotic series */
+        y += detail::psi_asy(x);
+        return y;
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..97f29b33ab50abb01f4ee4b71d0f2fbc6ffd1858
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h
@@ -0,0 +1,111 @@
+/*                                             rgamma.c
+ *
+ *     Reciprocal Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, rgamma();
+ *
+ * y = rgamma( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns one divided by the Gamma function of the argument.
+ *
+ * The function is approximated by a Chebyshev expansion in
+ * the interval [0,1].  Range reduction is by recurrence
+ * for arguments between -34.034 and +34.84425627277176174.
+ * 0 is returned for positive arguments outside this
+ * range.  For arguments less than -34.034 the cosecant
+ * reflection formula is applied; lograrithms are employed
+ * to avoid unnecessary overflow.
+ *
+ * The reciprocal Gamma function has no singularities,
+ * but overflow and underflow may occur for large arguments.
+ * These conditions return either INFINITY or 0 with
+ * appropriate sign.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -30,+30      30000       1.1e-15     2.0e-16
+ * For arguments less than -34.034 the peak error is on the
+ * order of 5e-15 (DEC), excepting overflow or underflow.
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "chbevl.h"
+#include "const.h"
+#include "gamma.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for reciprocal Gamma function
+         * in interval 0 to 1.  Function is 1/(x Gamma(x)) - 1
+         */
+
+        constexpr double rgamma_R[] = {
+            3.13173458231230000000E-17, -6.70718606477908000000E-16, 2.20039078172259550000E-15,
+            2.47691630348254132600E-13, -6.60074100411295197440E-12, 5.13850186324226978840E-11,
+            1.08965386454418662084E-9,  -3.33964630686836942556E-8,  2.68975996440595483619E-7,
+            2.96001177518801696639E-6,  -8.04814124978471142852E-5,  4.16609138709688864714E-4,
+            5.06579864028608725080E-3,  -6.41925436109158228810E-2,  -4.98558728684003594785E-3,
+            1.27546015610523951063E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE double rgamma(double x) {
+        double w, y, z;
+
+	if (x == 0) {
+	    // This case is separate from below to get correct sign for zero.
+	    return x;
+	}
+
+	if (x < 0 && x == std::floor(x)) {
+	    // Gamma poles.
+	    return 0.0;
+	}
+
+	if (std::abs(x) > 4.0) {
+	    return 1.0 / Gamma(x);
+	}
+
+        z = 1.0;
+        w = x;
+
+        while (w > 1.0) { /* Downward recurrence */
+            w -= 1.0;
+            z *= w;
+        }
+        while (w < 0.0) { /* Upward recurrence */
+            z /= w;
+            w += 1.0;
+        }
+        if (w == 0.0) /* Nonpositive integer */
+            return (0.0);
+        if (w == 1.0) /* Other integer */
+            return (1.0 / z);
+
+        y = w * (1.0 + chbevl(4.0 * w - 2.0, detail::rgamma_R, 16)) / z;
+        return (y);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h
new file mode 100644
index 0000000000000000000000000000000000000000..fe0c631e34582d32132afdf41e2e6904fda90c82
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h
@@ -0,0 +1,811 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     iv.c
+ *
+ *     Modified Bessel function of noninteger order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, iv();
+ *
+ * y = iv( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order v of the
+ * argument.  If x is negative, v must be integer valued.
+ *
+ */
+/*                                                     iv.c    */
+/*     Modified Bessel function of noninteger order            */
+/* If x < 0, then v must be an integer. */
+
+/*
+ * Parts of the code are copyright:
+ *
+ *     Cephes Math Library Release 2.8:  June, 2000
+ *     Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ *
+ * And other parts:
+ *
+ *     Copyright (c) 2006 Xiaogang Zhang
+ *     Use, modification and distribution are subject to the
+ *     Boost Software License, Version 1.0.
+ *
+ *     Boost Software License - Version 1.0 - August 17th, 2003
+ *
+ *     Permission is hereby granted, free of charge, to any person or
+ *     organization obtaining a copy of the software and accompanying
+ *     documentation covered by this license (the "Software") to use, reproduce,
+ *     display, distribute, execute, and transmit the Software, and to prepare
+ *     derivative works of the Software, and to permit third-parties to whom the
+ *     Software is furnished to do so, all subject to the following:
+ *
+ *     The copyright notices in the Software and this entire statement,
+ *     including the above license grant, this restriction and the following
+ *     disclaimer, must be included in all copies of the Software, in whole or
+ *     in part, and all derivative works of the Software, unless such copies or
+ *     derivative works are solely in the form of machine-executable object code
+ *     generated by a source language processor.
+ *
+ *     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ *     OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
+ *     NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
+ *     DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
+ *     WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ *     CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ *     SOFTWARE.
+ *
+ * And the rest are:
+ *
+ *     Copyright (C) 2009 Pauli Virtanen
+ *     Distributed under the same license as Scipy.
+ *
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /*
+         * Compute Iv from (AMS5 9.7.1), asymptotic expansion for large |z|
+         * Iv ~ exp(x)/sqrt(2 pi x) ( 1 + (4*v*v-1)/8x + (4*v*v-1)(4*v*v-9)/8x/2! + ...)
+         */
+        XSF_HOST_DEVICE inline double iv_asymptotic(double v, double x) {
+            double mu;
+            double sum, term, prefactor, factor;
+            int k;
+
+            prefactor = std::exp(x) / std::sqrt(2 * M_PI * x);
+
+            if (prefactor == std::numeric_limits::infinity()) {
+                return prefactor;
+            }
+
+            mu = 4 * v * v;
+            sum = 1.0;
+            term = 1.0;
+            k = 1;
+
+            do {
+                factor = (mu - (2 * k - 1) * (2 * k - 1)) / (8 * x) / k;
+                if (k > 100) {
+                    /* didn't converge */
+                    set_error("iv(iv_asymptotic)", SF_ERROR_NO_RESULT, NULL);
+                    break;
+                }
+                term *= -factor;
+                sum += term;
+                ++k;
+            } while (std::abs(term) > MACHEP * std::abs(sum));
+            return sum * prefactor;
+        }
+
+        /*
+         * Uniform asymptotic expansion factors, (AMS5 9.3.9; AMS5 9.3.10)
+         *
+         * Computed with:
+         * --------------------
+         import numpy as np
+         t = np.poly1d([1,0])
+         def up1(p):
+         return .5*t*t*(1-t*t)*p.deriv() + 1/8. * ((1-5*t*t)*p).integ()
+         us = [np.poly1d([1])]
+         for k in range(10):
+         us.append(up1(us[-1]))
+         n = us[-1].order
+         for p in us:
+         print "{" + ", ".join(["0"]*(n-p.order) + map(repr, p)) + "},"
+         print "N_UFACTORS", len(us)
+         print "N_UFACTOR_TERMS", us[-1].order + 1
+         * --------------------
+         */
+        constexpr int iv_N_UFACTORS = 11;
+        constexpr int iv_N_UFACTOR_TERMS = 31;
+
+        constexpr double iv_asymptotic_ufactors[iv_N_UFACTORS][iv_N_UFACTOR_TERMS] = {
+            {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, 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, 0, 0, 0, -0.20833333333333334,
+             0.0, 0.125, 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.3342013888888889,
+             0.0,
+             -0.40104166666666669,
+             0.0,
+             0.0703125,
+             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,   -1.0258125964506173,
+             0.0, 1.8464626736111112,
+             0.0, -0.89121093750000002,
+             0.0, 0.0732421875,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             4.6695844234262474,
+             0.0,
+             -11.207002616222995,
+             0.0,
+             8.78912353515625,
+             0.0,
+             -2.3640869140624998,
+             0.0,
+             0.112152099609375,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   -28.212072558200244,
+             0.0, 84.636217674600744,
+             0.0, -91.818241543240035,
+             0.0, 42.534998745388457,
+             0.0, -7.3687943594796312,
+             0.0, 0.22710800170898438,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             212.5701300392171,
+             0.0,
+             -765.25246814118157,
+             0.0,
+             1059.9904525279999,
+             0.0,
+             -699.57962737613275,
+             0.0,
+             218.19051174421159,
+             0.0,
+             -26.491430486951554,
+             0.0,
+             0.57250142097473145,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   -1919.4576623184068,
+             0.0, 8061.7221817373083,
+             0.0, -13586.550006434136,
+             0.0, 11655.393336864536,
+             0.0, -5305.6469786134048,
+             0.0, 1200.9029132163525,
+             0.0, -108.09091978839464,
+             0.0, 1.7277275025844574,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             20204.291330966149,
+             0.0,
+             -96980.598388637503,
+             0.0,
+             192547.0012325315,
+             0.0,
+             -203400.17728041555,
+             0.0,
+             122200.46498301747,
+             0.0,
+             -41192.654968897557,
+             0.0,
+             7109.5143024893641,
+             0.0,
+             -493.915304773088,
+             0.0,
+             6.074042001273483,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   -242919.18790055133,
+             0.0, 1311763.6146629769,
+             0.0, -2998015.9185381061,
+             0.0, 3763271.2976564039,
+             0.0, -2813563.2265865342,
+             0.0, 1268365.2733216248,
+             0.0, -331645.17248456361,
+             0.0, 45218.768981362737,
+             0.0, -2499.8304818112092,
+             0.0, 24.380529699556064,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {3284469.8530720375,
+             0.0,
+             -19706819.11843222,
+             0.0,
+             50952602.492664628,
+             0.0,
+             -74105148.211532637,
+             0.0,
+             66344512.274729028,
+             0.0,
+             -37567176.660763353,
+             0.0,
+             13288767.166421819,
+             0.0,
+             -2785618.1280864552,
+             0.0,
+             308186.40461266245,
+             0.0,
+             -13886.089753717039,
+             0.0,
+             110.01714026924674,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0}};
+
+        /*
+         * Compute Iv, Kv from (AMS5 9.7.7 + 9.7.8), asymptotic expansion for large v
+         */
+        XSF_HOST_DEVICE inline void ikv_asymptotic_uniform(double v, double x, double *i_value, double *k_value) {
+            double i_prefactor, k_prefactor;
+            double t, t2, eta, z;
+            double i_sum, k_sum, term, divisor;
+            int k, n;
+            int sign = 1;
+
+            if (v < 0) {
+                /* Negative v; compute I_{-v} and K_{-v} and use (AMS 9.6.2) */
+                sign = -1;
+                v = -v;
+            }
+
+            z = x / v;
+            t = 1 / std::sqrt(1 + z * z);
+            t2 = t * t;
+            eta = std::sqrt(1 + z * z) + std::log(z / (1 + 1 / t));
+
+            i_prefactor = std::sqrt(t / (2 * M_PI * v)) * std::exp(v * eta);
+            i_sum = 1.0;
+
+            k_prefactor = std::sqrt(M_PI * t / (2 * v)) * std::exp(-v * eta);
+            k_sum = 1.0;
+
+            divisor = v;
+            for (n = 1; n < iv_N_UFACTORS; ++n) {
+                /*
+                 * Evaluate u_k(t) with Horner's scheme;
+                 * (using the knowledge about which coefficients are zero)
+                 */
+                term = 0;
+                for (k = iv_N_UFACTOR_TERMS - 1 - 3 * n; k < iv_N_UFACTOR_TERMS - n; k += 2) {
+                    term *= t2;
+                    term += iv_asymptotic_ufactors[n][k];
+                }
+                for (k = 1; k < n; k += 2) {
+                    term *= t2;
+                }
+                if (n % 2 == 1) {
+                    term *= t;
+                }
+
+                /* Sum terms */
+                term /= divisor;
+                i_sum += term;
+                k_sum += (n % 2 == 0) ? term : -term;
+
+                /* Check convergence */
+                if (std::abs(term) < MACHEP) {
+                    break;
+                }
+
+                divisor *= v;
+            }
+
+            if (std::abs(term) > 1e-3 * std::abs(i_sum)) {
+                /* Didn't converge */
+                set_error("ikv_asymptotic_uniform", SF_ERROR_NO_RESULT, NULL);
+            }
+            if (std::abs(term) > MACHEP * std::abs(i_sum)) {
+                /* Some precision lost */
+                set_error("ikv_asymptotic_uniform", SF_ERROR_LOSS, NULL);
+            }
+
+            if (k_value != NULL) {
+                /* symmetric in v */
+                *k_value = k_prefactor * k_sum;
+            }
+
+            if (i_value != NULL) {
+                if (sign == 1) {
+                    *i_value = i_prefactor * i_sum;
+                } else {
+                    /* (AMS 9.6.2) */
+                    *i_value = (i_prefactor * i_sum + (2 / M_PI) * xsf::cephes::sinpi(v) * k_prefactor * k_sum);
+                }
+            }
+        }
+
+        /*
+         * The following code originates from the Boost C++ library,
+         * from file `boost/math/special_functions/detail/bessel_ik.hpp`,
+         * converted from C++ to C.
+         */
+
+        /*
+         * Modified Bessel functions of the first and second kind of fractional order
+         *
+         * Calculate K(v, x) and K(v+1, x) by method analogous to
+         * Temme, Journal of Computational Physics, vol 21, 343 (1976)
+         */
+        XSF_HOST_DEVICE inline int temme_ik_series(double v, double x, double *K, double *K1) {
+            double f, h, p, q, coef, sum, sum1, tolerance;
+            double a, b, c, d, sigma, gamma1, gamma2;
+            std::uint64_t k;
+            double gp;
+            double gm;
+
+            /*
+             * |x| <= 2, Temme series converge rapidly
+             * |x| > 2, the larger the |x|, the slower the convergence
+             */
+            XSF_ASSERT(std::abs(x) <= 2);
+            XSF_ASSERT(std::abs(v) <= 0.5f);
+
+            gp = xsf::cephes::Gamma(v + 1) - 1;
+            gm = xsf::cephes::Gamma(-v + 1) - 1;
+
+            a = std::log(x / 2);
+            b = std::exp(v * a);
+            sigma = -a * v;
+            c = std::abs(v) < MACHEP ? 1 : xsf::cephes::sinpi(v) / (v * M_PI);
+            d = std::abs(sigma) < MACHEP ? 1 : std::sinh(sigma) / sigma;
+            gamma1 = std::abs(v) < MACHEP ? -SCIPY_EULER : (0.5 / v) * (gp - gm) * c;
+            gamma2 = (2 + gp + gm) * c / 2;
+
+            /* initial values */
+            p = (gp + 1) / (2 * b);
+            q = (1 + gm) * b / 2;
+            f = (std::cosh(sigma) * gamma1 + d * (-a) * gamma2) / c;
+            h = p;
+            coef = 1;
+            sum = coef * f;
+            sum1 = coef * h;
+
+            /* series summation */
+            tolerance = MACHEP;
+            for (k = 1; k < MAXITER; k++) {
+                f = (k * f + p + q) / (k * k - v * v);
+                p /= k - v;
+                q /= k + v;
+                h = p - k * f;
+                coef *= x * x / (4 * k);
+                sum += coef * f;
+                sum1 += coef * h;
+                if (std::abs(coef * f) < std::abs(sum) * tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(temme_ik_series)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *K = sum;
+            *K1 = 2 * sum1 / x;
+
+            return 0;
+        }
+
+        /* Evaluate continued fraction fv = I_(v+1) / I_v, derived from
+         * Abramowitz and Stegun, Handbook of Mathematical Functions, 1972, 9.1.73 */
+        XSF_HOST_DEVICE inline int CF1_ik(double v, double x, double *fv) {
+            double C, D, f, a, b, delta, tiny, tolerance;
+            std::uint64_t k;
+
+            /*
+             * |x| <= |v|, CF1_ik converges rapidly
+             * |x| > |v|, CF1_ik needs O(|x|) iterations to converge
+             */
+
+            /*
+             * modified Lentz's method, see
+             * Lentz, Applied Optics, vol 15, 668 (1976)
+             */
+            tolerance = 2 * MACHEP;
+            tiny = 1 / std::sqrt(std::numeric_limits::max());
+            C = f = tiny; /* b0 = 0, replace with tiny */
+            D = 0;
+            for (k = 1; k < MAXITER; k++) {
+                a = 1;
+                b = 2 * (v + k) / x;
+                C = b + a / C;
+                D = b + a * D;
+                if (C == 0) {
+                    C = tiny;
+                }
+                if (D == 0) {
+                    D = tiny;
+                }
+                D = 1 / D;
+                delta = C * D;
+                f *= delta;
+                if (std::abs(delta - 1) <= tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(CF1_ik)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *fv = f;
+
+            return 0;
+        }
+
+        /*
+         * Calculate K(v, x) and K(v+1, x) by evaluating continued fraction
+         * z1 / z0 = U(v+1.5, 2v+1, 2x) / U(v+0.5, 2v+1, 2x), see
+         * Thompson and Barnett, Computer Physics Communications, vol 47, 245 (1987)
+         */
+        XSF_HOST_DEVICE inline int CF2_ik(double v, double x, double *Kv, double *Kv1) {
+
+            double S, C, Q, D, f, a, b, q, delta, tolerance, current, prev;
+            std::uint64_t k;
+
+            /*
+             * |x| >= |v|, CF2_ik converges rapidly
+             * |x| -> 0, CF2_ik fails to converge
+             */
+
+            XSF_ASSERT(std::abs(x) > 1);
+
+            /*
+             * Steed's algorithm, see Thompson and Barnett,
+             * Journal of Computational Physics, vol 64, 490 (1986)
+             */
+            tolerance = MACHEP;
+            a = v * v - 0.25;
+            b = 2 * (x + 1);                /* b1 */
+            D = 1 / b;                      /* D1 = 1 / b1 */
+            f = delta = D;                  /* f1 = delta1 = D1, coincidence */
+            prev = 0;                       /* q0 */
+            current = 1;                    /* q1 */
+            Q = C = -a;                     /* Q1 = C1 because q1 = 1 */
+            S = 1 + Q * delta;              /* S1 */
+            for (k = 2; k < MAXITER; k++) { /* starting from 2 */
+                /* continued fraction f = z1 / z0 */
+                a -= 2 * (k - 1);
+                b += 2;
+                D = 1 / (b + a * D);
+                delta *= b * D - 1;
+                f += delta;
+
+                /* series summation S = 1 + \sum_{n=1}^{\infty} C_n * z_n / z_0 */
+                q = (prev - (b - 2) * current) / a;
+                prev = current;
+                current = q; /* forward recurrence for q */
+                C *= -a / k;
+                Q += C * q;
+                S += Q * delta;
+
+                /* S converges slower than f */
+                if (std::abs(Q * delta) < std::abs(S) * tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(CF2_ik)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *Kv = std::sqrt(M_PI / (2 * x)) * std::exp(-x) / S;
+            *Kv1 = *Kv * (0.5 + v + x + (v * v - 0.25) * f) / x;
+
+            return 0;
+        }
+
+        /* Flags for what to compute */
+        enum { ikv_temme_need_i = 0x1, ikv_temme_need_k = 0x2 };
+
+        /*
+         * Compute I(v, x) and K(v, x) simultaneously by Temme's method, see
+         * Temme, Journal of Computational Physics, vol 19, 324 (1975)
+         */
+        XSF_HOST_DEVICE inline void ikv_temme(double v, double x, double *Iv_p, double *Kv_p) {
+            /* Kv1 = K_(v+1), fv = I_(v+1) / I_v */
+            /* Ku1 = K_(u+1), fu = I_(u+1) / I_u */
+            double u, Iv, Kv, Kv1, Ku, Ku1, fv;
+            double W, current, prev, next;
+            int reflect = 0;
+            unsigned n, k;
+            int kind;
+
+            kind = 0;
+            if (Iv_p != NULL) {
+                kind |= ikv_temme_need_i;
+            }
+            if (Kv_p != NULL) {
+                kind |= ikv_temme_need_k;
+            }
+
+            if (v < 0) {
+                reflect = 1;
+                v = -v; /* v is non-negative from here */
+                kind |= ikv_temme_need_k;
+            }
+            n = std::round(v);
+            u = v - n; /* -1/2 <= u < 1/2 */
+
+            if (x < 0) {
+                if (Iv_p != NULL)
+                    *Iv_p = std::numeric_limits::quiet_NaN();
+                if (Kv_p != NULL)
+                    *Kv_p = std::numeric_limits::quiet_NaN();
+                set_error("ikv_temme", SF_ERROR_DOMAIN, NULL);
+                return;
+            }
+            if (x == 0) {
+                Iv = (v == 0) ? 1 : 0;
+                if (kind & ikv_temme_need_k) {
+                    set_error("ikv_temme", SF_ERROR_OVERFLOW, NULL);
+                    Kv = std::numeric_limits::infinity();
+                } else {
+                    Kv = std::numeric_limits::quiet_NaN(); /* any value will do */
+                }
+
+                if (reflect && (kind & ikv_temme_need_i)) {
+                    double z = (u + n % 2);
+
+                    Iv = xsf::cephes::sinpi(z) == 0 ? Iv : std::numeric_limits::infinity();
+                    if (std::isinf(Iv)) {
+                        set_error("ikv_temme", SF_ERROR_OVERFLOW, NULL);
+                    }
+                }
+
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv;
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+                return;
+            }
+            /* x is positive until reflection */
+            W = 1 / x;                            /* Wronskian */
+            if (x <= 2) {                         /* x in (0, 2] */
+                temme_ik_series(u, x, &Ku, &Ku1); /* Temme series */
+            } else {                              /* x in (2, \infty) */
+                CF2_ik(u, x, &Ku, &Ku1);          /* continued fraction CF2_ik */
+            }
+            prev = Ku;
+            current = Ku1;
+            for (k = 1; k <= n; k++) { /* forward recurrence for K */
+                next = 2 * (u + k) * current / x + prev;
+                prev = current;
+                current = next;
+            }
+            Kv = prev;
+            Kv1 = current;
+            if (kind & ikv_temme_need_i) {
+                double lim = (4 * v * v + 10) / (8 * x);
+
+                lim *= lim;
+                lim *= lim;
+                lim /= 24;
+                if ((lim < MACHEP * 10) && (x > 100)) {
+                    /*
+                     * x is huge compared to v, CF1 may be very slow
+                     * to converge so use asymptotic expansion for large
+                     * x case instead.  Note that the asymptotic expansion
+                     * isn't very accurate - so it's deliberately very hard
+                     * to get here - probably we're going to overflow:
+                     */
+                    Iv = iv_asymptotic(v, x);
+                } else {
+                    CF1_ik(v, x, &fv);        /* continued fraction CF1_ik */
+                    Iv = W / (Kv * fv + Kv1); /* Wronskian relation */
+                }
+            } else {
+                Iv = std::numeric_limits::quiet_NaN(); /* any value will do */
+            }
+
+            if (reflect) {
+                double z = (u + n % 2);
+
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv + (2 / M_PI) * xsf::cephes::sinpi(z) * Kv; /* reflection formula */
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+            } else {
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv;
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+            }
+            return;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double iv(double v, double x) {
+        int sign;
+        double t, ax, res;
+
+        if (std::isnan(v) || std::isnan(x)) {
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        /* If v is a negative integer, invoke symmetry */
+        t = std::floor(v);
+        if (v < 0.0) {
+            if (t == v) {
+                v = -v; /* symmetry */
+                t = -t;
+            }
+        }
+        /* If x is negative, require v to be an integer */
+        sign = 1;
+        if (x < 0.0) {
+            if (t != v) {
+                set_error("iv", SF_ERROR_DOMAIN, NULL);
+                return (std::numeric_limits::quiet_NaN());
+            }
+            if (v != 2.0 * std::floor(v / 2.0)) {
+                sign = -1;
+            }
+        }
+
+        /* Avoid logarithm singularity */
+        if (x == 0.0) {
+            if (v == 0.0) {
+                return 1.0;
+            }
+            if (v < 0.0) {
+                set_error("iv", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            } else
+                return 0.0;
+        }
+
+        ax = std::abs(x);
+        if (std::abs(v) > 50) {
+            /*
+             * Uniform asymptotic expansion for large orders.
+             *
+             * This appears to overflow slightly later than the Boost
+             * implementation of Temme's method.
+             */
+            detail::ikv_asymptotic_uniform(v, ax, &res, NULL);
+        } else {
+            /* Otherwise: Temme's method */
+            detail::ikv_temme(v, ax, &res, NULL);
+        }
+        res *= sign;
+        return res;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h
new file mode 100644
index 0000000000000000000000000000000000000000..fcdd2d7986466e33bff8bf15235c2d2814206d61
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h
@@ -0,0 +1,248 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     shichi.c
+ *
+ *     Hyperbolic sine and cosine integrals
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, Chi, Shi, shichi();
+ *
+ * shichi( x, &Chi, &Shi );
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integrals
+ *
+ *                            x
+ *                            -
+ *                           | |   cosh t - 1
+ *   Chi(x) = eul + ln x +   |    -----------  dt,
+ *                         | |          t
+ *                          -
+ *                          0
+ *
+ *               x
+ *               -
+ *              | |  sinh t
+ *   Shi(x) =   |    ------  dt
+ *            | |       t
+ *             -
+ *             0
+ *
+ * where eul = 0.57721566490153286061 is Euler's constant.
+ * The integrals are evaluated by power series for x < 8
+ * and by Chebyshev expansions for x between 8 and 88.
+ * For large x, both functions approach exp(x)/2x.
+ * Arguments greater than 88 in magnitude return INFINITY.
+ *
+ *
+ * ACCURACY:
+ *
+ * Test interval 0 to 88.
+ *                      Relative error:
+ * arithmetic   function  # trials      peak         rms
+ *    IEEE         Shi      30000       6.9e-16     1.6e-16
+ *        Absolute error, except relative when |Chi| > 1:
+ *    IEEE         Chi      30000       8.4e-16     1.4e-16
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "chbevl.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* x exp(-x) shi(x), inverted interval 8 to 18 */
+        constexpr double shichi_S1[] = {
+            1.83889230173399459482E-17,  -9.55485532279655569575E-17, 2.04326105980879882648E-16,
+            1.09896949074905343022E-15,  -1.31313534344092599234E-14, 5.93976226264314278932E-14,
+            -3.47197010497749154755E-14, -1.40059764613117131000E-12, 9.49044626224223543299E-12,
+            -1.61596181145435454033E-11, -1.77899784436430310321E-10, 1.35455469767246947469E-9,
+            -1.03257121792819495123E-9,  -3.56699611114982536845E-8,  1.44818877384267342057E-7,
+            7.82018215184051295296E-7,   -5.39919118403805073710E-6,  -3.12458202168959833422E-5,
+            8.90136741950727517826E-5,   2.02558474743846862168E-3,   2.96064440855633256972E-2,
+            1.11847751047257036625E0};
+
+        /* x exp(-x) shi(x), inverted interval 18 to 88 */
+        constexpr double shichi_S2[] = {
+            -1.05311574154850938805E-17, 2.62446095596355225821E-17,  8.82090135625368160657E-17,
+            -3.38459811878103047136E-16, -8.30608026366935789136E-16, 3.93397875437050071776E-15,
+            1.01765565969729044505E-14,  -4.21128170307640802703E-14, -1.60818204519802480035E-13,
+            3.34714954175994481761E-13,  2.72600352129153073807E-12,  1.66894954752839083608E-12,
+            -3.49278141024730899554E-11, -1.58580661666482709598E-10, -1.79289437183355633342E-10,
+            1.76281629144264523277E-9,   1.69050228879421288846E-8,   1.25391771228487041649E-7,
+            1.16229947068677338732E-6,   1.61038260117376323993E-5,   3.49810375601053973070E-4,
+            1.28478065259647610779E-2,   1.03665722588798326712E0};
+
+        /* x exp(-x) chin(x), inverted interval 8 to 18 */
+        constexpr double shichi_C1[] = {
+            -8.12435385225864036372E-18, 2.17586413290339214377E-17, 5.22624394924072204667E-17,
+            -9.48812110591690559363E-16, 5.35546311647465209166E-15, -1.21009970113732918701E-14,
+            -6.00865178553447437951E-14, 7.16339649156028587775E-13, -2.93496072607599856104E-12,
+            -1.40359438136491256904E-12, 8.76302288609054966081E-11, -4.40092476213282340617E-10,
+            -1.87992075640569295479E-10, 1.31458150989474594064E-8,  -4.75513930924765465590E-8,
+            -2.21775018801848880741E-7,  1.94635531373272490962E-6,  4.33505889257316408893E-6,
+            -6.13387001076494349496E-5,  -3.13085477492997465138E-4, 4.97164789823116062801E-4,
+            2.64347496031374526641E-2,   1.11446150876699213025E0};
+
+        /* x exp(-x) chin(x), inverted interval 18 to 88 */
+        constexpr double shichi_C2[] = {
+            8.06913408255155572081E-18,  -2.08074168180148170312E-17, -5.98111329658272336816E-17,
+            2.68533951085945765591E-16,  4.52313941698904694774E-16,  -3.10734917335299464535E-15,
+            -4.42823207332531972288E-15, 3.49639695410806959872E-14,  6.63406731718911586609E-14,
+            -3.71902448093119218395E-13, -1.27135418132338309016E-12, 2.74851141935315395333E-12,
+            2.33781843985453438400E-11,  2.71436006377612442764E-11,  -2.56600180000355990529E-10,
+            -1.61021375163803438552E-9,  -4.72543064876271773512E-9,  -3.00095178028681682282E-9,
+            7.79387474390914922337E-8,   1.06942765566401507066E-6,   1.59503164802313196374E-5,
+            3.49592575153777996871E-4,   1.28475387530065247392E-2,   1.03665693917934275131E0};
+
+        /*
+         * Evaluate 3F0(a1, a2, a3; z)
+         *
+         * The series is only asymptotic, so this requires z large enough.
+         */
+        XSF_HOST_DEVICE inline double hyp3f0(double a1, double a2, double a3, double z) {
+            int n, maxiter;
+            double err, sum, term, m;
+
+            m = std::pow(z, -1.0 / 3);
+            if (m < 50) {
+                maxiter = m;
+            } else {
+                maxiter = 50;
+            }
+
+            term = 1.0;
+            sum = term;
+            for (n = 0; n < maxiter; ++n) {
+                term *= (a1 + n) * (a2 + n) * (a3 + n) * z / (n + 1);
+                sum += term;
+                if (std::abs(term) < 1e-13 * std::abs(sum) || term == 0) {
+                    break;
+                }
+            }
+
+            err = std::abs(term);
+
+            if (err > 1e-13 * std::abs(sum)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            return sum;
+        }
+
+    } // namespace detail
+
+    /* Sine and cosine integrals */
+    XSF_HOST_DEVICE inline int shichi(double x, double *si, double *ci) {
+        double k, z, c, s, a, b;
+        short sign;
+
+        if (x < 0.0) {
+            sign = -1;
+            x = -x;
+        } else {
+            sign = 0;
+        }
+
+        if (x == 0.0) {
+            *si = 0.0;
+            *ci = -std::numeric_limits::infinity();
+            return (0);
+        }
+
+        if (x >= 8.0) {
+            goto chb;
+        }
+
+        if (x >= 88.0) {
+            goto asymp;
+        }
+
+        z = x * x;
+
+        /*     Direct power series expansion   */
+        a = 1.0;
+        s = 1.0;
+        c = 0.0;
+        k = 2.0;
+
+        do {
+            a *= z / k;
+            c += a / k;
+            k += 1.0;
+            a /= k;
+            s += a / k;
+            k += 1.0;
+        } while (std::abs(a / s) > detail::MACHEP);
+
+        s *= x;
+        goto done;
+
+    chb:
+        /* Chebyshev series expansions */
+        if (x < 18.0) {
+            a = (576.0 / x - 52.0) / 10.0;
+            k = std::exp(x) / x;
+            s = k * chbevl(a, detail::shichi_S1, 22);
+            c = k * chbevl(a, detail::shichi_C1, 23);
+            goto done;
+        }
+
+        if (x <= 88.0) {
+            a = (6336.0 / x - 212.0) / 70.0;
+            k = std::exp(x) / x;
+            s = k * chbevl(a, detail::shichi_S2, 23);
+            c = k * chbevl(a, detail::shichi_C2, 24);
+            goto done;
+        }
+
+    asymp:
+        if (x > 1000) {
+            *si = std::numeric_limits::infinity();
+            *ci = std::numeric_limits::infinity();
+        } else {
+            /* Asymptotic expansions
+             * http://functions.wolfram.com/GammaBetaErf/CoshIntegral/06/02/
+             * http://functions.wolfram.com/GammaBetaErf/SinhIntegral/06/02/0001/
+             */
+            a = detail::hyp3f0(0.5, 1, 1, 4.0 / (x * x));
+            b = detail::hyp3f0(1, 1, 1.5, 4.0 / (x * x));
+            *si = std::cosh(x) / x * a + std::sinh(x) / (x * x) * b;
+            *ci = std::sinh(x) / x * a + std::cosh(x) / (x * x) * b;
+        }
+        if (sign) {
+            *si = -*si;
+        }
+        return 0;
+
+    done:
+        if (sign) {
+            s = -s;
+        }
+
+        *si = s;
+
+        *ci = detail::SCIPY_EULER + std::log(x) + c;
+        return (0);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h
new file mode 100644
index 0000000000000000000000000000000000000000..c22612ccc9abfd0594467ad40ad466b4559db2bc
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h
@@ -0,0 +1,224 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     sici.c
+ *
+ *     Sine and cosine integrals
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, Ci, Si, sici();
+ *
+ * sici( x, &Si, &Ci );
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the integrals
+ *
+ *                          x
+ *                          -
+ *                         |  cos t - 1
+ *   Ci(x) = eul + ln x +  |  --------- dt,
+ *                         |      t
+ *                        -
+ *                         0
+ *             x
+ *             -
+ *            |  sin t
+ *   Si(x) =  |  ----- dt
+ *            |    t
+ *           -
+ *            0
+ *
+ * where eul = 0.57721566490153286061 is Euler's constant.
+ * The integrals are approximated by rational functions.
+ * For x > 8 auxiliary functions f(x) and g(x) are employed
+ * such that
+ *
+ * Ci(x) = f(x) sin(x) - g(x) cos(x)
+ * Si(x) = pi/2 - f(x) cos(x) - g(x) sin(x)
+ *
+ *
+ * ACCURACY:
+ *    Test interval = [0,50].
+ * Absolute error, except relative when > 1:
+ * arithmetic   function   # trials      peak         rms
+ *    IEEE        Si        30000       4.4e-16     7.3e-17
+ *    IEEE        Ci        30000       6.9e-16     5.1e-17
+ */
+
+/*
+ * Cephes Math Library Release 2.1:  January, 1989
+ * Copyright 1984, 1987, 1989 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double sici_SN[] = {
+            -8.39167827910303881427E-11, 4.62591714427012837309E-8,  -9.75759303843632795789E-6,
+            9.76945438170435310816E-4,   -4.13470316229406538752E-2, 1.00000000000000000302E0,
+        };
+
+        constexpr double sici_SD[] = {
+            2.03269266195951942049E-12, 1.27997891179943299903E-9, 4.41827842801218905784E-7,
+            9.96412122043875552487E-5,  1.42085239326149893930E-2, 9.99999999999999996984E-1,
+        };
+
+        constexpr double sici_CN[] = {
+            2.02524002389102268789E-11, -1.35249504915790756375E-8, 3.59325051419993077021E-6,
+            -4.74007206873407909465E-4, 2.89159652607555242092E-2,  -1.00000000000000000080E0,
+        };
+
+        constexpr double sici_CD[] = {
+            4.07746040061880559506E-12, 3.06780997581887812692E-9, 1.23210355685883423679E-6,
+            3.17442024775032769882E-4,  5.10028056236446052392E-2, 4.00000000000000000080E0,
+        };
+
+        constexpr double sici_FN4[] = {
+            4.23612862892216586994E0,  5.45937717161812843388E0,  1.62083287701538329132E0,  1.67006611831323023771E-1,
+            6.81020132472518137426E-3, 1.08936580650328664411E-4, 5.48900223421373614008E-7,
+        };
+
+        constexpr double sici_FD4[] = {
+            /*  1.00000000000000000000E0, */
+            8.16496634205391016773E0,  7.30828822505564552187E0,  1.86792257950184183883E0,  1.78792052963149907262E-1,
+            7.01710668322789753610E-3, 1.10034357153915731354E-4, 5.48900252756255700982E-7,
+        };
+
+        constexpr double sici_FN8[] = {
+            4.55880873470465315206E-1, 7.13715274100146711374E-1,  1.60300158222319456320E-1,
+            1.16064229408124407915E-2, 3.49556442447859055605E-4,  4.86215430826454749482E-6,
+            3.20092790091004902806E-8, 9.41779576128512936592E-11, 9.70507110881952024631E-14,
+        };
+
+        constexpr double sici_FD8[] = {
+            /*  1.00000000000000000000E0, */
+            9.17463611873684053703E-1,  1.78685545332074536321E-1,  1.22253594771971293032E-2,
+            3.58696481881851580297E-4,  4.92435064317881464393E-6,  3.21956939101046018377E-8,
+            9.43720590350276732376E-11, 9.70507110881952025725E-14,
+        };
+
+        constexpr double sici_GN4[] = {
+            8.71001698973114191777E-2, 6.11379109952219284151E-1, 3.97180296392337498885E-1, 7.48527737628469092119E-2,
+            5.38868681462177273157E-3, 1.61999794598934024525E-4, 1.97963874140963632189E-6, 7.82579040744090311069E-9,
+        };
+
+        constexpr double sici_GD4[] = {
+            /*  1.00000000000000000000E0, */
+            1.64402202413355338886E0,  6.66296701268987968381E-1, 9.88771761277688796203E-2, 6.22396345441768420760E-3,
+            1.73221081474177119497E-4, 2.02659182086343991969E-6, 7.82579218933534490868E-9,
+        };
+
+        constexpr double sici_GN8[] = {
+            6.97359953443276214934E-1, 3.30410979305632063225E-1,  3.84878767649974295920E-2,
+            1.71718239052347903558E-3, 3.48941165502279436777E-5,  3.47131167084116673800E-7,
+            1.70404452782044526189E-9, 3.85945925430276600453E-12, 3.14040098946363334640E-15,
+        };
+
+        constexpr double sici_GD8[] = {
+            /*  1.00000000000000000000E0, */
+            1.68548898811011640017E0,  4.87852258695304967486E-1,  4.67913194259625806320E-2,
+            1.90284426674399523638E-3, 3.68475504442561108162E-5,  3.57043223443740838771E-7,
+            1.72693748966316146736E-9, 3.87830166023954706752E-12, 3.14040098946363335242E-15,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) {
+        double z, c, s, f, g;
+        short sign;
+
+        if (x < 0.0) {
+            sign = -1;
+            x = -x;
+        } else {
+            sign = 0;
+        }
+
+        if (x == 0.0) {
+            *si = 0.0;
+            *ci = -std::numeric_limits::infinity();
+            return (0);
+        }
+
+        if (x > 1.0e9) {
+            if (std::isinf(x)) {
+                if (sign == -1) {
+                    *si = -M_PI_2;
+                    *ci = std::numeric_limits::quiet_NaN();
+                } else {
+                    *si = M_PI_2;
+                    *ci = 0;
+                }
+                return 0;
+            }
+            *si = M_PI_2 - std::cos(x) / x;
+            *ci = std::sin(x) / x;
+        }
+
+        if (x > 4.0) {
+            goto asympt;
+        }
+
+        z = x * x;
+        s = x * polevl(z, detail::sici_SN, 5) / polevl(z, detail::sici_SD, 5);
+        c = z * polevl(z, detail::sici_CN, 5) / polevl(z, detail::sici_CD, 5);
+
+        if (sign) {
+            s = -s;
+        }
+        *si = s;
+        *ci = detail::SCIPY_EULER + std::log(x) + c; /* real part if x < 0 */
+        return (0);
+
+        /* The auxiliary functions are:
+         *
+         *
+         * *si = *si - M_PI_2;
+         * c = cos(x);
+         * s = sin(x);
+         *
+         * t = *ci * s - *si * c;
+         * a = *ci * c + *si * s;
+         *
+         * *si = t;
+         * *ci = -a;
+         */
+
+    asympt:
+
+        s = std::sin(x);
+        c = std::cos(x);
+        z = 1.0 / (x * x);
+        if (x < 8.0) {
+            f = polevl(z, detail::sici_FN4, 6) / (x * p1evl(z, detail::sici_FD4, 7));
+            g = z * polevl(z, detail::sici_GN4, 7) / p1evl(z, detail::sici_GD4, 7);
+        } else {
+            f = polevl(z, detail::sici_FN8, 8) / (x * p1evl(z, detail::sici_FD8, 8));
+            g = z * polevl(z, detail::sici_GN8, 8) / p1evl(z, detail::sici_GD8, 9);
+        }
+        *si = M_PI_2 - f * c - g * s;
+        if (sign) {
+            *si = -(*si);
+        }
+        *ci = f * s - g * c;
+
+        return (0);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h
new file mode 100644
index 0000000000000000000000000000000000000000..63adb1698f4c6e51d971484c92b3cf2c98dcba6f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h
@@ -0,0 +1,221 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     sindg.c
+ *
+ *     Circular sine of angle in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, sindg();
+ *
+ * y = sindg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Range reduction is into intervals of 45 degrees.
+ *
+ * Two polynomial approximating functions are employed.
+ * Between 0 and pi/4 the sine is approximated by
+ *      x  +  x**3 P(x**2).
+ * Between pi/4 and pi/2 the cosine is represented as
+ *      1  -  x**2 P(x**2).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      +-1000       30000      2.3e-16      5.6e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message           condition        value returned
+ * sindg total loss   x > 1.0e14 (IEEE)     0.0
+ *
+ */
+/*							cosdg.c
+ *
+ *	Circular cosine of angle in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cosdg();
+ *
+ * y = cosdg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Range reduction is into intervals of 45 degrees.
+ *
+ * Two polynomial approximating functions are employed.
+ * Between 0 and pi/4 the cosine is approximated by
+ *      1  -  x**2 P(x**2).
+ * Between pi/4 and pi/2 the sine is represented as
+ *      x  +  x**3 P(x**2).
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE     +-1000        30000       2.1e-16     5.7e-17
+ *  See also sin().
+ *
+ */
+
+/* Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double sincof[] = {1.58962301572218447952E-10, -2.50507477628503540135E-8,
+                                     2.75573136213856773549E-6,  -1.98412698295895384658E-4,
+                                     8.33333333332211858862E-3,  -1.66666666666666307295E-1};
+
+        constexpr double coscof[] = {1.13678171382044553091E-11, -2.08758833757683644217E-9, 2.75573155429816611547E-7,
+                                     -2.48015872936186303776E-5, 1.38888888888806666760E-3,  -4.16666666666666348141E-2,
+                                     4.99999999999999999798E-1};
+
+        constexpr double sindg_lossth = 1.0e14;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double sindg(double x) {
+        double y, z, zz;
+        int j, sign;
+
+        /* make argument positive but save the sign */
+        sign = 1;
+        if (x < 0) {
+            x = -x;
+            sign = -1;
+        }
+
+        if (x > detail::sindg_lossth) {
+            set_error("sindg", SF_ERROR_NO_RESULT, NULL);
+            return (0.0);
+        }
+
+        y = std::floor(x / 45.0); /* integer part of x/M_PI_4 */
+
+        /* strip high bits of integer part to prevent integer overflow */
+        z = std::ldexp(y, -4);
+        z = std::floor(z);        /* integer part of y/8 */
+        z = y - std::ldexp(z, 4); /* y - 16 * (y/16) */
+
+        j = z; /* convert to integer for tests on the phase angle */
+        /* map zeros to origin */
+        if (j & 1) {
+            j += 1;
+            y += 1.0;
+        }
+        j = j & 07; /* octant modulo 360 degrees */
+        /* reflect in x axis */
+        if (j > 3) {
+            sign = -sign;
+            j -= 4;
+        }
+
+        z = x - y * 45.0;   /* x mod 45 degrees */
+        z *= detail::PI180; /* multiply by pi/180 to convert to radians */
+        zz = z * z;
+
+        if ((j == 1) || (j == 2)) {
+            y = 1.0 - zz * polevl(zz, detail::coscof, 6);
+        } else {
+            y = z + z * (zz * polevl(zz, detail::sincof, 5));
+        }
+
+        if (sign < 0)
+            y = -y;
+
+        return (y);
+    }
+
+    XSF_HOST_DEVICE inline double cosdg(double x) {
+        double y, z, zz;
+        int j, sign;
+
+        /* make argument positive */
+        sign = 1;
+        if (x < 0)
+            x = -x;
+
+        if (x > detail::sindg_lossth) {
+            set_error("cosdg", SF_ERROR_NO_RESULT, NULL);
+            return (0.0);
+        }
+
+        y = std::floor(x / 45.0);
+        z = std::ldexp(y, -4);
+        z = std::floor(z);        /* integer part of y/8 */
+        z = y - std::ldexp(z, 4); /* y - 16 * (y/16) */
+
+        /* integer and fractional part modulo one octant */
+        j = z;
+        if (j & 1) { /* map zeros to origin */
+            j += 1;
+            y += 1.0;
+        }
+        j = j & 07;
+        if (j > 3) {
+            j -= 4;
+            sign = -sign;
+        }
+
+        if (j > 1)
+            sign = -sign;
+
+        z = x - y * 45.0;   /* x mod 45 degrees */
+        z *= detail::PI180; /* multiply by pi/180 to convert to radians */
+
+        zz = z * z;
+
+        if ((j == 1) || (j == 2)) {
+            y = z + z * (zz * polevl(zz, detail::sincof, 5));
+        } else {
+            y = 1.0 - zz * polevl(zz, detail::coscof, 6);
+        }
+
+        if (sign < 0)
+            y = -y;
+
+        return (y);
+    }
+
+    /* Degrees, minutes, seconds to radians: */
+
+    /* 1 arc second, in radians = 4.848136811095359935899141023579479759563533023727e-6 */
+
+    namespace detail {
+        constexpr double sindg_P64800 = 4.848136811095359935899141023579479759563533023727e-6;
+    }
+
+    XSF_HOST_DEVICE inline double radian(double d, double m, double s) {
+        return (((d * 60.0 + m) * 60.0 + s) * detail::sindg_P64800);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h
new file mode 100644
index 0000000000000000000000000000000000000000..071b1a81d8bd5467fabf99fa54881f5862c0218b
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h
@@ -0,0 +1,139 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     tandg.c
+ *
+ *     Circular tangent of argument in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, tandg();
+ *
+ * y = tandg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the circular tangent of the argument x in degrees.
+ *
+ * Range reduction is modulo pi/4.  A rational function
+ *       x + x**3 P(x**2)/Q(x**2)
+ * is employed in the basic interval [0, pi/4].
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     0,10         30000      3.2e-16      8.4e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * tandg total loss   x > 1.0e14 (IEEE)     0.0
+ * tandg singularity  x = 180 k  +  90     INFINITY
+ */
+/*							cotdg.c
+ *
+ *	Circular cotangent of argument in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cotdg();
+ *
+ * y = cotdg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the circular cotangent of the argument x in degrees.
+ *
+ * Range reduction is modulo pi/4.  A rational function
+ *       x + x**3 P(x**2)/Q(x**2)
+ * is employed in the basic interval [0, pi/4].
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * cotdg total loss   x > 1.0e14 (IEEE)     0.0
+ * cotdg singularity  x = 180 k            INFINITY
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double tandg_lossth = 1.0e14;
+
+        XSF_HOST_DEVICE inline double tancot(double xx, int cotflg) {
+            double x;
+            int sign;
+
+            /* make argument positive but save the sign */
+            if (xx < 0) {
+                x = -xx;
+                sign = -1;
+            } else {
+                x = xx;
+                sign = 1;
+            }
+
+            if (x > detail::tandg_lossth) {
+                set_error("tandg", SF_ERROR_NO_RESULT, NULL);
+                return 0.0;
+            }
+
+            /* modulo 180 */
+            x = x - 180.0 * std::floor(x / 180.0);
+            if (cotflg) {
+                if (x <= 90.0) {
+                    x = 90.0 - x;
+                } else {
+                    x = x - 90.0;
+                    sign *= -1;
+                }
+            } else {
+                if (x > 90.0) {
+                    x = 180.0 - x;
+                    sign *= -1;
+                }
+            }
+            if (x == 0.0) {
+                return 0.0;
+            } else if (x == 45.0) {
+                return sign * 1.0;
+            } else if (x == 90.0) {
+                set_error((cotflg ? "cotdg" : "tandg"), SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            }
+            /* x is now transformed into [0, 90) */
+            return sign * std::tan(x * detail::PI180);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double tandg(double x) { return (detail::tancot(x, 0)); }
+
+    XSF_HOST_DEVICE inline double cotdg(double x) { return (detail::tancot(x, 1)); }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h
new file mode 100644
index 0000000000000000000000000000000000000000..47dcdbe6ab3c72e91dcd13f7f432572260ca3c62
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h
@@ -0,0 +1,58 @@
+/* Translated into C++ by SciPy developers in 2024.
+ *
+ * Original author: Josh Wilson, 2020.
+ */
+
+/*
+ * Implement sin(pi * x) and cos(pi * x) for real x. Since the periods
+ * of these functions are integral (and thus representable in double
+ * precision), it's possible to compute them with greater accuracy
+ * than sin(x) and cos(x).
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    /* Compute sin(pi * x). */
+    template 
+    XSF_HOST_DEVICE T sinpi(T x) {
+        T s = 1.0;
+
+        if (x < 0.0) {
+            x = -x;
+            s = -1.0;
+        }
+
+        T r = std::fmod(x, 2.0);
+        if (r < 0.5) {
+            return s * std::sin(M_PI * r);
+        } else if (r > 1.5) {
+            return s * std::sin(M_PI * (r - 2.0));
+        } else {
+            return -s * std::sin(M_PI * (r - 1.0));
+        }
+    }
+
+    /* Compute cos(pi * x) */
+    template 
+    XSF_HOST_DEVICE T cospi(T x) {
+        if (x < 0.0) {
+            x = -x;
+        }
+
+        T r = std::fmod(x, 2.0);
+        if (r == 0.5) {
+            // We don't want to return -0.0
+            return 0.0;
+        }
+        if (r < 1.0) {
+            return -std::sin(M_PI * (r - 0.5));
+        } else {
+            return std::sin(M_PI * (r - 1.5));
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h
new file mode 100644
index 0000000000000000000000000000000000000000..eb045edda2122e206fc866b180c1fbd71670a553
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h
@@ -0,0 +1,186 @@
+/* Translated into C++ by SciPy developers in 2024. */
+
+/*                                                     unity.c
+ *
+ * Relative error approximations for function arguments near
+ * unity.
+ *
+ *    log1p(x) = log(1+x)
+ *    expm1(x) = exp(x) - 1
+ *    cosm1(x) = cos(x) - 1
+ *    lgam1p(x) = lgam(1+x)
+ *
+ */
+
+/* Scipy changes:
+ * - 06-10-2016: added lgam1p
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "polevl.h"
+#include "zeta.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* log1p(x) = log(1 + x)  */
+
+        /* Coefficients for log(1+x) = x - x**2/2 + x**3 P(x)/Q(x)
+         * 1/sqrt(2) <= x < sqrt(2)
+         * Theoretical peak relative error = 2.32e-20
+         */
+
+        constexpr double unity_LP[] = {
+            4.5270000862445199635215E-5, 4.9854102823193375972212E-1, 6.5787325942061044846969E0,
+            2.9911919328553073277375E1,  6.0949667980987787057556E1,  5.7112963590585538103336E1,
+            2.0039553499201281259648E1,
+        };
+
+        constexpr double unity_LQ[] = {
+            /* 1.0000000000000000000000E0, */
+            1.5062909083469192043167E1, 8.3047565967967209469434E1, 2.2176239823732856465394E2,
+            3.0909872225312059774938E2, 2.1642788614495947685003E2, 6.0118660497603843919306E1,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double log1p(double x) {
+        double z;
+
+        z = 1.0 + x;
+        if ((z < M_SQRT1_2) || (z > M_SQRT2))
+            return (std::log(z));
+        z = x * x;
+        z = -0.5 * z + x * (z * polevl(x, detail::unity_LP, 6) / p1evl(x, detail::unity_LQ, 6));
+        return (x + z);
+    }
+
+    /* log(1 + x) - x */
+    XSF_HOST_DEVICE inline double log1pmx(double x) {
+        if (std::abs(x) < 0.5) {
+            uint64_t n;
+            double xfac = x;
+            double term;
+            double res = 0;
+
+            for (n = 2; n < detail::MAXITER; n++) {
+                xfac *= -x;
+                term = xfac / n;
+                res += term;
+                if (std::abs(term) < detail::MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+            return res;
+        } else {
+            return log1p(x) - x;
+        }
+    }
+
+    /* expm1(x) = exp(x) - 1  */
+
+    /*  e^x =  1 + 2x P(x^2)/( Q(x^2) - P(x^2) )
+     * -0.5 <= x <= 0.5
+     */
+
+    namespace detail {
+
+        constexpr double unity_EP[3] = {
+            1.2617719307481059087798E-4,
+            3.0299440770744196129956E-2,
+            9.9999999999999999991025E-1,
+        };
+
+        constexpr double unity_EQ[4] = {
+            3.0019850513866445504159E-6,
+            2.5244834034968410419224E-3,
+            2.2726554820815502876593E-1,
+            2.0000000000000000000897E0,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double expm1(double x) {
+        double r, xx;
+
+        if (!std::isfinite(x)) {
+            if (std::isnan(x)) {
+                return x;
+            } else if (x > 0) {
+                return x;
+            } else {
+                return -1.0;
+            }
+        }
+        if ((x < -0.5) || (x > 0.5))
+            return (std::exp(x) - 1.0);
+        xx = x * x;
+        r = x * polevl(xx, detail::unity_EP, 2);
+        r = r / (polevl(xx, detail::unity_EQ, 3) - r);
+        return (r + r);
+    }
+
+    /* cosm1(x) = cos(x) - 1  */
+
+    namespace detail {
+        constexpr double unity_coscof[7] = {
+            4.7377507964246204691685E-14, -1.1470284843425359765671E-11, 2.0876754287081521758361E-9,
+            -2.7557319214999787979814E-7, 2.4801587301570552304991E-5,   -1.3888888888888872993737E-3,
+            4.1666666666666666609054E-2,
+        };
+
+    }
+
+    XSF_HOST_DEVICE inline double cosm1(double x) {
+        double xx;
+
+        if ((x < -M_PI_4) || (x > M_PI_4))
+            return (std::cos(x) - 1.0);
+        xx = x * x;
+        xx = -0.5 * xx + xx * xx * polevl(xx, detail::unity_coscof, 6);
+        return xx;
+    }
+
+    namespace detail {
+        /* Compute lgam(x + 1) around x = 0 using its Taylor series. */
+        XSF_HOST_DEVICE inline double lgam1p_taylor(double x) {
+            int n;
+            double xfac, coeff, res;
+
+            if (x == 0) {
+                return 0;
+            }
+            res = -SCIPY_EULER * x;
+            xfac = -x;
+            for (n = 2; n < 42; n++) {
+                xfac *= -x;
+                coeff = xsf::cephes::zeta(n, 1) * xfac / n;
+                res += coeff;
+                if (std::abs(coeff) < detail::MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+
+            return res;
+        }
+    } // namespace detail
+
+    /* Compute lgam(x + 1). */
+    XSF_HOST_DEVICE inline double lgam1p(double x) {
+        if (std::abs(x) <= 0.5) {
+            return detail::lgam1p_taylor(x);
+        } else if (std::abs(x - 1) < 0.5) {
+            return std::log(x) + detail::lgam1p_taylor(x - 1);
+        } else {
+            return lgam(x + 1);
+        }
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h
new file mode 100644
index 0000000000000000000000000000000000000000..6f9d68e0bdced0edf70c17cdacf9a676341a908a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h
@@ -0,0 +1,172 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     zeta.c
+ *
+ *     Riemann zeta function of two arguments
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, q, y, zeta();
+ *
+ * y = zeta( x, q );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *
+ *                 inf.
+ *                  -        -x
+ *   zeta(x,q)  =   >   (k+q)
+ *                  -
+ *                 k=0
+ *
+ * where x > 1 and q is not a negative integer or zero.
+ * The Euler-Maclaurin summation formula is used to obtain
+ * the expansion
+ *
+ *                n
+ *                -       -x
+ * zeta(x,q)  =   >  (k+q)
+ *                -
+ *               k=1
+ *
+ *           1-x                 inf.  B   x(x+1)...(x+2j)
+ *      (n+q)           1         -     2j
+ *  +  ---------  -  -------  +   >    --------------------
+ *        x-1              x      -                   x+2j+1
+ *                   2(n+q)      j=1       (2j)! (n+q)
+ *
+ * where the B2j are Bernoulli numbers.  Note that (see zetac.c)
+ * zeta(x,1) = zetac(x) + 1.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *
+ *
+ * REFERENCE:
+ *
+ * Gradshteyn, I. S., and I. M. Ryzhik, Tables of Integrals,
+ * Series, and Products, p. 1073; Academic Press, 1980.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Expansion coefficients
+         * for Euler-Maclaurin summation formula
+         * (2k)! / B2k
+         * where B2k are Bernoulli numbers
+         */
+        constexpr double zeta_A[] = {
+            12.0,
+            -720.0,
+            30240.0,
+            -1209600.0,
+            47900160.0,
+            -1.8924375803183791606e9, /*1.307674368e12/691 */
+            7.47242496e10,
+            -2.950130727918164224e12,  /*1.067062284288e16/3617 */
+            1.1646782814350067249e14,  /*5.109094217170944e18/43867 */
+            -4.5979787224074726105e15, /*8.028576626982912e20/174611 */
+            1.8152105401943546773e17,  /*1.5511210043330985984e23/854513 */
+            -7.1661652561756670113e18  /*1.6938241367317436694528e27/236364091 */
+        };
+
+        /* 30 Nov 86 -- error in third coefficient fixed */
+    } // namespace detail
+
+    XSF_HOST_DEVICE double inline zeta(double x, double q) {
+        int i;
+        double a, b, k, s, t, w;
+
+        if (x == 1.0)
+            goto retinf;
+
+        if (x < 1.0) {
+        domerr:
+            set_error("zeta", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        if (q <= 0.0) {
+            if (q == floor(q)) {
+                set_error("zeta", SF_ERROR_SINGULAR, NULL);
+            retinf:
+                return (std::numeric_limits::infinity());
+            }
+            if (x != std::floor(x))
+                goto domerr; /* because q^-x not defined */
+        }
+
+        /* Asymptotic expansion
+         * https://dlmf.nist.gov/25.11#E43
+         */
+        if (q > 1e8) {
+            return (1 / (x - 1) + 1 / (2 * q)) * std::pow(q, 1 - x);
+        }
+
+        /* Euler-Maclaurin summation formula */
+
+        /* Permit negative q but continue sum until n+q > +9 .
+         * This case should be handled by a reflection formula.
+         * If q<0 and x is an integer, there is a relation to
+         * the polyGamma function.
+         */
+        s = std::pow(q, -x);
+        a = q;
+        i = 0;
+        b = 0.0;
+        while ((i < 9) || (a <= 9.0)) {
+            i += 1;
+            a += 1.0;
+            b = std::pow(a, -x);
+            s += b;
+            if (std::abs(b / s) < detail::MACHEP)
+                goto done;
+        }
+
+        w = a;
+        s += b * w / (x - 1.0);
+        s -= 0.5 * b;
+        a = 1.0;
+        k = 0.0;
+        for (i = 0; i < 12; i++) {
+            a *= x + k;
+            b /= w;
+            t = a * b / detail::zeta_A[i];
+            s = s + t;
+            t = std::abs(t / s);
+            if (t < detail::MACHEP)
+                goto done;
+            k += 1.0;
+            a *= x + k;
+            b /= w;
+            k += 1.0;
+        }
+    done:
+        return (s);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h
new file mode 100644
index 0000000000000000000000000000000000000000..5cb40ed1e1e095a8c99414f891a697c263845784
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h
@@ -0,0 +1,304 @@
+#pragma once
+
+// Define math constants if they are not available
+#ifndef M_E
+#define M_E 2.71828182845904523536
+#endif
+
+#ifndef M_LOG2E
+#define M_LOG2E 1.44269504088896340736
+#endif
+
+#ifndef M_LOG10E
+#define M_LOG10E 0.434294481903251827651
+#endif
+
+#ifndef M_LN2
+#define M_LN2 0.693147180559945309417
+#endif
+
+#ifndef M_LN10
+#define M_LN10 2.30258509299404568402
+#endif
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+#ifndef M_PI_2
+#define M_PI_2 1.57079632679489661923
+#endif
+
+#ifndef M_PI_4
+#define M_PI_4 0.785398163397448309616
+#endif
+
+#ifndef M_1_PI
+#define M_1_PI 0.318309886183790671538
+#endif
+
+#ifndef M_2_PI
+#define M_2_PI 0.636619772367581343076
+#endif
+
+#ifndef M_2_SQRTPI
+#define M_2_SQRTPI 1.12837916709551257390
+#endif
+
+#ifndef M_SQRT2
+#define M_SQRT2 1.41421356237309504880
+#endif
+
+#ifndef M_SQRT1_2
+#define M_SQRT1_2 0.707106781186547524401
+#endif
+
+#ifdef __CUDACC__
+#define XSF_HOST_DEVICE __host__ __device__
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// Fallback to global namespace for functions unsupported on NVRTC Jit
+#ifdef _LIBCUDACXX_COMPILER_NVRTC
+#include 
+#endif
+
+namespace std {
+
+XSF_HOST_DEVICE inline double abs(double num) { return cuda::std::abs(num); }
+
+XSF_HOST_DEVICE inline double exp(double num) { return cuda::std::exp(num); }
+
+XSF_HOST_DEVICE inline double log(double num) { return cuda::std::log(num); }
+
+XSF_HOST_DEVICE inline double sqrt(double num) { return cuda::std::sqrt(num); }
+
+XSF_HOST_DEVICE inline bool isinf(double num) { return cuda::std::isinf(num); }
+
+XSF_HOST_DEVICE inline bool isnan(double num) { return cuda::std::isnan(num); }
+
+XSF_HOST_DEVICE inline bool isfinite(double num) { return cuda::std::isfinite(num); }
+
+XSF_HOST_DEVICE inline double pow(double x, double y) { return cuda::std::pow(x, y); }
+
+XSF_HOST_DEVICE inline double sin(double x) { return cuda::std::sin(x); }
+
+XSF_HOST_DEVICE inline double cos(double x) { return cuda::std::cos(x); }
+
+XSF_HOST_DEVICE inline double tan(double x) { return cuda::std::tan(x); }
+
+XSF_HOST_DEVICE inline double atan(double x) { return cuda::std::atan(x); }
+
+XSF_HOST_DEVICE inline double acos(double x) { return cuda::std::acos(x); }
+
+XSF_HOST_DEVICE inline double sinh(double x) { return cuda::std::sinh(x); }
+
+XSF_HOST_DEVICE inline double cosh(double x) { return cuda::std::cosh(x); }
+
+XSF_HOST_DEVICE inline double asinh(double x) { return cuda::std::asinh(x); }
+
+XSF_HOST_DEVICE inline bool signbit(double x) { return cuda::std::signbit(x); }
+
+// Fallback to global namespace for functions unsupported on NVRTC
+#ifndef _LIBCUDACXX_COMPILER_NVRTC
+XSF_HOST_DEVICE inline double ceil(double x) { return cuda::std::ceil(x); }
+XSF_HOST_DEVICE inline double floor(double x) { return cuda::std::floor(x); }
+XSF_HOST_DEVICE inline double round(double x) { return cuda::std::round(x); }
+XSF_HOST_DEVICE inline double trunc(double x) { return cuda::std::trunc(x); }
+XSF_HOST_DEVICE inline double fma(double x, double y, double z) { return cuda::std::fma(x, y, z); }
+XSF_HOST_DEVICE inline double copysign(double x, double y) { return cuda::std::copysign(x, y); }
+XSF_HOST_DEVICE inline double modf(double value, double *iptr) { return cuda::std::modf(value, iptr); }
+XSF_HOST_DEVICE inline double fmax(double x, double y) { return cuda::std::fmax(x, y); }
+XSF_HOST_DEVICE inline double fmin(double x, double y) { return cuda::std::fmin(x, y); }
+XSF_HOST_DEVICE inline double log10(double num) { return cuda::std::log10(num); }
+XSF_HOST_DEVICE inline double log1p(double num) { return cuda::std::log1p(num); }
+XSF_HOST_DEVICE inline double frexp(double num, int *exp) { return cuda::std::frexp(num, exp); }
+XSF_HOST_DEVICE inline double ldexp(double num, int exp) { return cuda::std::ldexp(num, exp); }
+XSF_HOST_DEVICE inline double fmod(double x, double y) { return cuda::std::fmod(x, y); }
+XSF_HOST_DEVICE inline double nextafter(double from, double to) { return cuda::std::nextafter(from, to); }
+#else
+XSF_HOST_DEVICE inline double ceil(double x) { return ::ceil(x); }
+XSF_HOST_DEVICE inline double floor(double x) { return ::floor(x); }
+XSF_HOST_DEVICE inline double round(double x) { return ::round(x); }
+XSF_HOST_DEVICE inline double trunc(double x) { return ::trunc(x); }
+XSF_HOST_DEVICE inline double fma(double x, double y, double z) { return ::fma(x, y, z); }
+XSF_HOST_DEVICE inline double copysign(double x, double y) { return ::copysign(x, y); }
+XSF_HOST_DEVICE inline double modf(double value, double *iptr) { return ::modf(value, iptr); }
+XSF_HOST_DEVICE inline double fmax(double x, double y) { return ::fmax(x, y); }
+XSF_HOST_DEVICE inline double fmin(double x, double y) { return ::fmin(x, y); }
+XSF_HOST_DEVICE inline double log10(double num) { return ::log10(num); }
+XSF_HOST_DEVICE inline double log1p(double num) { return ::log1p(num); }
+XSF_HOST_DEVICE inline double frexp(double num, int *exp) { return ::frexp(num, exp); }
+XSF_HOST_DEVICE inline double ldexp(double num, int exp) { return ::ldexp(num, exp); }
+XSF_HOST_DEVICE inline double fmod(double x, double y) { return ::fmod(x, y); }
+XSF_HOST_DEVICE inline double nextafter(double from, double to) { return ::nextafter(from, to); }
+#endif
+
+template 
+XSF_HOST_DEVICE void swap(T &a, T &b) {
+    cuda::std::swap(a, b);
+}
+
+// Reimplement std::clamp until it's available in CuPy
+template 
+XSF_HOST_DEVICE constexpr T clamp(T &v, T &lo, T &hi) {
+    return v < lo ? lo : (v > hi ? lo : v);
+}
+
+template 
+using numeric_limits = cuda::std::numeric_limits;
+
+// Must use thrust for complex types in order to support CuPy
+template 
+using complex = thrust::complex;
+
+template 
+XSF_HOST_DEVICE T abs(const complex &z) {
+    return thrust::abs(z);
+}
+
+template 
+XSF_HOST_DEVICE complex exp(const complex &z) {
+    return thrust::exp(z);
+}
+
+template 
+XSF_HOST_DEVICE complex log(const complex &z) {
+    return thrust::log(z);
+}
+
+template 
+XSF_HOST_DEVICE T norm(const complex &z) {
+    return thrust::norm(z);
+}
+
+template 
+XSF_HOST_DEVICE complex sqrt(const complex &z) {
+    return thrust::sqrt(z);
+}
+
+template 
+XSF_HOST_DEVICE complex conj(const complex &z) {
+    return thrust::conj(z);
+}
+
+template 
+XSF_HOST_DEVICE complex pow(const complex &x, const complex &y) {
+    return thrust::pow(x, y);
+}
+
+template 
+XSF_HOST_DEVICE complex pow(const complex &x, const T &y) {
+    return thrust::pow(x, y);
+}
+
+// Other types and utilities
+template 
+using is_floating_point = cuda::std::is_floating_point;
+
+template 
+using enable_if = cuda::std::enable_if;
+
+template 
+using decay = cuda::std::decay;
+
+template 
+using invoke_result = cuda::std::invoke_result;
+
+template 
+using pair = cuda::std::pair;
+
+template 
+using tuple = cuda::std::tuple;
+
+using cuda::std::ptrdiff_t;
+using cuda::std::size_t;
+using cuda::std::uint64_t;
+
+#define XSF_ASSERT(a)
+
+} // namespace std
+
+#else
+#define XSF_HOST_DEVICE
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifdef DEBUG
+#define XSF_ASSERT(a) assert(a)
+#else
+#define XSF_ASSERT(a)
+#endif
+
+namespace xsf {
+
+// basic
+using std::abs;
+
+// exponential
+using std::exp;
+
+// power
+using std::sqrt;
+
+// trigonometric
+using std::cos;
+using std::sin;
+
+// floating-point manipulation
+using std::copysign;
+
+// classification and comparison
+using std::isfinite;
+using std::isinf;
+using std::isnan;
+using std::signbit;
+
+// complex
+using std::imag;
+using std::real;
+
+template 
+struct remove_complex {
+    using type = T;
+};
+
+template 
+struct remove_complex> {
+    using type = T;
+};
+
+template 
+using remove_complex_t = typename remove_complex::type;
+
+template 
+struct complex_type {
+    using type = std::complex;
+};
+
+template 
+using complex_type_t = typename complex_type::type;
+
+template 
+using complex = complex_type_t;
+
+} // namespace xsf
+
+#endif
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..db51362ce03907ee7c86c0995836e6d5d18160c6
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h
@@ -0,0 +1,205 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header comment appears below.
+ */
+
+/* An implementation of the digamma function for complex arguments.
+ *
+ * Author: Josh Wilson
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * Sources:
+ * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ *
+ * [2] mpmath (version 0.19), http://mpmath.org
+ */
+
+#pragma once
+
+#include "cephes/psi.h"
+#include "cephes/zeta.h"
+#include "config.h"
+#include "error.h"
+#include "trig.h"
+
+namespace xsf {
+namespace detail {
+    // All of the following were computed with mpmath
+    // Location of the positive root
+    constexpr double digamma_posroot = 1.4616321449683623;
+    // Value of the positive root
+    constexpr double digamma_posrootval = -9.2412655217294275e-17;
+    // Location of the negative root
+    constexpr double digamma_negroot = -0.504083008264455409;
+    // Value of the negative root
+    constexpr double digamma_negrootval = 7.2897639029768949e-17;
+
+    template 
+    XSF_HOST_DEVICE T digamma_zeta_series(T z, double root, double rootval) {
+        T res = rootval;
+        T coeff = -1.0;
+
+        z = z - root;
+        T term;
+        for (int n = 1; n < 100; n++) {
+            coeff *= -z;
+            term = coeff * cephes::zeta(n + 1, root);
+            res += term;
+            if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) {
+                break;
+            }
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex
+    digamma_forward_recurrence(std::complex z, std::complex psiz, int n) {
+        /* Compute digamma(z + n) using digamma(z) using the recurrence
+         * relation
+         *
+         * digamma(z + 1) = digamma(z) + 1/z.
+         *
+         * See https://dlmf.nist.gov/5.5#E2 */
+        std::complex res = psiz;
+
+        for (int k = 0; k < n; k++) {
+            res += 1.0 / (z + static_cast(k));
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex
+    digamma_backward_recurrence(std::complex z, std::complex psiz, int n) {
+        /* Compute digamma(z - n) using digamma(z) and a recurrence relation. */
+        std::complex res = psiz;
+
+        for (int k = 1; k < n + 1; k++) {
+            res -= 1.0 / (z - static_cast(k));
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex digamma_asymptotic_series(std::complex z) {
+        /* Evaluate digamma using an asymptotic series. See
+         *
+         * https://dlmf.nist.gov/5.11#E2 */
+        double bernoulli2k[] = {0.166666666666666667,   -0.0333333333333333333, 0.0238095238095238095,
+                                -0.0333333333333333333, 0.0757575757575757576,  -0.253113553113553114,
+                                1.16666666666666667,    -7.09215686274509804,   54.9711779448621554,
+                                -529.124242424242424,   6192.12318840579710,    -86580.2531135531136,
+                                1425517.16666666667,    -27298231.0678160920,   601580873.900642368,
+                                -15116315767.0921569};
+        std::complex rzz = 1.0 / z / z;
+        std::complex zfac = 1.0;
+        std::complex term;
+        std::complex res;
+
+        if (!(std::isfinite(z.real()) && std::isfinite(z.imag()))) {
+            /* Check for infinity (or nan) and return early.
+             * Result of division by complex infinity is implementation dependent.
+             * and has been observed to vary between C++ stdlib and CUDA stdlib.
+             */
+            return std::log(z);
+        }
+
+        res = std::log(z) - 0.5 / z;
+
+        for (int k = 1; k < 17; k++) {
+            zfac *= rzz;
+            term = -bernoulli2k[k - 1] * zfac / (2 * static_cast(k));
+            res += term;
+            if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) {
+                break;
+            }
+        }
+        return res;
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline double digamma(double z) {
+    /* Wrap Cephes' psi to take advantage of the series expansion around
+     * the smallest negative zero.
+     */
+    if (std::abs(z - detail::digamma_negroot) < 0.3) {
+        return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval);
+    }
+    return cephes::psi(z);
+}
+
+XSF_HOST_DEVICE inline float digamma(float z) { return static_cast(digamma(static_cast(z))); }
+
+XSF_HOST_DEVICE inline std::complex digamma(std::complex z) {
+    /*
+     * Compute the digamma function for complex arguments. The strategy
+     * is:
+     *
+     * - Around the two zeros closest to the origin (posroot and negroot)
+     * use a Taylor series with precomputed zero order coefficient.
+     * - If close to the origin, use a recurrence relation to step away
+     * from the origin.
+     * - If close to the negative real axis, use the reflection formula
+     * to move to the right halfplane.
+     * - If |z| is large (> 16), use the asymptotic series.
+     * - If |z| is small, use a recurrence relation to make |z| large
+     * enough to use the asymptotic series.
+     */
+    double absz = std::abs(z);
+    std::complex res = 0;
+    /* Use the asymptotic series for z away from the negative real axis
+     * with abs(z) > smallabsz. */
+    int smallabsz = 16;
+    /* Use the reflection principle for z with z.real < 0 that are within
+     * smallimag of the negative real axis.
+     * int smallimag = 6  # unused below except in a comment */
+
+    if (z.real() <= 0.0 && std::ceil(z.real()) == z) {
+        // Poles
+        set_error("digamma", SF_ERROR_SINGULAR, NULL);
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (std::abs(z - detail::digamma_negroot) < 0.3) {
+        // First negative root.
+        return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval);
+    }
+
+    if (z.real() < 0 and std::abs(z.imag()) < smallabsz) {
+        /* Reflection formula for digamma. See
+         *
+         *https://dlmf.nist.gov/5.5#E4
+         */
+        res = -M_PI * cospi(z) / sinpi(z);
+        z = 1.0 - z;
+        absz = std::abs(z);
+    }
+
+    if (absz < 0.5) {
+        /* Use one step of the recurrence relation to step away from
+         * the pole. */
+        res = -1.0 / z;
+        z += 1.0;
+        absz = std::abs(z);
+    }
+
+    if (std::abs(z - detail::digamma_posroot) < 0.5) {
+        res += detail::digamma_zeta_series(z, detail::digamma_posroot, detail::digamma_posrootval);
+    } else if (absz > smallabsz) {
+        res += detail::digamma_asymptotic_series(z);
+    } else if (z.real() >= 0.0) {
+        double n = std::trunc(smallabsz - absz) + 1;
+        std::complex init = detail::digamma_asymptotic_series(z + n);
+        res += detail::digamma_backward_recurrence(z + n, init, n);
+    } else {
+        // z.real() < 0, absz < smallabsz, and z.imag() > smallimag
+        double n = std::trunc(smallabsz - absz) - 1;
+        std::complex init = detail::digamma_asymptotic_series(z - n);
+        res += detail::digamma_forward_recurrence(z - n, init, n);
+    }
+    return res;
+}
+
+XSF_HOST_DEVICE inline std::complex digamma(std::complex z) {
+    return static_cast>(digamma(static_cast>(z)));
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h
new file mode 100644
index 0000000000000000000000000000000000000000..7221b5e6c4051b82f80dfb360f9fab896be6a6bd
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h
@@ -0,0 +1,57 @@
+#pragma once
+
+typedef enum {
+    SF_ERROR_OK = 0,    /* no error */
+    SF_ERROR_SINGULAR,  /* singularity encountered */
+    SF_ERROR_UNDERFLOW, /* floating point underflow */
+    SF_ERROR_OVERFLOW,  /* floating point overflow */
+    SF_ERROR_SLOW,      /* too many iterations required */
+    SF_ERROR_LOSS,      /* loss of precision */
+    SF_ERROR_NO_RESULT, /* no result obtained */
+    SF_ERROR_DOMAIN,    /* out of domain */
+    SF_ERROR_ARG,       /* invalid input parameter */
+    SF_ERROR_OTHER,     /* unclassified error */
+    SF_ERROR_MEMORY,    /* memory allocation failed */
+    SF_ERROR__LAST
+} sf_error_t;
+
+#ifdef __cplusplus
+
+#include "config.h"
+
+namespace xsf {
+
+#ifndef SP_SPECFUN_ERROR
+XSF_HOST_DEVICE inline void set_error(const char *func_name, sf_error_t code, const char *fmt, ...) {
+    // nothing
+}
+#else
+void set_error(const char *func_name, sf_error_t code, const char *fmt, ...);
+#endif
+
+template 
+XSF_HOST_DEVICE void set_error_and_nan(const char *name, sf_error_t code, T &value) {
+    if (code != SF_ERROR_OK) {
+        set_error(name, code, nullptr);
+
+        if (code == SF_ERROR_DOMAIN || code == SF_ERROR_OVERFLOW || code == SF_ERROR_NO_RESULT) {
+            value = std::numeric_limits::quiet_NaN();
+        }
+    }
+}
+
+template 
+XSF_HOST_DEVICE void set_error_and_nan(const char *name, sf_error_t code, std::complex &value) {
+    if (code != SF_ERROR_OK) {
+        set_error(name, code, nullptr);
+
+        if (code == SF_ERROR_DOMAIN || code == SF_ERROR_OVERFLOW || code == SF_ERROR_NO_RESULT) {
+            value.real(std::numeric_limits::quiet_NaN());
+            value.imag(std::numeric_limits::quiet_NaN());
+        }
+    }
+}
+
+} // namespace xsf
+
+#endif
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h
new file mode 100644
index 0000000000000000000000000000000000000000..b126fb608fae47620431e05cea21ac66e6847e59
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h
@@ -0,0 +1,47 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+/* Evaluate polynomials.
+ *
+ * All of the coefficients are stored in reverse order, i.e. if the
+ * polynomial is
+ *
+ *     u_n x^n + u_{n - 1} x^{n - 1} + ... + u_0,
+ *
+ * then coeffs[0] = u_n, coeffs[1] = u_{n - 1}, ..., coeffs[n] = u_0.
+ *
+ * References
+ * ----------
+ * [1] Knuth, "The Art of Computer Programming, Volume II"
+ */
+
+#pragma once
+
+#include "config.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline std::complex cevalpoly(const double *coeffs, int degree, std::complex z) {
+    /* Evaluate a polynomial with real coefficients at a complex point.
+     *
+     * Uses equation (3) in section 4.6.4 of [1]. Note that it is more
+     * efficient than Horner's method.
+     */
+    double a = coeffs[0];
+    double b = coeffs[1];
+    double r = 2 * z.real();
+    double s = std::norm(z);
+    double tmp;
+
+    for (int j = 2; j < degree + 1; j++) {
+        tmp = b;
+        b = std::fma(-s, a, coeffs[j]);
+        a = std::fma(r, a, tmp);
+    }
+
+    return z * a + b;
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h
new file mode 100644
index 0000000000000000000000000000000000000000..600448aeb7f7a525aef76d4c59c31fa2489bcb1d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h
@@ -0,0 +1,266 @@
+/* The functions exp1, expi below are based on translations of the Fortran code
+ * by Shanjie Zhang and Jianming Jin from the book
+ *
+ *  Shanjie Zhang, Jianming Jin,
+ *  Computation of Special Functions,
+ *  Wiley, 1996,
+ *  ISBN: 0-471-11963-6,
+ *  LC: QA351.C45.
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+#include "cephes/const.h"
+
+
+namespace xsf {
+
+
+XSF_HOST_DEVICE inline double exp1(double x) {
+    // ============================================
+    // Purpose: Compute exponential integral E1(x)
+    // Input :  x  --- Argument of E1(x)
+    // Output:  E1 --- E1(x)  ( x > 0 )
+    // ============================================
+    int k, m;
+    double e1, r, t, t0;
+    constexpr double ga = cephes::detail::SCIPY_EULER;
+
+    if (x == 0.0) {
+	return std::numeric_limits::infinity();
+    }
+    if (x <= 1.0) {
+        e1 = 1.0;
+        r = 1.0;
+        for (k = 1; k < 26; k++) {
+            r = -r*k*x/std::pow(k+1.0, 2);
+            e1 += r;
+            if (std::abs(r) <= std::abs(e1)*1e-15) { break; }
+        }
+        return -ga - std::log(x) + x*e1;
+    }
+    m = 20 + (int)(80.0/x);
+    t0 = 0.0;
+    for (k = m; k > 0; k--) {
+	t0 = k / (1.0 + k / (x+t0));
+    }
+    t = 1.0 / (x + t0);
+    return std::exp(-x)*t;
+}
+
+XSF_HOST_DEVICE inline float exp1(float x) { return exp1(static_cast(x)); }
+
+XSF_HOST_DEVICE inline std::complex exp1(std::complex z) {
+    // ====================================================
+    // Purpose: Compute complex exponential integral E1(z)
+    // Input :  z   --- Argument of E1(z)
+    // Output:  CE1 --- E1(z)
+    // ====================================================
+    constexpr double el = cephes::detail::SCIPY_EULER;
+    int k;
+    std::complex ce1, cr, zc, zd, zdc;
+    double x = z.real();
+    double a0 = std::abs(z);
+    // Continued fraction converges slowly near negative real axis,
+    // so use power series in a wedge around it until radius 40.0
+    double xt = -2.0*std::abs(z.imag());
+
+    if (a0 == 0.0) { return std::numeric_limits::infinity(); }
+    if ((a0 < 5.0) || ((x < xt) && (a0 < 40.0))) {
+        // Power series
+        ce1 = 1.0;
+        cr = 1.0;
+        for (k = 1; k < 501; k++) {
+            cr = -cr*z*static_cast(k / std::pow(k + 1, 2));
+            ce1 += cr;
+            if (std::abs(cr) < std::abs(ce1)*1e-15) { break; }
+        }
+        if ((x <= 0.0) && (z.imag() == 0.0)) {
+            //Careful on the branch cut -- use the sign of the imaginary part
+            // to get the right sign on the factor if pi.
+            ce1 = -el - std::log(-z) + z*ce1 - std::copysign(M_PI, z.imag())*std::complex(0.0, 1.0);
+        } else {
+            ce1 = -el - std::log(z) + z*ce1;
+        }
+    } else {
+        // Continued fraction https://dlmf.nist.gov/6.9
+        //                  1     1     1     2     2     3     3
+        // E1 = exp(-z) * ----- ----- ----- ----- ----- ----- ----- ...
+        //                Z +   1 +   Z +   1 +   Z +   1 +   Z +
+        zc = 0.0;
+        zd = static_cast(1) / z;
+        zdc = zd;
+        zc += zdc;
+        for (k = 1; k < 501; k++) {
+            zd = static_cast(1) / (zd*static_cast(k) + static_cast(1));
+            zdc *= (zd - static_cast(1));
+            zc += zdc;
+
+            zd = static_cast(1) / (zd*static_cast(k) + z);
+            zdc *= (z*zd - static_cast(1));
+            zc += zdc;
+            if ((std::abs(zdc) <= std::abs(zc)*1e-15) && (k > 20)) { break; }
+        }
+        ce1 = std::exp(-z)*zc;
+        if ((x <= 0.0) && (z.imag() == 0.0)) {
+            ce1 -= M_PI*std::complex(0.0, 1.0);
+        }
+    }
+    return ce1;
+}
+
+XSF_HOST_DEVICE inline std::complex exp1(std::complex z) {
+    return static_cast>(exp1(static_cast>(z)));
+}
+
+XSF_HOST_DEVICE inline double expi(double x) {
+    // ============================================
+    // Purpose: Compute exponential integral Ei(x)
+    // Input :  x  --- Argument of Ei(x)
+    // Output:  EI --- Ei(x)
+    // ============================================
+
+    constexpr double ga = cephes::detail::SCIPY_EULER;
+    double ei, r;
+
+    if (x == 0.0) {
+        ei = -std::numeric_limits::infinity();
+    } else if (x < 0) {
+        ei = -exp1(-x);
+    } else if (std::abs(x) <= 40.0) {
+        // Power series around x=0
+        ei = 1.0;
+        r = 1.0;
+
+        for (int k = 1; k <= 100; k++) {
+            r = r * k * x / ((k + 1.0) * (k + 1.0));
+            ei += r;
+            if (std::abs(r / ei) <= 1.0e-15) { break; }
+        }
+        ei = ga + std::log(x) + x * ei;
+    } else {
+        // Asymptotic expansion (the series is not convergent)
+        ei = 1.0;
+        r = 1.0;
+        for (int k = 1; k <= 20; k++) {
+            r = r * k / x;
+            ei += r;
+        }
+        ei = std::exp(x) / x * ei;
+    }
+    return ei;
+}
+
+XSF_HOST_DEVICE inline float expi(float x) { return expi(static_cast(x)); }
+    
+std::complex expi(std::complex z) {
+    // ============================================
+    // Purpose: Compute exponential integral Ei(x)
+    // Input :  x  --- Complex argument of Ei(x)
+    // Output:  EI --- Ei(x)
+    // ============================================
+
+    std::complex cei;
+    cei = - exp1(-z);
+    if (z.imag() > 0.0) {
+        cei += std::complex(0.0, M_PI);
+    } else if (z.imag() < 0.0 ) {
+        cei -= std::complex(0.0, M_PI);
+    } else {
+        if (z.real() > 0.0) {
+            cei += std::complex(0.0, copysign(M_PI, z.imag()));
+        }
+    }
+    return cei;
+}
+
+
+XSF_HOST_DEVICE inline std::complex expi(std::complex z) {
+    return static_cast>(expi(static_cast>(z)));
+}
+
+namespace detail {
+
+    //
+    // Compute a factor of the exponential integral E1.
+    // This is used in scaled_exp1(x) for moderate values of x.
+    //
+    // The function uses the continued fraction expansion given in equation 5.1.22
+    // of Abramowitz & Stegun, "Handbook of Mathematical Functions".
+    // For n=1, this is
+    //
+    //    E1(x) = exp(-x)*C(x)
+    //
+    // where C(x), expressed in the notation used in A&S, is the continued fraction
+    //
+    //            1    1    1    2    2    3    3
+    //    C(x) = ---  ---  ---  ---  ---  ---  ---  ...
+    //           x +  1 +  x +  1 +  x +  1 +  x +
+    //
+    // Here, we pull a factor of 1/z out of C(x), so
+    //
+    //    E1(x) = (exp(-x)/x)*F(x)
+    //
+    // and a bit of algebra gives the continued fraction expansion of F(x) to be
+    //
+    //            1    1    1    2    2    3    3
+    //    F(x) = ---  ---  ---  ---  ---  ---  ---  ...
+    //           1 +  x +  1 +  x +  1 +  x +  1 +
+    //
+    XSF_HOST_DEVICE inline double expint1_factor_cont_frac(double x) {
+        // The number of terms to use in the truncated continued fraction
+        // depends on x.  Larger values of x require fewer terms.
+        int m = 20 + (int) (80.0 / x);
+        double t0 = 0.0;
+        for (int k = m; k > 0; --k) {
+            t0 = k / (x + k / (1 + t0));
+        }
+        return 1 / (1 + t0);
+    }
+
+} // namespace detail
+
+//
+// Scaled version  of the exponential integral E_1(x).
+//
+// Factor E_1(x) as
+//
+//    E_1(x) = exp(-x)/x * F(x)
+//
+// This function computes F(x).
+//
+// F(x) has the properties:
+//  * F(0) = 0
+//  * F is increasing on [0, inf)
+//  * lim_{x->inf} F(x) = 1.
+//
+XSF_HOST_DEVICE inline double scaled_exp1(double x) {
+    if (x < 0) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    if (x == 0) {
+        return 0.0;
+    }
+
+    if (x <= 1) {
+        // For small x, the naive implementation is sufficiently accurate.
+        return x * std::exp(x) * exp1(x);
+    }
+
+    if (x <= 1250) {
+        // For moderate x, use the continued fraction expansion.
+        return detail::expint1_factor_cont_frac(x);
+    }
+
+    // For large x, use the asymptotic expansion.  This is equation 5.1.51
+    // from Abramowitz & Stegun, "Handbook of Mathematical Functions".
+    return 1 + (-1 + (2 + (-6 + (24 - 120 / x) / x) / x) / x) / x;
+}
+
+XSF_HOST_DEVICE inline float scaled_exp1(float x) { return scaled_exp1(static_cast(x)); }
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h
new file mode 100644
index 0000000000000000000000000000000000000000..9d4eff7532202380bcd5dbd2978d46d5f613d5eb
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h
@@ -0,0 +1,694 @@
+/* Implementation of Gauss's hypergeometric function for complex values.
+ *
+ * This implementation is based on the Fortran implementation by Shanjie Zhang and
+ * Jianming Jin included in specfun.f [1]_.  Computation of Gauss's hypergeometric
+ * function involves handling a patchwork of special cases. By default the Zhang and
+ * Jin implementation has been followed as closely as possible except for situations where
+ * an improvement was obvious. We've attempted to document the reasons behind decisions
+ * made by Zhang and Jin and to document the reasons for deviating from their implementation
+ * when this has been done. References to the NIST Digital Library of Mathematical
+ * Functions [2]_ have been added where they are appropriate. The review paper by
+ * Pearson et al [3]_ is an excellent resource for best practices for numerical
+ * computation of hypergeometric functions. We have followed this review paper
+ * when making improvements to and correcting defects in Zhang and Jin's
+ * implementation. When Pearson et al propose several competing alternatives for a
+ * given case, we've used our best judgment to decide on the method to use.
+ *
+ * Author: Albert Steppi
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * References
+ * ----------
+ * .. [1] S. Zhang and J.M. Jin, "Computation of Special Functions", Wiley 1996
+ * .. [2] NIST Digital Library of Mathematical Functions. http://dlmf.nist.gov/,
+ *        Release 1.1.1 of 2021-03-15. F. W. J. Olver, A. B. Olde Daalhuis,
+ *        D. W. Lozier, B. I. Schneider, R. F. Boisvert, C. W. Clark, B. R. Miller,
+ *        B. V. Saunders, H. S. Cohl, and M. A. McClain, eds.
+ * .. [3] Pearson, J.W., Olver, S. & Porter, M.A.
+ *        "Numerical methods for the computation of the confluent and Gauss
+ *        hypergeometric functions."
+ *        Numer Algor 74, 821-866 (2017). https://doi.org/10.1007/s11075-016-0173-0
+ * .. [4] Raimundas Vidunas, "Degenerate Gauss Hypergeometric Functions",
+ *        Kyushu Journal of Mathematics, 2007, Volume 61, Issue 1, Pages 109-135,
+ * .. [5] López, J.L., Temme, N.M. New series expansions of the Gauss hypergeometric
+ *        function. Adv Comput Math 39, 349-365 (2013).
+ *        https://doi.org/10.1007/s10444-012-9283-y
+ * """
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+#include "tools.h"
+
+#include "binom.h"
+#include "cephes/gamma.h"
+#include "cephes/lanczos.h"
+#include "cephes/poch.h"
+#include "cephes/hyp2f1.h"
+#include "digamma.h"
+
+namespace xsf {
+namespace detail {
+    constexpr double hyp2f1_EPS = 1e-15;
+    /* The original implementation in SciPy from Zhang and Jin used 1500 for the
+     * maximum number of series iterations in some cases and 500 in others.
+     * Through the empirical results on the test cases in
+     * scipy/special/_precompute/hyp2f1_data.py, it was determined that these values
+     * can lead to early termination of series which would have eventually converged
+     * at a reasonable level of accuracy. We've bumped the iteration limit to 3000,
+     * and may adjust it again based on further analysis. */
+    constexpr std::uint64_t hyp2f1_MAXITER = 3000;
+
+    XSF_HOST_DEVICE inline double four_gammas_lanczos(double u, double v, double w, double x) {
+        /* Compute ratio of gamma functions using lanczos approximation.
+         *
+         * Computes gamma(u)*gamma(v)/(gamma(w)*gamma(x))
+         *
+         * It is assumed that x = u + v - w, but it is left to the user to
+         * ensure this.
+         *
+         * The lanczos approximation takes the form
+         *
+         * gamma(x) = factor(x) * lanczos_sum_expg_scaled(x)
+         *
+         * where factor(x) = ((x + lanczos_g - 0.5)/e)**(x - 0.5).
+         *
+         * The formula above is only valid for x >= 0.5, but can be extended to
+         * x < 0.5 with the reflection principle.
+         *
+         * Using the lanczos approximation when computing this ratio of gamma functions
+         * allows factors to be combined analytically to avoid underflow and overflow
+         * and produce a more accurate result. The condition x = u + v - w makes it
+         * possible to cancel the factors in the expression
+         *
+         * factor(u) * factor(v) / (factor(w) * factor(x))
+         *
+         * by taking one factor and absorbing it into the others. Currently, this
+         * implementation takes the factor corresponding to the argument with largest
+         * absolute value and absorbs it into the others.
+         *
+         * Since this is only called internally by four_gammas. It is assumed that
+         * |u| >= |v| and |w| >= |x|.
+         */
+
+        /* The below implementation may incorrectly return finite results
+         * at poles of the gamma function. Handle these cases explicitly. */
+        if ((u == std::trunc(u) && u <= 0) || (v == std::trunc(v) && v <= 0)) {
+            /* Return nan if numerator has pole. Diverges to +- infinity
+             * depending on direction so value is undefined. */
+            return std::numeric_limits::quiet_NaN();
+        }
+        if ((w == std::trunc(w) && w <= 0) || (x == std::trunc(x) && x <= 0)) {
+            // Return 0 if denominator has pole but not numerator.
+            return 0.0;
+        }
+
+        double result = 1.0;
+        double ugh, vgh, wgh, xgh, u_prime, v_prime, w_prime, x_prime;
+
+        if (u >= 0.5) {
+            result *= cephes::lanczos_sum_expg_scaled(u);
+            ugh = u + cephes::lanczos_g - 0.5;
+            u_prime = u;
+        } else {
+            result /= cephes::lanczos_sum_expg_scaled(1 - u) * std::sin(M_PI * u) * M_1_PI;
+            ugh = 0.5 - u + cephes::lanczos_g;
+            u_prime = 1 - u;
+        }
+
+        if (v >= 0.5) {
+            result *= cephes::lanczos_sum_expg_scaled(v);
+            vgh = v + cephes::lanczos_g - 0.5;
+            v_prime = v;
+        } else {
+            result /= cephes::lanczos_sum_expg_scaled(1 - v) * std::sin(M_PI * v) * M_1_PI;
+            vgh = 0.5 - v + cephes::lanczos_g;
+            v_prime = 1 - v;
+        }
+
+        if (w >= 0.5) {
+            result /= cephes::lanczos_sum_expg_scaled(w);
+            wgh = w + cephes::lanczos_g - 0.5;
+            w_prime = w;
+        } else {
+            result *= cephes::lanczos_sum_expg_scaled(1 - w) * std::sin(M_PI * w) * M_1_PI;
+            wgh = 0.5 - w + cephes::lanczos_g;
+            w_prime = 1 - w;
+        }
+
+        if (x >= 0.5) {
+            result /= cephes::lanczos_sum_expg_scaled(x);
+            xgh = x + cephes::lanczos_g - 0.5;
+            x_prime = x;
+        } else {
+            result *= cephes::lanczos_sum_expg_scaled(1 - x) * std::sin(M_PI * x) * M_1_PI;
+            xgh = 0.5 - x + cephes::lanczos_g;
+            x_prime = 1 - x;
+        }
+
+        if (std::abs(u) >= std::abs(w)) {
+            // u has greatest absolute value. Absorb ugh into the others.
+            if (std::abs((v_prime - u_prime) * (v - 0.5)) < 100 * ugh and v > 100) {
+                /* Special case where base is close to 1. Condition taken from
+                 * Boost's beta function implementation. */
+                result *= std::exp((v - 0.5) * std::log1p((v_prime - u_prime) / ugh));
+            } else {
+                result *= std::pow(vgh / ugh, v - 0.5);
+            }
+
+            if (std::abs((u_prime - w_prime) * (w - 0.5)) < 100 * wgh and u > 100) {
+                result *= std::exp((w - 0.5) * std::log1p((u_prime - w_prime) / wgh));
+            } else {
+                result *= std::pow(ugh / wgh, w - 0.5);
+            }
+
+            if (std::abs((u_prime - x_prime) * (x - 0.5)) < 100 * xgh and u > 100) {
+                result *= std::exp((x - 0.5) * std::log1p((u_prime - x_prime) / xgh));
+            } else {
+                result *= std::pow(ugh / xgh, x - 0.5);
+            }
+        } else {
+            // w has greatest absolute value. Absorb wgh into the others.
+            if (std::abs((u_prime - w_prime) * (u - 0.5)) < 100 * wgh and u > 100) {
+                result *= std::exp((u - 0.5) * std::log1p((u_prime - w_prime) / wgh));
+            } else {
+                result *= pow(ugh / wgh, u - 0.5);
+            }
+            if (std::abs((v_prime - w_prime) * (v - 0.5)) < 100 * wgh and v > 100) {
+                result *= std::exp((v - 0.5) * std::log1p((v_prime - w_prime) / wgh));
+            } else {
+                result *= std::pow(vgh / wgh, v - 0.5);
+            }
+            if (std::abs((w_prime - x_prime) * (x - 0.5)) < 100 * xgh and x > 100) {
+                result *= std::exp((x - 0.5) * std::log1p((w_prime - x_prime) / xgh));
+            } else {
+                result *= std::pow(wgh / xgh, x - 0.5);
+            }
+        }
+        // This exhausts all cases because we assume |u| >= |v| and |w| >= |x|.
+
+        return result;
+    }
+
+    XSF_HOST_DEVICE inline double four_gammas(double u, double v, double w, double x) {
+        double result;
+
+        // Without loss of generality, ensure |u| >= |v| and |w| >= |x|.
+        if (std::abs(v) > std::abs(u)) {
+            std::swap(u, v);
+        }
+        if (std::abs(x) > std::abs(w)) {
+            std::swap(x, w);
+        }
+        /* Direct ratio tends to be more accurate for arguments in this range. Range
+         * chosen empirically based on the relevant benchmarks in
+         * scipy/special/_precompute/hyp2f1_data.py */
+        if (std::abs(u) <= 100 && std::abs(v) <= 100 && std::abs(w) <= 100 && std::abs(x) <= 100) {
+            result = cephes::Gamma(u) * cephes::Gamma(v) * (cephes::rgamma(w) * cephes::rgamma(x));
+            if (std::isfinite(result) && result != 0.0) {
+                return result;
+            }
+        }
+        result = four_gammas_lanczos(u, v, w, x);
+        if (std::isfinite(result) && result != 0.0) {
+            return result;
+        }
+        // If overflow or underflow, try again with logs.
+        result = std::exp(cephes::lgam(v) - cephes::lgam(x) + cephes::lgam(u) - cephes::lgam(w));
+        result *= cephes::gammasgn(u) * cephes::gammasgn(w) * cephes::gammasgn(v) * cephes::gammasgn(x);
+        return result;
+    }
+
+    class HypergeometricSeriesGenerator {
+        /* Maclaurin series for hyp2f1.
+         *
+         * Series is convergent for |z| < 1 but is only practical for numerical
+         * computation when |z| < 0.9.
+         */
+      public:
+        XSF_HOST_DEVICE HypergeometricSeriesGenerator(double a, double b, double c, std::complex z)
+            : a_(a), b_(b), c_(c), z_(z), term_(1.0), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex output = term_;
+            term_ = term_ * (a_ + k_) * (b_ + k_) / ((k_ + 1) * (c_ + k_)) * z_;
+            ++k_;
+            return output;
+        }
+
+      private:
+        double a_, b_, c_;
+        std::complex z_, term_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform1Generator {
+        /* 1 -z transformation of standard series.*/
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform1Generator(double a, double b, double c, std::complex z)
+            : factor1_(four_gammas(c, c - a - b, c - a, c - b)),
+              factor2_(four_gammas(c, a + b - c, a, b) * std::pow(1.0 - z, c - a - b)),
+              generator1_(HypergeometricSeriesGenerator(a, b, a + b - c + 1, 1.0 - z)),
+              generator2_(HypergeometricSeriesGenerator(c - a, c - b, c - a - b + 1, 1.0 - z)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            return factor1_ * generator1_() + factor2_ * generator2_();
+        }
+
+      private:
+        std::complex factor1_, factor2_;
+        HypergeometricSeriesGenerator generator1_, generator2_;
+    };
+
+    class Hyp2f1Transform1LimitSeriesGenerator {
+        /* 1 - z transform in limit as c - a - b approaches an integer m. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform1LimitSeriesGenerator(double a, double b, double m, std::complex z)
+            : d1_(xsf::digamma(a)), d2_(xsf::digamma(b)), d3_(xsf::digamma(1 + m)),
+              d4_(xsf::digamma(1.0)), a_(a), b_(b), m_(m), z_(z), log_1_z_(std::log(1.0 - z)),
+              factor_(cephes::rgamma(m + 1)), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term_ = (d1_ + d2_ - d3_ - d4_ + log_1_z_) * factor_;
+            // Use digamma(x + 1) = digamma(x) + 1/x
+            d1_ += 1 / (a_ + k_);       // d1 = digamma(a + k)
+            d2_ += 1 / (b_ + k_);       // d2 = digamma(b + k)
+            d3_ += 1 / (1.0 + m_ + k_); // d3 = digamma(1 + m + k)
+            d4_ += 1 / (1.0 + k_);      // d4 = digamma(1 + k)
+            factor_ *= (a_ + k_) * (b_ + k_) / ((k_ + 1.0) * (m_ + k_ + 1)) * (1.0 - z_);
+            ++k_;
+            return term_;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, m_;
+        std::complex z_, log_1_z_, factor_;
+        int k_;
+    };
+
+    class Hyp2f1Transform2Generator {
+        /* 1/z transformation of standard series.*/
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2Generator(double a, double b, double c, std::complex z)
+            : factor1_(four_gammas(c, b - a, b, c - a) * std::pow(-z, -a)),
+              factor2_(four_gammas(c, a - b, a, c - b) * std::pow(-z, -b)),
+              generator1_(HypergeometricSeriesGenerator(a, a - c + 1, a - b + 1, 1.0 / z)),
+              generator2_(HypergeometricSeriesGenerator(b, b - c + 1, b - a + 1, 1.0 / z)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            return factor1_ * generator1_() + factor2_ * generator2_();
+        }
+
+      private:
+        std::complex factor1_, factor2_;
+        HypergeometricSeriesGenerator generator1_, generator2_;
+    };
+
+    class Hyp2f1Transform2LimitSeriesGenerator {
+        /* 1/z transform in limit as a - b approaches a non-negative integer m. (Can swap a and b to
+         * handle the m a negative integer case. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitSeriesGenerator(double a, double b, double c, double m,
+                                                                 std::complex z)
+            : d1_(xsf::digamma(1.0)), d2_(xsf::digamma(1 + m)), d3_(xsf::digamma(a)),
+              d4_(xsf::digamma(c - a)), a_(a), b_(b), c_(c), m_(m), z_(z), log_neg_z_(std::log(-z)),
+              factor_(xsf::cephes::poch(b, m) * xsf::cephes::poch(1 - c + b, m) *
+                      xsf::cephes::rgamma(m + 1)),
+              k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term = (d1_ + d2_ - d3_ - d4_ + log_neg_z_) * factor_;
+            // Use digamma(x + 1) = digamma(x) + 1/x
+            d1_ += 1 / (1.0 + k_);         // d1 = digamma(1 + k)
+            d2_ += 1 / (1.0 + m_ + k_);    // d2 = digamma(1 + m + k)
+            d3_ += 1 / (a_ + k_);          // d3 = digamma(a + k)
+            d4_ -= 1 / (c_ - a_ - k_ - 1); // d4 = digamma(c - a - k)
+            factor_ *= (b_ + m_ + k_) * (1 - c_ + b_ + m_ + k_) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+            ++k_;
+            return term;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, c_, m_;
+        std::complex z_, log_neg_z_, factor_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform2LimitSeriesCminusAIntGenerator {
+        /* 1/z transform in limit as a - b approaches a non-negative integer m, and c - a approaches
+         * a positive integer n. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitSeriesCminusAIntGenerator(double a, double b, double c, double m,
+                                                                           double n, std::complex z)
+            : d1_(xsf::digamma(1.0)), d2_(xsf::digamma(1 + m)), d3_(xsf::digamma(a)),
+              d4_(xsf::digamma(n)), a_(a), b_(b), c_(c), m_(m), n_(n), z_(z), log_neg_z_(std::log(-z)),
+              factor_(xsf::cephes::poch(b, m) * xsf::cephes::poch(1 - c + b, m) *
+                      xsf::cephes::rgamma(m + 1)),
+              k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term;
+            if (k_ < n_) {
+                term = (d1_ + d2_ - d3_ - d4_ + log_neg_z_) * factor_;
+                // Use digamma(x + 1) = digamma(x) + 1/x
+                d1_ += 1 / (1.0 + k_);    // d1 = digamma(1 + k)
+                d2_ += 1 / (1 + m_ + k_); // d2 = digamma(1 + m + k)
+                d3_ += 1 / (a_ + k_);     // d3 = digamma(a + k)
+                d4_ -= 1 / (n_ - k_ - 1); // d4 = digamma(c - a - k)
+                factor_ *= (b_ + m_ + k_) * (1 - c_ + b_ + m_ + k_) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+                ++k_;
+                return term;
+            }
+            if (k_ == n_) {
+                /* When c - a approaches a positive integer and k_ >= c - a = n then
+                 * poch(1 - c + b + m + k) = poch(1 - c + a + k) = approaches zero and
+                 * digamma(c - a - k) approaches a pole. However we can use the limit
+                 * digamma(-n + epsilon) / gamma(-n + epsilon) -> (-1)**(n + 1) * (n+1)! as epsilon -> 0
+                 * to continue the series.
+                 *
+                 * poch(1 - c + b, m + k) = gamma(1 - c + b + m + k)/gamma(1 - c + b)
+                 *
+                 * If a - b is an integer and c - a is an integer, then a and b must both be integers, so assume
+                 * a and b are integers and take the limit as c approaches an integer.
+                 *
+                 * gamma(1 - c + epsilon + a + k)/gamma(1 - c - epsilon + b) =
+                 * (gamma(c + epsilon - b) / gamma(c + epsilon - a - k)) *
+                 * (sin(pi * (c + epsilon - b)) / sin(pi * (c + epsilon - a - k))) (reflection principle)
+                 *
+                 * In the limit as epsilon goes to zero, the ratio of sines will approach
+                 * (-1)**(a - b + k) = (-1)**(m + k)
+                 *
+                 * We may then replace
+                 *
+                 * poch(1 - c - epsilon + b, m + k)*digamma(c + epsilon - a - k)
+                 *
+                 * with
+                 *
+                 * (-1)**(a - b + k)*gamma(c + epsilon - b) * digamma(c + epsilon - a - k) / gamma(c + epsilon - a - k)
+                 *
+                 * and taking the limit epsilon -> 0 gives
+                 *
+                 * (-1)**(a - b + k) * gamma(c - b) * (-1)**(k + a - c + 1)(k + a - c)!
+                 * = (-1)**(c - b - 1)*Gamma(k + a - c + 1)
+                 */
+                factor_ = std::pow(-1, m_ + n_) * xsf::binom(c_ - 1, b_ - 1) *
+                          xsf::cephes::poch(c_ - a_ + 1, m_ - 1) / std::pow(z_, static_cast(k_));
+            }
+            term = factor_;
+            factor_ *= (b_ + m_ + k_) * (k_ + a_ - c_ + 1) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+            ++k_;
+            return term;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, c_, m_, n_;
+        std::complex z_, log_neg_z_, factor_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform2LimitFinitePartGenerator {
+        /* Initial finite sum in limit as a - b approaches a non-negative integer m. The limiting series
+         * for the 1 - z transform also has an initial finite sum, but it is a standard hypergeometric
+         * series. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitFinitePartGenerator(double b, double c, double m,
+                                                                     std::complex z)
+            : b_(b), c_(c), m_(m), z_(z), term_(cephes::Gamma(m) * cephes::rgamma(c - b)), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex output = term_;
+            term_ = term_ * (b_ + k_) * (c_ - b_ - k_ - 1) / ((k_ + 1) * (m_ - k_ - 1)) / z_;
+            ++k_;
+            return output;
+        }
+
+      private:
+        double b_, c_, m_;
+        std::complex z_, term_;
+        std::uint64_t k_;
+    };
+
+    class LopezTemmeSeriesGenerator {
+        /* Lopez-Temme Series for Gaussian hypergeometric function [4].
+         *
+         * Converges for all z with real(z) < 1, including in the regions surrounding
+         * the points exp(+- i*pi/3) that are not covered by any of the standard
+         * transformations.
+         */
+      public:
+        XSF_HOST_DEVICE LopezTemmeSeriesGenerator(double a, double b, double c, std::complex z)
+            : n_(0), a_(a), b_(b), c_(c), phi_previous_(1.0), phi_(1 - 2 * b / c), z_(z), Z_(a * z / (z - 2.0)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            if (n_ == 0) {
+                ++n_;
+                return 1.0;
+            }
+            if (n_ > 1) { // Update phi and Z for n>=2
+                double new_phi = ((n_ - 1) * phi_previous_ - (2.0 * b_ - c_) * phi_) / (c_ + (n_ - 1));
+                phi_previous_ = phi_;
+                phi_ = new_phi;
+                Z_ = Z_ * z_ / (z_ - 2.0) * ((a_ + (n_ - 1)) / n_);
+            }
+            ++n_;
+            return Z_ * phi_;
+        }
+
+      private:
+        std::uint64_t n_;
+        double a_, b_, c_, phi_previous_, phi_;
+        std::complex z_, Z_;
+    };
+
+    XSF_HOST_DEVICE std::complex hyp2f1_transform1_limiting_case(double a, double b, double c, double m,
+                                                                             std::complex z) {
+        /* 1 - z transform in limiting case where c - a - b approaches an integer m. */
+        std::complex result = 0.0;
+        if (m >= 0) {
+            if (m != 0) {
+                auto series_generator = HypergeometricSeriesGenerator(a, b, 1 - m, 1.0 - z);
+                result += four_gammas(m, c, a + m, b + m) * series_eval_fixed_length(series_generator,
+                                                                                     std::complex{0.0, 0.0},
+                                                                                     static_cast(m));
+            }
+            std::complex prefactor = std::pow(-1.0, m + 1) * xsf::cephes::Gamma(c) /
+                                             (xsf::cephes::Gamma(a) * xsf::cephes::Gamma(b)) *
+                                             std::pow(1.0 - z, m);
+            auto series_generator = Hyp2f1Transform1LimitSeriesGenerator(a + m, b + m, m, z);
+            result += prefactor * series_eval(series_generator, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        } else {
+            result = four_gammas(-m, c, a, b) * std::pow(1.0 - z, m);
+            auto series_generator1 = HypergeometricSeriesGenerator(a + m, b + m, 1 + m, 1.0 - z);
+            result *= series_eval_fixed_length(series_generator1, std::complex{0.0, 0.0},
+                                               static_cast(-m));
+            double prefactor = std::pow(-1.0, m + 1) * xsf::cephes::Gamma(c) *
+                               (xsf::cephes::rgamma(a + m) * xsf::cephes::rgamma(b + m));
+            auto series_generator2 = Hyp2f1Transform1LimitSeriesGenerator(a, b, -m, z);
+            result += prefactor * series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+    }
+
+    XSF_HOST_DEVICE std::complex hyp2f1_transform2_limiting_case(double a, double b, double c, double m,
+                                                                             std::complex z) {
+        /* 1 / z transform in limiting case where a - b approaches a non-negative integer m. Negative integer case
+         * can be handled by swapping a and b. */
+        auto series_generator1 = Hyp2f1Transform2LimitFinitePartGenerator(b, c, m, z);
+        std::complex result = cephes::Gamma(c) * cephes::rgamma(a) * std::pow(-z, -b);
+        result *=
+            series_eval_fixed_length(series_generator1, std::complex{0.0, 0.0}, static_cast(m));
+        std::complex prefactor = cephes::Gamma(c) * (cephes::rgamma(a) * cephes::rgamma(c - b) * std::pow(-z, -a));
+        double n = c - a;
+        if (abs(n - std::round(n)) < hyp2f1_EPS) {
+            auto series_generator2 = Hyp2f1Transform2LimitSeriesCminusAIntGenerator(a, b, c, m, n, z);
+            result += prefactor * series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+        auto series_generator2 = Hyp2f1Transform2LimitSeriesGenerator(a, b, c, m, z);
+        result += prefactor *
+                  series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS, hyp2f1_MAXITER, "hyp2f1");
+        return result;
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline std::complex hyp2f1(double a, double b, double c, std::complex z) {
+    /* Special Cases
+     * -----------------------------------------------------------------------
+     * Takes constant value 1 when a = 0 or b = 0, even if c is a non-positive
+     * integer. This follows mpmath. */
+    if (a == 0 || b == 0) {
+        return 1.0;
+    }
+    double z_abs = std::abs(z);
+    // Equals 1 when z i 0, unless c is 0.
+    if (z_abs == 0) {
+        if (c != 0) {
+            return 1.0;
+        } else {
+            // Returning real part NAN and imaginary part 0 follows mpmath.
+            return std::complex{std::numeric_limits::quiet_NaN(), 0};
+        }
+    }
+    bool a_neg_int = a == std::trunc(a) && a < 0;
+    bool b_neg_int = b == std::trunc(b) && b < 0;
+    bool c_non_pos_int = c == std::trunc(c) and c <= 0;
+    /* Diverges when c is a non-positive integer unless a is an integer with
+     * c <= a <= 0 or b is an integer with c <= b <= 0, (or z equals 0 with
+     * c != 0) Cases z = 0, a = 0, or b = 0 have already been handled. We follow
+     * mpmath in handling the degenerate cases where any of a, b, c are
+     * non-positive integers. See [3] for a treatment of degenerate cases. */
+    if (c_non_pos_int && !((a_neg_int && c <= a && a < 0) || (b_neg_int && c <= b && b < 0))) {
+        return std::complex{std::numeric_limits::infinity(), 0};
+    }
+    /* Reduces to a polynomial when a or b is a negative integer.
+     * If a and b are both negative integers, we take care to terminate
+     * the series at a or b of smaller magnitude. This is to ensure proper
+     * handling of situations like a < c < b <= 0, a, b, c all non-positive
+     * integers, where terminating at a would lead to a term of the form 0 / 0. */
+    double max_degree;
+    if (a_neg_int || b_neg_int) {
+        if (a_neg_int && b_neg_int) {
+            max_degree = a > b ? std::abs(a) : std::abs(b);
+        } else if (a_neg_int) {
+            max_degree = std::abs(a);
+        } else {
+            max_degree = std::abs(b);
+        }
+        if (max_degree <= (double) UINT64_MAX) {
+            auto series_generator = detail::HypergeometricSeriesGenerator(a, b, c, z);
+            return detail::series_eval_fixed_length(series_generator, std::complex{0.0, 0.0}, max_degree + 1);
+        } else {
+            set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+            return std::complex{std::numeric_limits::quiet_NaN(),
+                                        std::numeric_limits::quiet_NaN()};
+        }
+    }
+    // Kummer's Theorem for z = -1; c = 1 + a - b (DLMF 15.4.26)
+    if (std::abs(z + 1.0) < detail::hyp2f1_EPS && std::abs(1 + a - b - c) < detail::hyp2f1_EPS && !c_non_pos_int) {
+        return detail::four_gammas(a - b + 1, 0.5 * a + 1, a + 1, 0.5 * a - b + 1);
+    }
+    std::complex result;
+    bool c_minus_a_neg_int = c - a == std::trunc(c - a) && c - a < 0;
+    bool c_minus_b_neg_int = c - b == std::trunc(c - b) && c - b < 0;
+    /* If one of c - a or c - b is a negative integer, reduces to evaluating
+     * a polynomial through an Euler hypergeometric transformation.
+     * (DLMF 15.8.1) */
+    if (c_minus_a_neg_int || c_minus_b_neg_int) {
+        max_degree = c_minus_b_neg_int ? std::abs(c - b) : std::abs(c - a);
+        if (max_degree <= (double) UINT64_MAX) {
+            result = std::pow(1.0 - z, c - a - b);
+            auto series_generator = detail::HypergeometricSeriesGenerator(c - a, c - b, c, z);
+            result *=
+                detail::series_eval_fixed_length(series_generator, std::complex{0.0, 0.0}, max_degree + 2);
+            return result;
+        } else {
+            set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+            return std::complex{std::numeric_limits::quiet_NaN(),
+                                        std::numeric_limits::quiet_NaN()};
+        }
+    }
+    /* Diverges as real(z) -> 1 when c <= a + b.
+     * Todo: Actually check for overflow instead of using a fixed tolerance for
+     * all parameter combinations like in the Fortran original. */
+    if (std::abs(1 - z.real()) < detail::hyp2f1_EPS && z.imag() == 0 && c - a - b <= 0 && !c_non_pos_int) {
+        return std::complex{std::numeric_limits::infinity(), 0};
+    }
+    // Gauss's Summation Theorem for z = 1; c - a - b > 0 (DLMF 15.4.20).
+    if (z == 1.0 && c - a - b > 0 && !c_non_pos_int) {
+        return detail::four_gammas(c, c - a - b, c - a, c - b);
+    }
+    /* |z| < 0, z.real() >= 0. Use the Maclaurin Series.
+     * -----------------------------------------------------------------------
+     * Apply Euler Hypergeometric Transformation (DLMF 15.8.1) to reduce
+     * size of a and b if possible. We follow Zhang and Jin's
+     * implementation [1] although there is very likely a better heuristic
+     * to determine when this transformation should be applied. As it
+     * stands, this hurts precision in some cases. */
+    if (z_abs < 0.9 && z.real() >= 0) {
+        if (c - a < a && c - b < b) {
+            result = std::pow(1.0 - z, c - a - b);
+            auto series_generator = detail::HypergeometricSeriesGenerator(c - a, c - b, c, z);
+            result *= detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                          detail::hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+        auto series_generator = detail::HypergeometricSeriesGenerator(a, b, c, z);
+        return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                   detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* Points near exp(iπ/3), exp(-iπ/3) not handled by any of the standard
+     * transformations. Use series of López and Temme [5]. These regions
+     * were not correctly handled by Zhang and Jin's implementation.
+     * -------------------------------------------------------------------------*/
+    if (0.9 <= z_abs && z_abs < 1.1 && std::abs(1.0 - z) >= 0.9 && z.real() >= 0) {
+        /* This condition for applying Euler Transformation (DLMF 15.8.1)
+         * was determined empirically to work better for this case than that
+         * used in Zhang and Jin's implementation for |z| < 0.9,
+         *  real(z) >= 0. */
+        if ((c - a <= a && c - b < b) || (c - a < a && c - b <= b)) {
+            auto series_generator = detail::LopezTemmeSeriesGenerator(c - a, c - b, c, z);
+            result = std::pow(1.0 - 0.5 * z, a - c); // Lopez-Temme prefactor
+            result *= detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                          detail::hyp2f1_MAXITER, "hyp2f1");
+            return std::pow(1.0 - z, c - a - b) * result; // Euler transform prefactor.
+        }
+        auto series_generator = detail::LopezTemmeSeriesGenerator(a, b, c, z);
+        result = detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                     detail::hyp2f1_MAXITER, "hyp2f1");
+        return std::pow(1.0 - 0.5 * z, -a) * result; // Lopez-Temme prefactor.
+    }
+    /* z/(z - 1) transformation (DLMF 15.8.1). Avoids cancellation issues that
+     * occur with Maclaurin series for real(z) < 0.
+     * -------------------------------------------------------------------------*/
+    if (z_abs < 1.1 && z.real() < 0) {
+        if (0 < b && b < a && a < c) {
+            std::swap(a, b);
+        }
+        auto series_generator = detail::HypergeometricSeriesGenerator(a, c - b, c, z / (z - 1.0));
+        return std::pow(1.0 - z, -a) * detail::series_eval(series_generator, std::complex{0.0, 0.0},
+                                                           detail::hyp2f1_EPS, detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* 1 - z transformation (DLMF 15.8.4). */
+    if (0.9 <= z_abs && z_abs < 1.1) {
+        if (std::abs(c - a - b - std::round(c - a - b)) < detail::hyp2f1_EPS) {
+            // Removable singularity when c - a - b is an integer. Need to use limiting formula.
+            double m = std::round(c - a - b);
+            return detail::hyp2f1_transform1_limiting_case(a, b, c, m, z);
+        }
+        auto series_generator = detail::Hyp2f1Transform1Generator(a, b, c, z);
+        return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                   detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* 1/z transformation (DLMF 15.8.2). */
+    if (std::abs(a - b - std::round(a - b)) < detail::hyp2f1_EPS) {
+        if (b > a) {
+            std::swap(a, b);
+        }
+        double m = std::round(a - b);
+        return detail::hyp2f1_transform2_limiting_case(a, b, c, m, z);
+    }
+    auto series_generator = detail::Hyp2f1Transform2Generator(a, b, c, z);
+    return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                               detail::hyp2f1_MAXITER, "hyp2f1");
+}
+
+XSF_HOST_DEVICE inline std::complex hyp2f1(float a, float b, float c, std::complex x) {
+    return static_cast>(hyp2f1(static_cast(a), static_cast(b),
+                                                   static_cast(c), static_cast>(x)));
+}
+
+XSF_HOST_DEVICE inline double hyp2f1(double a, double b, double c, double x) { return cephes::hyp2f1(a, b, c, x); }
+
+XSF_HOST_DEVICE inline float hyp2f1(float a, float b, float c, float x) {
+    return hyp2f1(static_cast(a), static_cast(b), static_cast(c), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h
new file mode 100644
index 0000000000000000000000000000000000000000..e5dc871bd003937a483a39001d796b1bacc26d01
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h
@@ -0,0 +1,173 @@
+// Numerically stable computation of iv(v+1, x) / iv(v, x)
+
+#pragma once
+
+#include "config.h"
+#include "tools.h"
+#include "error.h"
+#include "cephes/dd_real.h"
+
+namespace xsf {
+
+/* Generates the "tail" of Perron's continued fraction for iv(v,x)/iv(v-1,x).
+ *
+ * The Perron continued fraction is studied in [1].  It is given by
+ *
+ *         iv(v, x)      x    -(2v+1)x   -(2v+3)x   -(2v+5)x
+ *   R := --------- = ------ ---------- ---------- ---------- ...
+ *        iv(v-1,x)   x+2v + 2(v+x)+1 + 2(v+x)+2 + 2(v+x)+3 +
+ *
+ * Given a suitable constant c, the continued fraction may be rearranged
+ * into the following form to avoid premature floating point overflow:
+ *
+ *        xc                -(2vc+c)(xc) -(2vc+3c)(xc) -(2vc+5c)(xc)
+ *   R = -----,  fc = 2vc + ------------ ------------- ------------- ...
+ *       xc+fc              2(vc+xc)+c + 2(vc+xc)+2c + 2(vc+xc)+3c +
+ *
+ * This class generates the fractions of fc after 2vc.
+ *
+ * [1] Gautschi, W. and Slavik, J. (1978). "On the computation of modified
+ *     Bessel function ratios." Mathematics of Computation, 32(143):865-875.
+ */
+template 
+struct IvRatioCFTailGenerator {
+
+    XSF_HOST_DEVICE IvRatioCFTailGenerator(T vc, T xc, T c) noexcept {
+        a0_ = -(2*vc-c)*xc;
+        as_ = -2*c*xc;
+        b0_ = 2*(vc+xc);
+        bs_ = c;
+        k_ = 0;
+    }
+
+    XSF_HOST_DEVICE std::pair operator()() noexcept {
+        using std::fma;
+        ++k_;
+        return {fma(static_cast(k_), as_, a0_),
+                fma(static_cast(k_), bs_, b0_)};
+    }
+
+private:
+    T a0_, as_;  // a[k] == a0 + as*k, k >= 1
+    T b0_, bs_;  // b[k] == b0 + bs*k, k >= 1
+    std::uint64_t k_; // current index
+};
+
+// Computes f(v, x) using Perron's continued fraction.
+//
+// T specifies the working type.  This allows the function to perform
+// calculations in a higher precision, such as double-double, even if
+// the return type is hardcoded to be double.
+template 
+XSF_HOST_DEVICE inline std::pair
+_iv_ratio_cf(double v, double x, bool complement) {
+
+    int e;
+    std::frexp(std::fmax(v, x), &e);
+    T c = T(std::ldexp(1, 2-e)); // rescaling multiplier
+    T vc = v * c;
+    T xc = x * c;
+
+    IvRatioCFTailGenerator cf(vc, xc, c);
+    auto [fc, terms] = detail::series_eval_kahan(
+        detail::continued_fraction_series(cf),
+        T(std::numeric_limits::epsilon()),
+        1000,
+        2*vc);
+
+    T ret = (complement ? fc : xc) / (xc + fc);
+    return {static_cast(ret), terms};
+}
+
+XSF_HOST_DEVICE inline double iv_ratio(double v, double x) {
+
+    if (std::isnan(v) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (v < 0.5 || x < 0) {
+        set_error("iv_ratio", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(v) && std::isinf(x)) {
+        // There is not a unique limit as both v and x tends to infinity.
+        set_error("iv_ratio", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        return x; // keep sign of x because iv_ratio is an odd function
+    }
+    if (std::isinf(v)) {
+        return 0.0;
+    }
+    if (std::isinf(x)) {
+        return 1.0;
+    }
+
+    auto [ret, terms] = _iv_ratio_cf(v, x, false);
+    if (terms == 0) { // failed to converge; should not happen
+        set_error("iv_ratio", SF_ERROR_NO_RESULT, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    return ret;
+}
+
+XSF_HOST_DEVICE inline float iv_ratio(float v, float x) {
+    return iv_ratio(static_cast(v), static_cast(x));
+}
+
+XSF_HOST_DEVICE inline double iv_ratio_c(double v, double x) {
+
+    if (std::isnan(v) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (v < 0.5 || x < 0) {
+        set_error("iv_ratio_c", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(v) && std::isinf(x)) {
+        // There is not a unique limit as both v and x tends to infinity.
+        set_error("iv_ratio_c", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        return 1.0;
+    }
+    if (std::isinf(v)) {
+        return 1.0;
+    }
+    if (std::isinf(x)) {
+        return 0.0;
+    }
+
+    if (v >= 1) {
+        // Numerical experiments show that evaluating the Perron c.f.
+        // in double precision is sufficiently accurate if v >= 1.
+        auto [ret, terms] = _iv_ratio_cf(v, x, true);
+        if (terms == 0) { // failed to converge; should not happen
+            set_error("iv_ratio_c", SF_ERROR_NO_RESULT, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        return ret;
+    } else if (v > 0.5) {
+        // double-double arithmetic is needed for 0.5 < v < 1 to
+        // achieve relative error on the scale of machine precision.
+        using cephes::detail::double_double;
+        auto [ret, terms] = _iv_ratio_cf(v, x, true);
+        if (terms == 0) { // failed to converge; should not happen
+            set_error("iv_ratio_c", SF_ERROR_NO_RESULT, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        return ret;
+    } else {
+        // The previous branch (v > 0.5) also works for v == 0.5, but
+        // the closed-form formula "1 - tanh(x)" is more efficient.
+        double t = std::exp(-2*x);
+        return (2 * t) / (1 + t);
+    }
+}
+
+XSF_HOST_DEVICE inline float iv_ratio_c(float v, float x) {
+    return iv_ratio_c(static_cast(v), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h
new file mode 100644
index 0000000000000000000000000000000000000000..9eb1882eaec464b5e5dcf47f2168f9125996a816
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h
@@ -0,0 +1,150 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of the Lambert W function [1]. Based on MPMath
+ *  Implementation [2], and documentation [3].
+ *
+ * Copyright: Yosef Meller, 2009
+ * Author email: mellerf@netvision.net.il
+ *
+ * Distributed under the same license as SciPy
+ *
+ *
+ * References:
+ * [1] On the Lambert W function, Adv. Comp. Math. 5 (1996) 329-359,
+ *     available online: https://web.archive.org/web/20230123211413/https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
+ * [2] mpmath source code,
+ https://github.com/mpmath/mpmath/blob/c5939823669e1bcce151d89261b802fe0d8978b4/mpmath/functions/functions.py#L435-L461
+ * [3]
+ https://web.archive.org/web/20230504171447/https://mpmath.org/doc/current/functions/powers.html#lambert-w-function
+ *
+
+ * TODO: use a series expansion when extremely close to the branch point
+ * at `-1/e` and make sure that the proper branch is chosen there.
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+#include "evalpoly.h"
+
+namespace xsf {
+constexpr double EXPN1 = 0.36787944117144232159553; // exp(-1)
+constexpr double OMEGA = 0.56714329040978387299997; // W(1, 0)
+
+namespace detail {
+    XSF_HOST_DEVICE inline std::complex lambertw_branchpt(std::complex z) {
+        // Series for W(z, 0) around the branch point; see 4.22 in [1].
+        double coeffs[] = {-1.0 / 3.0, 1.0, -1.0};
+        std::complex p = std::sqrt(2.0 * (M_E * z + 1.0));
+
+        return cevalpoly(coeffs, 2, p);
+    }
+
+    XSF_HOST_DEVICE inline std::complex lambertw_pade0(std::complex z) {
+        // (3, 2) Pade approximation for W(z, 0) around 0.
+        double num[] = {12.85106382978723404255, 12.34042553191489361902, 1.0};
+        double denom[] = {32.53191489361702127660, 14.34042553191489361702, 1.0};
+
+        /* This only gets evaluated close to 0, so we don't need a more
+         * careful algorithm that avoids overflow in the numerator for
+         * large z. */
+        return z * cevalpoly(num, 2, z) / cevalpoly(denom, 2, z);
+    }
+
+    XSF_HOST_DEVICE inline std::complex lambertw_asy(std::complex z, long k) {
+        /* Compute the W function using the first two terms of the
+         * asymptotic series. See 4.20 in [1].
+         */
+        std::complex w = std::log(z) + 2.0 * M_PI * k * std::complex(0, 1);
+        return w - std::log(w);
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, double tol) {
+    double absz;
+    std::complex w;
+    std::complex ew, wew, wewz, wn;
+
+    if (std::isnan(z.real()) || std::isnan(z.imag())) {
+        return z;
+    }
+    if (z.real() == std::numeric_limits::infinity()) {
+        return z + 2.0 * M_PI * k * std::complex(0, 1);
+    }
+    if (z.real() == -std::numeric_limits::infinity()) {
+        return -z + (2.0 * M_PI * k + M_PI) * std::complex(0, 1);
+    }
+    if (z == 0.0) {
+        if (k == 0) {
+            return z;
+        }
+        set_error("lambertw", SF_ERROR_SINGULAR, NULL);
+        return -std::numeric_limits::infinity();
+    }
+    if (z == 1.0 && k == 0) {
+        // Split out this case because the asymptotic series blows up
+        return OMEGA;
+    }
+
+    absz = std::abs(z);
+    // Get an initial guess for Halley's method
+    if (k == 0) {
+        if (std::abs(z + EXPN1) < 0.3) {
+            w = detail::lambertw_branchpt(z);
+        } else if (-1.0 < z.real() && z.real() < 1.5 && std::abs(z.imag()) < 1.0 &&
+                   -2.5 * std::abs(z.imag()) - 0.2 < z.real()) {
+            /* Empirically determined decision boundary where the Pade
+             * approximation is more accurate. */
+            w = detail::lambertw_pade0(z);
+        } else {
+            w = detail::lambertw_asy(z, k);
+        }
+    } else if (k == -1) {
+        if (absz <= EXPN1 && z.imag() == 0.0 && z.real() < 0.0) {
+            w = std::log(-z.real());
+        } else {
+            w = detail::lambertw_asy(z, k);
+        }
+    } else {
+        w = detail::lambertw_asy(z, k);
+    }
+
+    // Halley's method; see 5.9 in [1]
+    if (w.real() >= 0) {
+        // Rearrange the formula to avoid overflow in exp
+        for (int i = 0; i < 100; i++) {
+            ew = std::exp(-w);
+            wewz = w - z * ew;
+            wn = w - wewz / (w + 1.0 - (w + 2.0) * wewz / (2.0 * w + 2.0));
+            if (std::abs(wn - w) <= tol * std::abs(wn)) {
+                return wn;
+            }
+            w = wn;
+        }
+    } else {
+        for (int i = 0; i < 100; i++) {
+            ew = std::exp(w);
+            wew = w * ew;
+            wewz = wew - z;
+            wn = w - wewz / (wew + ew - (w + 2.0) * wewz / (2.0 * w + 2.0));
+            if (std::abs(wn - w) <= tol * std::abs(wn)) {
+                return wn;
+            }
+            w = wn;
+        }
+    }
+
+    set_error("lambertw", SF_ERROR_SLOW, "iteration failed to converge: %g + %gj", z.real(), z.imag());
+    return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+}
+
+XSF_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, float tol) {
+    return static_cast>(
+        lambertw(static_cast>(z), k, static_cast(tol)));
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..eaae479b2054177153b8671e7fe3174f1b09f20a
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h
@@ -0,0 +1,163 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header comment appears below.
+ */
+
+/* An implementation of the principal branch of the logarithm of
+ * Gamma. Also contains implementations of Gamma and 1/Gamma which are
+ * easily computed from log-Gamma.
+ *
+ * Author: Josh Wilson
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * References
+ * ----------
+ * [1] Hare, "Computing the Principal Branch of log-Gamma",
+ *     Journal of Algorithms, 1997.
+ *
+ * [2] Julia,
+ *     https://github.com/JuliaLang/julia/blob/master/base/special/gamma.jl
+ */
+
+#pragma once
+
+#include "cephes/gamma.h"
+#include "cephes/rgamma.h"
+#include "config.h"
+#include "error.h"
+#include "evalpoly.h"
+#include "trig.h"
+#include "zlog1.h"
+
+namespace xsf {
+
+namespace detail {
+    constexpr double loggamma_SMALLX = 7;
+    constexpr double loggamma_SMALLY = 7;
+    constexpr double loggamma_HLOG2PI = 0.918938533204672742;      // log(2*pi)/2
+    constexpr double loggamma_LOGPI = 1.1447298858494001741434262; // log(pi)
+    constexpr double loggamma_TAYLOR_RADIUS = 0.2;
+
+    XSF_HOST_DEVICE std::complex loggamma_stirling(std::complex z) {
+        /* Stirling series for log-Gamma
+         *
+         * The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the
+         * (2*n)th Bernoulli number. See (1.1) in [1].
+         */
+        double coeffs[] = {-2.955065359477124183E-2,  6.4102564102564102564E-3, -1.9175269175269175269E-3,
+                           8.4175084175084175084E-4,  -5.952380952380952381E-4, 7.9365079365079365079E-4,
+                           -2.7777777777777777778E-3, 8.3333333333333333333E-2};
+        std::complex rz = 1.0 / z;
+        std::complex rzz = rz / z;
+
+        return (z - 0.5) * std::log(z) - z + loggamma_HLOG2PI + rz * cevalpoly(coeffs, 7, rzz);
+    }
+
+    XSF_HOST_DEVICE std::complex loggamma_recurrence(std::complex z) {
+        /* Backward recurrence relation.
+         *
+         * See Proposition 2.2 in [1] and the Julia implementation [2].
+         *
+         */
+        int signflips = 0;
+        int sb = 0;
+        std::complex shiftprod = z;
+
+        z += 1.0;
+        int nsb;
+        while (z.real() <= loggamma_SMALLX) {
+            shiftprod *= z;
+            nsb = std::signbit(shiftprod.imag());
+            signflips += nsb != 0 && sb == 0 ? 1 : 0;
+            sb = nsb;
+            z += 1.0;
+        }
+        return loggamma_stirling(z) - std::log(shiftprod) - signflips * 2 * M_PI * std::complex(0, 1);
+    }
+
+    XSF_HOST_DEVICE std::complex loggamma_taylor(std::complex z) {
+        /* Taylor series for log-Gamma around z = 1.
+         *
+         * It is
+         *
+         * loggamma(z + 1) = -gamma*z + zeta(2)*z**2/2 - zeta(3)*z**3/3 ...
+         *
+         * where gamma is the Euler-Mascheroni constant.
+         */
+
+        double coeffs[] = {
+            -4.3478266053040259361E-2, 4.5454556293204669442E-2, -4.7619070330142227991E-2, 5.000004769810169364E-2,
+            -5.2631679379616660734E-2, 5.5555767627403611102E-2, -5.8823978658684582339E-2, 6.2500955141213040742E-2,
+            -6.6668705882420468033E-2, 7.1432946295361336059E-2, -7.6932516411352191473E-2, 8.3353840546109004025E-2,
+            -9.0954017145829042233E-2, 1.0009945751278180853E-1, -1.1133426586956469049E-1, 1.2550966952474304242E-1,
+            -1.4404989676884611812E-1, 1.6955717699740818995E-1, -2.0738555102867398527E-1, 2.7058080842778454788E-1,
+            -4.0068563438653142847E-1, 8.2246703342411321824E-1, -5.7721566490153286061E-1};
+
+        z -= 1.0;
+        return z * cevalpoly(coeffs, 22, z);
+    }
+} // namespace detail
+
+XSF_HOST_DEVICE inline double loggamma(double x) {
+    if (x < 0.0) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    return cephes::lgam(x);
+}
+
+XSF_HOST_DEVICE inline float loggamma(float x) { return loggamma(static_cast(x)); }
+
+XSF_HOST_DEVICE inline std::complex loggamma(std::complex z) {
+    // Compute the principal branch of log-Gamma
+
+    if (std::isnan(z.real()) || std::isnan(z.imag())) {
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (z.real() <= 0 and z == std::floor(z.real())) {
+        set_error("loggamma", SF_ERROR_SINGULAR, NULL);
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (z.real() > detail::loggamma_SMALLX || std::abs(z.imag()) > detail::loggamma_SMALLY) {
+        return detail::loggamma_stirling(z);
+    }
+    if (std::abs(z - 1.0) < detail::loggamma_TAYLOR_RADIUS) {
+        return detail::loggamma_taylor(z);
+    }
+    if (std::abs(z - 2.0) < detail::loggamma_TAYLOR_RADIUS) {
+        // Recurrence relation and the Taylor series around 1.
+        return detail::zlog1(z - 1.0) + detail::loggamma_taylor(z - 1.0);
+    }
+    if (z.real() < 0.1) {
+        // Reflection formula; see Proposition 3.1 in [1]
+        double tmp = std::copysign(2 * M_PI, z.imag()) * std::floor(0.5 * z.real() + 0.25);
+        return std::complex(detail::loggamma_LOGPI, tmp) - std::log(sinpi(z)) - loggamma(1.0 - z);
+    }
+    if (std::signbit(z.imag()) == 0) {
+        // z.imag() >= 0 but is not -0.0
+        return detail::loggamma_recurrence(z);
+    }
+    return std::conj(detail::loggamma_recurrence(std::conj(z)));
+}
+
+XSF_HOST_DEVICE inline std::complex loggamma(std::complex z) {
+    return static_cast>(loggamma(static_cast>(z)));
+}
+
+XSF_HOST_DEVICE inline double rgamma(double z) { return cephes::rgamma(z); }
+
+XSF_HOST_DEVICE inline float rgamma(float z) { return rgamma(static_cast(z)); }
+
+XSF_HOST_DEVICE inline std::complex rgamma(std::complex z) {
+    // Compute 1/Gamma(z) using loggamma.
+    if (z.real() <= 0 && z == std::floor(z.real())) {
+        // Zeros at 0, -1, -2, ...
+        return 0.0;
+    }
+    return std::exp(-loggamma(z));
+}
+
+XSF_HOST_DEVICE inline std::complex rgamma(std::complex z) {
+    return static_cast>(rgamma(static_cast>(z)));
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h
new file mode 100644
index 0000000000000000000000000000000000000000..4d26b64e02aa3f65a97d99160047efd76e7f121d
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h
@@ -0,0 +1,200 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of sin/cos/sinh/cosh integrals for complex arguments
+ *
+ * Sources
+ * [1] Fredrik Johansson and others. mpmath: a Python library for
+ *     arbitrary-precision floating-point arithmetic (version 0.19),
+ *     December 2013. http://mpmath.org/.
+ * [2] NIST, "Digital Library of Mathematical Functions",
+ *     https://dlmf.nist.gov/
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+#include "expint.h"
+#include "cephes/const.h"
+#include "cephes/sici.h"
+#include "cephes/shichi.h"
+
+namespace xsf {
+namespace detail {
+    
+    XSF_HOST_DEVICE inline void sici_power_series(int sgn, std::complex z,
+						       std::complex *s, std::complex *c) {
+	/* DLMF 6.6.5 and 6.6.6. If sgn = -1 computes si/ci, and if sgn = 1
+	 * computes shi/chi.
+	 */        
+	std::complex fac = z;
+	*s = fac;
+	*c = 0;
+	std::complex term1, term2;
+	for (int n = 1; n < 100; n++) {
+	    fac *= static_cast(sgn)*z/(2.0*n);
+	    term2 = fac/(2.0*n);
+	    *c += term2;
+	    fac *= z/(2.0*n + 1.0);
+	    term1 = fac/(2.0*n + 1.0);
+	    *s += term1;
+	    constexpr double tol = std::numeric_limits::epsilon();
+	    if (std::abs(term1) < tol*std::abs(*s) && std::abs(term2) < tol*std::abs(*c)) {
+		break;
+	    }
+	}
+    }
+
+}
+
+    
+XSF_HOST_DEVICE inline int sici(std::complex z,
+				    std::complex *si, std::complex *ci) {
+    /* Compute sin/cos integrals at complex arguments. The algorithm
+     * largely follows that of [1].
+     */
+
+    constexpr double EULER = xsf::cephes::detail::SCIPY_EULER;
+
+    if (z == std::numeric_limits::infinity()) {
+        *si = M_PI_2;
+        *ci = 0;
+        return 0;
+    }
+    if (z == -std::numeric_limits::infinity()) {
+	*si = -M_PI_2;
+        *ci = {0.0, M_PI};
+        return 0;
+    }
+
+    if (std::abs(z) < 0.8) {
+        // Use the series to avoid cancellation in si
+	detail::sici_power_series(-1, z, si, ci);
+
+        if (z == 0.0) {
+            set_error("sici", SF_ERROR_DOMAIN, NULL);
+            *ci = {-std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()};
+        } else {
+            *ci += EULER + std::log(z);
+	}
+        return 0;
+    }
+    
+    // DLMF 6.5.5/6.5.6 plus DLMF 6.4.4/6.4.6/6.4.7
+    std::complex jz = std::complex(0.0, 1.0) * z;
+    std::complex term1 = expi(jz);
+    std::complex term2 = expi(-jz);
+    *si = std::complex(0.0, -0.5)*(term1 - term2);
+    *ci = 0.5*(term1 + term2);
+    if (z.real() == 0) {
+        if (z.imag() > 0) {
+            *ci += std::complex(0.0, M_PI_2);
+	} else if (z.imag() < 0) {
+            *ci -= std::complex(0.0, M_PI_2);
+	}
+    } else if (z.real() > 0) {
+        *si -= M_PI_2;
+    } else {
+        *si += M_PI_2;
+        if (z.imag() >= 0) {
+            *ci += std::complex(0.0, M_PI);
+        } else {
+            *ci -= std::complex(0.0, M_PI);
+	}
+    }
+    return 0;
+}
+
+XSF_HOST_DEVICE inline int sici(std::complex z,
+				    std::complex *si_f, std::complex *ci_f) {
+    std::complex si;
+    std::complex ci;
+    int res = sici(z, &si, &ci);
+    *si_f = si;
+    *ci_f = ci;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int shichi(std::complex z,
+				       std::complex *shi, std::complex *chi) {
+    /* Compute sinh/cosh integrals at complex arguments. The algorithm
+     * largely follows that of [1].
+     */
+    constexpr double EULER = xsf::cephes::detail::SCIPY_EULER;
+    if (z == std::numeric_limits::infinity()) {
+        *shi = std::numeric_limits::infinity();
+        *chi = std::numeric_limits::infinity();
+        return 0;
+    }
+    if (z == -std::numeric_limits::infinity()) {
+        *shi = -std::numeric_limits::infinity();
+        *chi = std::numeric_limits::infinity();
+        return 0;
+    }
+    if (std::abs(z) < 0.8) {
+        // Use the series to avoid cancellation in shi
+	detail::sici_power_series(1, z, shi, chi);
+        if (z == 0.0) {
+            set_error("shichi", SF_ERROR_DOMAIN, NULL);
+            *chi = {-std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()};
+        } else {
+            *chi += EULER + std::log(z);
+	}
+	return 0;
+    }
+
+    std::complex term1 = expi(z);
+    std::complex term2 = expi(-z);
+    *shi = 0.5*(term1 - term2);
+    *chi = 0.5*(term1 + term2);
+    if (z.imag() > 0) {
+        *shi -= std::complex(0.0, 0.5*M_PI);
+        *chi += std::complex(0.0, 0.5*M_PI);
+    } else if (z.imag() < 0) {
+        *shi += std::complex(0.0, 0.5*M_PI);
+        *chi -= std::complex(0.0, 0.5*M_PI);
+    } else if (z.real() < 0) {
+        *chi += std::complex(0.0, M_PI);
+    }
+    return 0;
+}
+
+XSF_HOST_DEVICE inline int shichi(std::complex z,
+				    std::complex *shi_f, std::complex *chi_f) {
+    std::complex shi;
+    std::complex chi;
+    int res = shichi(z, &shi, &chi);
+    *shi_f = shi;
+    *chi_f = chi;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) {
+    return cephes::sici(x, si, ci);
+}
+
+XSF_HOST_DEVICE inline int shichi(double x, double *shi, double *chi) {
+    return cephes::shichi(x, shi, chi);
+}
+
+XSF_HOST_DEVICE inline int sici(float x, float *si_f, float *ci_f) {
+    double si;
+    double ci;
+    int res = cephes::sici(x, &si, &ci);
+    *si_f = si;
+    *ci_f = ci;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int shichi(float x, float *shi_f, float *chi_f) {
+    double shi;
+    double chi;
+    int res = cephes::shichi(x, &shi, &chi);
+    *shi_f = shi;
+    *chi_f = chi;
+    return res;
+}
+}
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h
new file mode 100644
index 0000000000000000000000000000000000000000..e349f6a5fb4f45b4718cb746dd7b0b2c1fd23ddd
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h
@@ -0,0 +1,427 @@
+/* Building blocks for implementing special functions */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+namespace xsf {
+namespace detail {
+
+    /* Result type of a "generator", a callable object that produces a value
+     * each time it is called.
+     */
+    template 
+    using generator_result_t = typename std::decay::type>::type;
+
+    /* Used to deduce the type of the numerator/denominator of a fraction. */
+    template 
+    struct pair_traits;
+
+    template 
+    struct pair_traits> {
+        using value_type = T;
+    };
+
+    template 
+    using pair_value_t = typename pair_traits::value_type;
+
+    /* Used to extract the "value type" of a complex type. */
+    template 
+    struct real_type {
+        using type = T;
+    };
+
+    template 
+    struct real_type> {
+        using type = T;
+    };
+
+    template 
+    using real_type_t = typename real_type::type;
+
+    // Return NaN, handling both real and complex types.
+    template 
+    XSF_HOST_DEVICE inline typename std::enable_if::value, T>::type maybe_complex_NaN() {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    template 
+    XSF_HOST_DEVICE inline typename std::enable_if::value, T>::type maybe_complex_NaN() {
+        using V = typename T::value_type;
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+
+    // Series evaluators.
+    template >
+    XSF_HOST_DEVICE T
+    series_eval(Generator &g, T init_val, real_type_t tol, std::uint64_t max_terms, const char *func_name) {
+        /* Sum an infinite series to a given precision.
+         *
+         * g : a generator of terms for the series.
+         *
+         * init_val : A starting value that terms are added to. This argument determines the
+         *     type of the result.
+         *
+         * tol : relative tolerance for stopping criterion.
+         *
+         * max_terms : The maximum number of terms to add before giving up and declaring
+         *     non-convergence.
+         *
+         * func_name : The name of the function within SciPy where this call to series_eval
+         *     will ultimately be used. This is needed to pass to set_error in case
+         *     of non-convergence.
+         */
+        T result = init_val;
+        T term;
+        for (std::uint64_t i = 0; i < max_terms; ++i) {
+            term = g();
+            result += term;
+            if (std::abs(term) < std::abs(result) * tol) {
+                return result;
+            }
+        }
+        // Exceeded max terms without converging. Return NaN.
+        set_error(func_name, SF_ERROR_NO_RESULT, NULL);
+        return maybe_complex_NaN();
+    }
+
+    template >
+    XSF_HOST_DEVICE T series_eval_fixed_length(Generator &g, T init_val, std::uint64_t num_terms) {
+        /* Sum a fixed number of terms from a series.
+         *
+         * g : a generator of terms for the series.
+         *
+         * init_val : A starting value that terms are added to. This argument determines the
+         *     type of the result.
+         *
+         * max_terms : The number of terms from the series to sum.
+         *
+         */
+        T result = init_val;
+        for (std::uint64_t i = 0; i < num_terms; ++i) {
+            result += g();
+        }
+        return result;
+    }
+
+    /* Performs one step of Kahan summation. */
+    template 
+    XSF_HOST_DEVICE void kahan_step(T &sum, T &comp, T x) {
+        T y = x - comp;
+        T t = sum + y;
+        comp = (t - sum) - y;
+        sum = t;
+    }
+
+    /* Evaluates an infinite series using Kahan summation.
+     *
+     * Denote the series by
+     *
+     *   S = a[0] + a[1] + a[2] + ...
+     *
+     * And for n = 0, 1, 2, ..., denote its n-th partial sum by
+     *
+     *   S[n] = a[0] + a[1] + ... + a[n]
+     *
+     * This function computes S[0], S[1], ... until a[n] is sufficiently
+     * small or if the maximum number of terms have been evaluated.
+     *
+     * Parameters
+     * ----------
+     *   g
+     *       Reference to generator that yields the sequence of values a[1],
+     *       a[2], a[3], ...
+     *
+     *   tol
+     *       Relative tolerance for convergence.  Specifically, stop iteration
+     *       as soon as `abs(a[n]) <= tol * abs(S[n])` for some n >= 1.
+     *
+     *   max_terms
+     *       Maximum number of terms after a[0] to evaluate.  It should be set
+     *       large enough such that the convergence criterion is guaranteed
+     *       to have been satisfied within that many terms if there is no
+     *       rounding error.
+     *
+     *   init_val
+     *       a[0].  Default is zero.  The type of this parameter (T) is used
+     *       for intermediary computations as well as the result.
+     *
+     * Return Value
+     * ------------
+     * If the convergence criterion is satisfied by some `n <= max_terms`,
+     * returns `(S[n], n)`.  Otherwise, returns `(S[max_terms], 0)`.
+     */
+    template >
+    XSF_HOST_DEVICE std::pair
+    series_eval_kahan(Generator &&g, real_type_t tol, std::uint64_t max_terms, T init_val = T(0)) {
+
+        using std::abs;
+        T sum = init_val;
+        T comp = T(0);
+        for (std::uint64_t i = 0; i < max_terms; ++i) {
+            T term = g();
+            kahan_step(sum, comp, term);
+            if (abs(term) <= tol * abs(sum)) {
+                return {sum, i + 1};
+            }
+        }
+        return {sum, 0};
+    }
+
+    /* Generator that yields the difference of successive convergents of a
+     * continued fraction.
+     *
+     * Let f[n] denote the n-th convergent of a continued fraction:
+     *
+     *                 a[1]   a[2]       a[n]
+     *   f[n] = b[0] + ------ ------ ... ----
+     *                 b[1] + b[2] +     b[n]
+     *
+     * with f[0] = b[0].  This generator yields the sequence of values
+     * f[1]-f[0], f[2]-f[1], f[3]-f[2], ...
+     *
+     * Constructor Arguments
+     * ---------------------
+     *   cf
+     *       Reference to generator that yields the terms of the continued
+     *       fraction as (numerator, denominator) pairs, starting from
+     *       (a[1], b[1]).
+     *
+     *       `cf` must outlive the ContinuedFractionSeriesGenerator object.
+     *
+     *       The constructed object always eagerly retrieves the next term
+     *       of the continued fraction.  Specifically, (a[1], b[1]) is
+     *       retrieved upon construction, and (a[n], b[n]) is retrieved after
+     *       (n-1) calls of `()`.
+     *
+     * Type Arguments
+     * --------------
+     *   T
+     *       Type in which computations are performed and results are turned.
+     *
+     * Remarks
+     * -------
+     * The series is computed using the recurrence relation described in [1].
+     * Let v[n], n >= 1 denote the terms of the series.  Then
+     *
+     *   v[1] = a[1] / b[1]
+     *   v[n] = v[n-1] * r[n-1], n >= 2
+     *
+     * where
+     *
+     *                              -(a[n] + a[n] * r[n-1])
+     *   r[1] = 0,  r[n] = ------------------------------------------, n >= 2
+     *                      (a[n] + a[n] * r[n-1]) + (b[n] * b[n-1])
+     *
+     * No error checking is performed.  The caller must ensure that all terms
+     * are finite and that intermediary computations do not trigger floating
+     * point exceptions such as overflow.
+     *
+     * The numerical stability of this method depends on the characteristics
+     * of the continued fraction being evaluated.
+     *
+     * Reference
+     * ---------
+     * [1] Gautschi, W. (1967). “Computational Aspects of Three-Term
+     *     Recurrence Relations.” SIAM Review, 9(1):24-82.
+     */
+    template >>
+    class ContinuedFractionSeriesGenerator {
+
+      public:
+        XSF_HOST_DEVICE explicit ContinuedFractionSeriesGenerator(Generator &cf) : cf_(cf) { init(); }
+
+        XSF_HOST_DEVICE T operator()() {
+            T v = v_;
+            advance();
+            return v;
+        }
+
+      private:
+        XSF_HOST_DEVICE void init() {
+            auto [num, denom] = cf_();
+            T a = num;
+            T b = denom;
+            r_ = T(0);
+            v_ = a / b;
+            b_ = b;
+        }
+
+        XSF_HOST_DEVICE void advance() {
+            auto [num, denom] = cf_();
+            T a = num;
+            T b = denom;
+            T p = a + a * r_;
+            T q = p + b * b_;
+            r_ = -p / q;
+            v_ = v_ * r_;
+            b_ = b;
+        }
+
+        Generator &cf_; // reference to continued fraction generator
+        T v_;           // v[n] == f[n] - f[n-1], n >= 1
+        T r_;           // r[1] = 0, r[n] = v[n]/v[n-1], n >= 2
+        T b_;           // last denominator, i.e. b[n-1]
+    };
+
+    /* Converts a continued fraction into a series whose terms are the
+     * difference of its successive convergents.
+     *
+     * See ContinuedFractionSeriesGenerator for details.
+     */
+    template >>
+    XSF_HOST_DEVICE ContinuedFractionSeriesGenerator continued_fraction_series(Generator &cf) {
+        return ContinuedFractionSeriesGenerator(cf);
+    }
+
+    /* Find initial bracket for a bracketing scalar root finder. A valid bracket is a pair of points a < b for
+     * which the signs of f(a) and f(b) differ. If f(x0) = 0, where x0 is the initial guess, this bracket finder
+     * will return the bracket (x0, x0). It is expected that the rootfinder will check if the bracket
+     * endpoints are roots.
+     *
+     * This is a private function intended specifically for the situation where
+     * the goal is to invert a CDF function F for a parametrized family of distributions with respect to one
+     * parameter, when the other parameters are known, and where F is monotonic with respect to the unknown parameter.
+     */
+    template 
+    XSF_HOST_DEVICE inline std::tuple bracket_root_for_cdf_inversion(
+        Function func, double x0, double xmin, double xmax, double step0_left,
+        double step0_right, double factor_left, double factor_right, bool increasing, std::uint64_t maxiter
+    ) {
+        double y0 = func(x0);
+
+        if (y0 == 0) {
+            // Initial guess is correct.
+            return {x0, x0, y0, y0, 0};
+        }
+
+        double y0_sgn = std::signbit(y0);
+
+        bool search_left;
+        /* The frontier is the new leading endpoint of the expanding bracket. The
+         * interior endpoint trails behind the frontier. In each step, the old frontier
+         * endpoint becomes the new interior endpoint. */
+        double interior, frontier, y_interior, y_frontier, y_interior_sgn, y_frontier_sgn, boundary, factor;
+        if ((increasing && y0 < 0) || (!increasing && y0 > 0)) {
+            /* If func is increasing  and func(x_right) < 0 or if func is decreasing and
+             *  f(y_right) > 0, we should expand the bracket to the right. */
+            interior = x0, y_interior = y0;
+            frontier = x0 + step0_right;
+            y_interior_sgn = y0_sgn;
+            search_left = false;
+            boundary = xmax;
+            factor = factor_right;
+        } else {
+            /* Otherwise we move and expand the bracket to the left. */
+            interior = x0, y_interior = y0;
+            frontier = x0 + step0_left;
+            y_interior_sgn = y0_sgn;
+            search_left = true;
+            boundary = xmin;
+            factor = factor_left;
+        }
+
+        bool reached_boundary = false;
+        for (std::uint64_t i = 0; i < maxiter; i++) {
+            y_frontier = func(frontier);
+            y_frontier_sgn = std::signbit(y_frontier);
+            if (y_frontier_sgn != y_interior_sgn || (y_frontier == 0.0)) {
+                /* Stopping condition, func evaluated at endpoints of bracket has opposing signs,
+                 * meeting requirement for bracketing root finder. (Or endpoint has reached a
+                 * zero.) */
+                if (search_left) {
+                    /* Ensure we return an interval (a, b) with a < b. */
+                    std::swap(interior, frontier);
+                    std::swap(y_interior, y_frontier);
+                }
+		return {interior, frontier, y_interior, y_frontier, 0};
+            }
+            if (reached_boundary) {
+                /* We've reached a boundary point without finding a root . */
+                return {
+                    std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+                    std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+                    search_left ? 1 : 2
+                };
+            }
+            double step = (frontier - interior) * factor;
+            interior = frontier;
+            y_interior = y_frontier;
+            y_interior_sgn = y_frontier_sgn;
+            frontier += step;
+            if ((search_left && frontier <= boundary) || (!search_left && frontier >= boundary)) {
+                /* If the frontier has reached the boundary, set a flag so the algorithm will know
+                 * not to search beyond this point. */
+                frontier = boundary;
+                reached_boundary = true;
+            }
+        }
+        /* Failed to converge within maxiter iterations. If maxiter is sufficiently high and
+         * factor_left and factor_right are set appropriately, this should only happen due to
+         * a bug in this function. Limiting the number of iterations is a defensive programming measure. */
+	return {
+            std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+            std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), 3
+        };
+    }
+
+    /* Find root of a scalar function using Chandrupatla's algorithm */
+    template 
+    XSF_HOST_DEVICE inline std::pair find_root_chandrupatla(
+        Function func, double x1, double x2, double f1, double f2, double rtol,
+        double atol, std::uint64_t maxiter
+    ) {
+        if (f1 == 0) {
+            return {x1, 0};
+        }
+        if (f2 == 0) {
+            return {x2, 0};
+        }
+        double t = 0.5, x3, f3;
+        for (uint64_t i = 0; i < maxiter; i++) {
+            double x = x1 + t * (x2 - x1);
+            double f = func(x);
+            if (std::signbit(f) == std::signbit(f1)) {
+                x3 = x1;
+                x1 = x;
+                f3 = f1;
+                f1 = f;
+            } else {
+                x3 = x2;
+                x2 = x1;
+                x1 = x;
+                f3 = f2;
+                f2 = f1;
+                f1 = f;
+            }
+            double xm, fm;
+            if (std::abs(f2) < std::abs(f1)) {
+                xm = x2;
+                fm = f2;
+            } else {
+                xm = x1;
+                fm = f1;
+            }
+            double tol = 2.0 * rtol * std::abs(xm) + 0.5 * atol;
+            double tl = tol / std::abs(x2 - x1);
+            if (tl > 0.5 || fm == 0) {
+                return {xm, 0};
+            }
+            double xi = (x1 - x2) / (x3 - x2);
+            double phi = (f1 - f2) / (f3 - f2);
+            double fl = 1.0 - std::sqrt(1.0 - xi);
+            double fh = std::sqrt(xi);
+
+            if ((fl < phi) && (phi < fh)) {
+                t = (f1 / (f2 - f1)) * (f3 / (f2 - f3)) + (f1 / (f3 - f1)) * (f2 / (f3 - f2)) * ((x3 - x1) / (x2 - x1));
+            } else {
+                t = 0.5;
+            }
+            t = std::fmin(std::fmax(t, tl), 1.0 - tl);
+        }
+        return {std::numeric_limits::quiet_NaN(), 1};
+    }
+
+} // namespace detail
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h
new file mode 100644
index 0000000000000000000000000000000000000000..a0221e00bbe358519c1586eb539310a5be6cddd1
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h
@@ -0,0 +1,164 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+/* Implement sin(pi*z) and cos(pi*z) for complex z. Since the periods
+ * of these functions are integral (and thus better representable in
+ * floating point), it's possible to compute them with greater accuracy
+ * than sin(z), cos(z).
+ */
+
+#pragma once
+
+#include "cephes/sindg.h"
+#include "cephes/tandg.h"
+#include "cephes/trig.h"
+#include "cephes/unity.h"
+#include "config.h"
+#include "evalpoly.h"
+
+namespace xsf {
+
+template 
+XSF_HOST_DEVICE T sinpi(T x) {
+    return cephes::sinpi(x);
+}
+
+template 
+XSF_HOST_DEVICE std::complex sinpi(std::complex z) {
+    T x = z.real();
+    T piy = M_PI * z.imag();
+    T abspiy = std::abs(piy);
+    T sinpix = cephes::sinpi(x);
+    T cospix = cephes::cospi(x);
+
+    if (abspiy < 700) {
+        return {sinpix * std::cosh(piy), cospix * std::sinh(piy)};
+    }
+
+    /* Have to be careful--sinh/cosh could overflow while cos/sin are small.
+     * At this large of values
+     *
+     * cosh(y) ~ exp(y)/2
+     * sinh(y) ~ sgn(y)*exp(y)/2
+     *
+     * so we can compute exp(y/2), scale by the right factor of sin/cos
+     * and then multiply by exp(y/2) to avoid overflow. */
+    T exphpiy = std::exp(abspiy / 2);
+    T coshfac;
+    T sinhfac;
+    if (exphpiy == std::numeric_limits::infinity()) {
+        if (sinpix == 0.0) {
+            // Preserve the sign of zero.
+            coshfac = std::copysign(0.0, sinpix);
+        } else {
+            coshfac = std::copysign(std::numeric_limits::infinity(), sinpix);
+        }
+        if (cospix == 0.0) {
+            // Preserve the sign of zero.
+            sinhfac = std::copysign(0.0, cospix);
+        } else {
+            sinhfac = std::copysign(std::numeric_limits::infinity(), cospix);
+        }
+        return {coshfac, sinhfac};
+    }
+
+    coshfac = 0.5 * sinpix * exphpiy;
+    sinhfac = 0.5 * cospix * exphpiy;
+    return {coshfac * exphpiy, sinhfac * exphpiy};
+}
+
+template 
+XSF_HOST_DEVICE T cospi(T x) {
+    return cephes::cospi(x);
+}
+
+template 
+XSF_HOST_DEVICE std::complex cospi(std::complex z) {
+    T x = z.real();
+    T piy = M_PI * z.imag();
+    T abspiy = std::abs(piy);
+    T sinpix = cephes::sinpi(x);
+    T cospix = cephes::cospi(x);
+
+    if (abspiy < 700) {
+        return {cospix * std::cosh(piy), -sinpix * std::sinh(piy)};
+    }
+
+    // See csinpi(z) for an idea of what's going on here.
+    T exphpiy = std::exp(abspiy / 2);
+    T coshfac;
+    T sinhfac;
+    if (exphpiy == std::numeric_limits::infinity()) {
+        if (sinpix == 0.0) {
+            // Preserve the sign of zero.
+            coshfac = std::copysign(0.0, cospix);
+        } else {
+            coshfac = std::copysign(std::numeric_limits::infinity(), cospix);
+        }
+        if (cospix == 0.0) {
+            // Preserve the sign of zero.
+            sinhfac = std::copysign(0.0, sinpix);
+        } else {
+            sinhfac = std::copysign(std::numeric_limits::infinity(), sinpix);
+        }
+        return {coshfac, sinhfac};
+    }
+
+    coshfac = 0.5 * cospix * exphpiy;
+    sinhfac = 0.5 * sinpix * exphpiy;
+    return {coshfac * exphpiy, sinhfac * exphpiy};
+}
+
+template 
+XSF_HOST_DEVICE T sindg(T x) {
+    return cephes::sindg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float sindg(float x) {
+    return sindg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T cosdg(T x) {
+    return cephes::cosdg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float cosdg(float x) {
+    return cosdg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T tandg(T x) {
+    return cephes::tandg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float tandg(float x) {
+    return tandg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T cotdg(T x) {
+    return cephes::cotdg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float cotdg(float x) {
+    return cotdg(static_cast(x));
+}
+
+inline double radian(double d, double m, double s) { return cephes::radian(d, m, s); }
+
+inline float radian(float d, float m, float s) {
+    return radian(static_cast(d), static_cast(m), static_cast(s));
+}
+
+inline double cosm1(double x) { return cephes::cosm1(x); }
+
+inline float cosm1(float x) { return cosm1(static_cast(x)); }
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h
new file mode 100644
index 0000000000000000000000000000000000000000..77cf165a0fc303a2ee425dff7083889908dcf887
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h
@@ -0,0 +1,843 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of Wright's generalized Bessel function Phi, see
+ * https://dlmf.nist.gov/10.46.E1
+ *
+ * Copyright: Christian Lorentzen
+ *
+ * Distributed under the same license as SciPy
+ *
+ *
+ * Implementation Overview:
+ *
+ * First, different functions are implemented valid for certain domains of the
+ * three arguments.
+ * Finally they are put together in wright_bessel. See the docstring of
+ * that function for more details.
+ */
+
+#pragma once
+
+#include "cephes/lanczos.h"
+#include "cephes/polevl.h"
+#include "cephes/rgamma.h"
+#include "config.h"
+#include "digamma.h"
+#include "error.h"
+
+namespace xsf {
+
+namespace detail {
+    // rgamma_zero: smallest value x for which rgamma(x) == 0 as x gets large
+    constexpr double rgamma_zero = 178.47241115886637;
+
+    XSF_HOST_DEVICE inline double exp_rgamma(double x, double y) {
+        /* Compute exp(x) / gamma(y) = exp(x) * rgamma(y).
+         *
+         * This helper function avoids overflow by using the lanczos
+         * approximation of the gamma function.
+         */
+        return std::exp(x + (1 - std::log(y + cephes::lanczos_g - 0.5)) * (y - 0.5)) /
+               cephes::lanczos_sum_expg_scaled(y);
+    }
+
+    XSF_HOST_DEVICE inline double wb_series(double a, double b, double x, unsigned int nstart, unsigned int nstop) {
+        /* 1. Taylor series expansion in x=0 for x <= 1.
+         *
+         * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b)
+         *
+         * Note that every term, and therefore also Phi(a, b, x) is
+         * monotone decreasing with increasing a or b.
+         */
+        double xk_k = std::pow(x, nstart) * cephes::rgamma(nstart + 1); // x^k/k!
+        double res = xk_k * cephes::rgamma(nstart * a + b);
+        // term k=nstart+1, +2, +3, ...
+        if (nstop > nstart) {
+            // series expansion until term k such that a*k+b <= rgamma_zero
+            unsigned int k_max = std::floor((rgamma_zero - b) / a);
+            if (nstop > k_max) {
+                nstop = k_max;
+            }
+            for (unsigned int k = nstart + 1; k < nstop; k++) {
+                xk_k *= x / k;
+                res += xk_k * cephes::rgamma(a * k + b);
+            }
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_large_a(double a, double b, double x, int n) {
+        /* 2. Taylor series expansion in x=0, for large a.
+         *
+         * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b)
+         *
+         * Use Stirling's formula to find k=k_max, the maximum term.
+         * Then use n terms of Taylor series around k_max.
+         */
+        int k_max = static_cast(std::pow(std::pow(a, -a) * x, 1.0 / (1 + a)));
+
+        int nstart = k_max - n / 2;
+        if (nstart < 0) {
+            nstart = 0;
+        }
+
+        double res = 0;
+        double lnx = std::log(x);
+        // For numerical stability, we factor out the maximum term exp(..) with k=k_max
+        // but only if it is larger than 0.
+        double max_exponent = std::fmax(0, k_max * lnx - cephes::lgam(k_max + 1) - cephes::lgam(a * k_max + b));
+        for (int k = nstart; k < nstart + n; k++) {
+            res += std::exp(k * lnx - cephes::lgam(k + 1) - cephes::lgam(a * k + b) - max_exponent);
+        }
+
+        if (!log_wb) {
+            res *= std::exp(max_exponent);
+        } else {
+            // logarithm of Wright's function
+            res = max_exponent + std::log(res);
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_small_a(double a, double b, double x, int order) {
+        /* 3. Taylor series in a=0 up to order 5, for tiny a and not too large x
+         *
+         * Phi(a, b, x) = exp(x)/Gamma(b)
+                          * (1 - a*x * Psi(b) + a^2/2*x*(1+x) * (Psi(b)^2 - Psi'(b)
+                             + ... )
+                          + O(a^6))
+         *
+         * where Psi is the digamma function.
+         *
+         * Parameter order takes effect only when b > 1e-3 and 2 <= order <= 5,
+         * otherwise it defaults to 2, or if b <= 1e-3, to 5. The lower order is,
+         * the fewer polygamma functions have to be computed.
+         *
+         * Call: python _precompute/wright_bessel.py 1
+         *
+         * For small b, i.e. b <= 1e-3, cancellation of poles of digamma(b)/Gamma(b)
+         * and polygamma needs to be carried out => series expansion in a=0 to order 5
+         * and in b=0 to order 4.
+         * Call: python _precompute/wright_bessel.py 2
+         */
+        double A[6]; // coefficients of a^k  (1, -x * Psi(b), ...)
+        double B[6]; // powers of b^k/k! or terms in polygamma functions
+        constexpr double C[5] = {  // coefficients of a^k1 * b^k2
+            1.0000000000000000,   // C[0]
+            1.1544313298030657,   // C[1]
+            -3.9352684291215233,  // C[2]
+            -1.0080632408182857,  // C[3]
+            19.984633365874979,   // C[4]
+        };
+        double X[6] = {  // polynomials in x;
+            1,  // X[0]
+            x,  // X[1]
+            x * (x + 1),  // X[2]
+            x * (x * (x + 3) + 1),  // X[3]
+            x * (x * (x * (x + 6) + 7) + 1),  // X[4]
+            x * (x * (x * (x * (x + 10) + 25) + 15) + 1),  // X[5]
+        };
+        double res;
+
+        if (b <= 1E-3) {
+            /* Series expansion of both a and b up to order 5:
+             * M_PI = pi
+             * M_EG = Euler Gamma aka Euler Mascheroni constant
+             * M_Z3 = zeta(3)
+             * C[0] = 1
+             * C[1] = 2*M_EG
+             * C[2] = 3*M_EG^2 - M_PI^2/2
+             * C[3] = 4*M_EG^3 - 2*M_EG*M_PI^2 + 8*M_Z3
+             * C[4] = 5*M_EG^4 - 5*M_EG^2*M_PI^2 + 40*M_EG*M_Z3 + M_PI^4/12
+             */
+            B[0] = 1.;
+            for (int k = 1; k < 5; k++) {
+                B[k] = b / k * B[k - 1];
+            }
+            // Note that polevl assumes inverse ordering => A[5] = 0th term
+            A[5] = cephes::rgamma(b);
+            A[4] = X[1]        * (C[0] + C[1] * b + C[2] * B[2] + C[3] * B[3] + C[4] * B[4]);
+            A[3] = X[2] / 2.   * (C[1] + C[2] * b + C[3] * B[2] + C[4] * B[3]);
+            A[2] = X[3] / 6.   * (C[2] + C[3] * b + C[4] * B[2]);
+            A[1] = X[4] / 24.  * (C[3] + C[4] * b);
+            A[0] = X[5] / 120. * C[4];
+            // res = exp(x) * (A[5] + A[4] * a + A[3] * a^2 + A[2] * a^3 + ...)
+            if (!log_wb) {
+                res = exp(x) * cephes::polevl(a, A, 5);
+            } else {
+                // logarithm of Wright's function
+                res = x + std::log(cephes::polevl(a, A, 5));
+            }
+        } else {
+            /* Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)
+             * A[n] = a^n/n!
+             * But here, we repurpose A[n] = X[n] * B[n] / n!
+             * Note that polevl assumes inverse ordering => A[order] = 0th term */
+            double dg = digamma(b);
+            // pg1 = polygamma(1, b)
+            double pg1 = cephes::zeta(2, b);
+            if (order <= 2) {
+                res = 1 + a * x * (-dg + 0.5 * a * (1 + x) * (dg * dg - pg1));
+            } else {
+                if (order > 5) {
+                    order = 5;
+                }
+                // pg2 = polygamma(2, b)
+                double pg2 = -2 * cephes::zeta(3, b);
+                B[0] = 1;
+                B[1] = -dg;
+                B[2] = dg * dg - pg1;
+                B[3] = (-dg * dg + 3 * pg1) * dg - pg2;
+                A[order] = 1;
+                A[order - 1] = X[1] * B[1];
+                A[order - 2] = X[2] * B[2] / 2.;
+                A[order - 3] = X[3] * B[3] / 6.;
+                if (order >= 4) {
+                    // double pg3 = polygamma(3, b)
+                    double pg3 = 6 * cephes::zeta(4, b);
+                    B[4] = ((dg * dg - 6 * pg1) * dg + 4 * pg2) * dg + 3 * pg1 * pg1 - pg3;
+                    A[order - 4] = X[4] * B[4] / 24.;
+                    if (order >= 5) {
+                        // pg4 = polygamma(4, b)
+                        double pg4 = -24 * cephes::zeta(5, b);
+                        B[5] =
+                            ((((-dg * dg + 10 * pg1) * dg - 10 * pg2) * dg - 15 * pg1 * pg1 + 5 * pg3) * dg +
+                             10 * pg1 * pg2 - pg4);
+                        A[order - 5] = X[5] * B[5] / 120.;
+                    }
+                }
+                res = cephes::polevl(a, A, order);
+            }
+            // res *= exp(x) * rgamma(b)
+            if (!log_wb) {
+                res *= exp_rgamma(x, b);
+            } else {
+                // logarithm of Wright's function
+                res = x - cephes::lgam(b) + std::log(res);
+            }
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_asymptotic(double a, double b, double x) {
+        /* 4. Asymptotic expansion for large x up to order 8
+         *
+         * Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k
+         *
+         * with Z = (a*x)^(1/(1+a)).
+         * Call: python _precompute/wright_bessel.py 3
+         */
+        double A[15];  // powers of a
+        double B[17];  // powers of b
+        double Ap1[9]; // powers of (1+a)
+        double C[9];   // coefficients of asymptotic series a_k
+
+        A[0] = 1.;
+        B[0] = 1.;
+        Ap1[0] = 1.;
+        for (int k = 1; k < 15; k++) {
+            A[k] = A[k - 1] * a;
+        }
+        for (int k = 1; k < 17; k++) {
+            B[k] = B[k - 1] * b;
+        }
+        for (int k = 1; k < 9; k++) {
+            Ap1[k] = Ap1[k - 1] * (1 + a);
+        }
+
+        C[0] = 1. / std::sqrt(2. * M_PI * Ap1[1]);
+
+        C[1] = C[0] / (24 * Ap1[1]);
+        C[1] *= (2 * a + 1) * (2 + a) - 12 * b * (1 + a - b);
+
+        C[2] = C[0] / (1152 * Ap1[2]);
+        C[2] *=
+            (144 * B[4] - 96 * B[3] * (5 * a + 1) + 24 * B[2] * (20 * A[2] + 5 * a - 4) -
+             24 * b * Ap1[1] * (6 * A[2] - 7 * a - 2) + (a + 2) * (2 * a + 1) * (2 * A[2] - 19 * a + 2));
+
+        C[3] = C[0] / (414720 * Ap1[3]);
+        C[3] *=
+            (8640 * B[6] - 8640 * B[5] * (7 * a - 1) + 10800 * B[4] * (14 * A[2] - 7 * a - 2) -
+             1440 * B[3] * (112 * A[3] - 147 * A[2] - 63 * a + 8) +
+             180 * B[2] * (364 * A[4] - 1288 * A[3] - 567 * A[2] + 392 * a + 76) -
+             180 * b * Ap1[1] * (20 * A[4] - 516 * A[3] + 417 * A[2] + 172 * a - 12) -
+             (a + 2) * (2 * a + 1) * (556 * A[4] + 1628 * A[3] - 9093 * A[2] + 1628 * a + 556));
+
+        C[4] = C[0] / (39813120 * Ap1[4]);
+        C[4] *=
+            (103680 * B[8] - 414720 * B[7] * (3 * a - 1) + 725760 * B[6] * a * (8 * a - 7) -
+             48384 * B[5] * (274 * A[3] - 489 * A[2] + 39 * a + 26) +
+             30240 * B[4] * (500 * A[4] - 1740 * A[3] + 495 * A[2] + 340 * a - 12) -
+             2880 * B[3] * (2588 * A[5] - 19780 * A[4] + 14453 * A[3] + 9697 * A[2] - 1892 * a - 404) +
+             48 * B[2] *
+                 (11488 * A[6] - 547836 * A[5] + 1007484 * A[4] + 593353 * A[3] - 411276 * A[2] - 114396 * a + 4288) +
+             48 * b * Ap1[1] *
+                 (7784 * A[6] + 48180 * A[5] - 491202 * A[4] + 336347 * A[3] + 163734 * A[2] - 28908 * a - 5560) -
+             (a + 2) * (2 * a + 1) *
+                 (4568 * A[6] - 226668 * A[5] - 465702 * A[4] + 2013479 * A[3] - 465702 * A[2] - 226668 * a + 4568));
+
+        C[5] = C[0] / (6688604160. * Ap1[5]);
+        C[5] *=
+            (1741824 * B[10] - 2903040 * B[9] * (11 * a - 5) + 2177280 * B[8] * (110 * A[2] - 121 * a + 14) -
+             580608 * B[7] * (1628 * A[3] - 3333 * A[2] + 1023 * a + 52) +
+             169344 * B[6] * (12364 * A[4] - 43648 * A[3] + 26763 * A[2] + 1232 * a - 788) -
+             24192 * B[5] * (104852 * A[5] - 646624 * A[4] + 721391 * A[3] - 16841 * A[2] - 74096 * a + 148) +
+             2016 * B[4] *
+                 (710248 * A[6] - 8878716 * A[5] + 17928834 * A[4] - 3333407 * A[3] - 4339566 * A[2] + 287364 * a +
+                  89128) -
+             1344 * B[3] *
+                 (87824 * A[7] - 7150220 * A[6] + 29202756 * A[5] - 15113527 * A[4] - 14223011 * A[3] + 3462492 * A[2] +
+                  1137092 * a - 18896) -
+             84 * B[2] *
+                 (1690480 * A[8] + 14139136 * A[7] - 232575464 * A[6] + 296712592 * A[5] + 215856619 * A[4] -
+                  152181392 * A[3] - 47718440 * A[2] + 5813632 * a + 943216) +
+             84 * b * Ap1[1] *
+                 (82224 * A[8] - 5628896 * A[7] - 26466520 * A[6] + 168779208 * A[5] - 104808005 * A[4] -
+                  56259736 * A[3] + 15879912 * A[2] + 4020640 * a - 63952) +
+             (a + 2) * (2 * a + 1) *
+                 (2622064 * A[8] + 12598624 * A[7] - 167685080 * A[6] - 302008904 * A[5] + 1115235367. * A[4] -
+                  302008904 * A[3] - 167685080 * A[2] + 12598624 * a + 2622064));
+
+        C[6] = C[0] / (4815794995200. * Ap1[6]);
+        C[6] *=
+            (104509440 * B[12] - 209018880 * B[11] * (13 * a - 7) + 574801920 * B[10] * (52 * A[2] - 65 * a + 12) -
+             63866880 * B[9] * (2834 * A[3] - 6279 * A[2] + 2769 * a - 134) +
+             23950080 * B[8] * (27404 * A[4] - 98228 * A[3] + 78663 * A[2] - 10868 * a - 1012) -
+             13685760 * B[7] * (105612 * A[5] - 599196 * A[4] + 791843 * A[3] - 224913 * A[2] - 27612 * a + 4540) +
+             2661120 * B[6] *
+                 (693680 * A[6] - 6473532 * A[5] + 13736424 * A[4] - 7047469 * A[3] - 723840 * A[2] + 471588 * a + 7376
+                 ) -
+             2661120 * B[5] *
+                 (432536 * A[7] - 7850804 * A[6] + 27531114 * A[5] - 24234457 * A[4] - 703001 * A[3] + 3633474 * A[2] -
+                  36244 * a - 45128) +
+             166320 * B[4] *
+                 (548912 * A[8] - 75660832 * A[7] + 502902712 * A[6] - 764807992 * A[5] + 91248287 * A[4] +
+                  217811464 * A[3] - 20365384 * A[2] - 9776416 * a + 37936) +
+             10080 * B[3] *
+                 (18759728 * A[9] + 165932208 * A[8] - 4710418440. * A[7] + 13686052536. * A[6] - 5456818809. * A[5] -
+                  6834514245. * A[4] + 1919299512. * A[3] + 752176152 * A[2] - 45661200 * a - 8616848) -
+             360 * B[2] *
+                 (32743360 * A[10] - 3381871792. * A[9] - 21488827776. * A[8] + 200389923864. * A[7] -
+                  198708005340. * A[6] - 171633799779. * A[5] + 123124874028. * A[4] + 40072774872. * A[3] -
+                  9137993280. * A[2] - 1895843248. * a + 18929728) -
+             360 * b * Ap1[1] *
+                 (57685408 * A[10] + 406929456 * A[9] - 6125375760. * A[8] - 27094918920. * A[7] +
+                  128752249410. * A[6] - 74866710561. * A[5] - 42917416470. * A[4] + 16256951352. * A[3] +
+                  4375268400. * A[2] - 316500688 * a - 47197152) +
+             (a + 2) * (2 * a + 1) *
+                 (167898208 * A[10] - 22774946512. * A[9] - 88280004528. * A[8] + 611863976472. * A[7] +
+                  1041430242126. * A[6] - 3446851131657. * A[5] + 1041430242126. * A[4] + 611863976472. * A[3] -
+                  88280004528. * A[2] - 22774946512. * a + 167898208));
+
+        C[7] = C[0] / (115579079884800. * Ap1[7]);
+        C[7] *=
+            (179159040 * B[14] - 1254113280. * B[13] * (5 * a - 3) + 1358622720. * B[12] * (70 * A[2] - 95 * a + 22) -
+             905748480 * B[11] * (904 * A[3] - 2109 * A[2] + 1119 * a - 112) +
+             1245404160. * B[10] * (3532 * A[4] - 12824 * A[3] + 11829 * A[2] - 2824 * a + 44) -
+             59304960 * B[9] * (256820 * A[5] - 1397680 * A[4] + 2025545 * A[3] - 869495 * A[2] + 52000 * a + 8788) +
+             14826240 * B[8] *
+                 (2274536 * A[6] - 18601572 * A[5] + 40698318 * A[4] - 28230079 * A[3] + 3916398 * A[2] + 832668 * a -
+                  65176) -
+             59304960 * B[7] *
+                 (760224 * A[7] - 9849164 * A[6] + 32495784 * A[5] - 34813869 * A[4] + 9175207 * A[3] + 1898688 * A[2] -
+                  469788 * a - 13184) +
+             25945920 * B[6] *
+                 (1167504 * A[8] - 28779840 * A[7] + 149752856 * A[6] - 246026112 * A[5] + 111944073 * A[4] +
+                  18341600 * A[3] - 12131496 * A[2] - 274368 * a + 102800) -
+             157248 * B[5] *
+                 (12341872 * A[9] - 3122991216. * A[8] + 29900054232. * A[7] - 78024816720. * A[6] +
+                  58914656739. * A[5] + 4637150811. * A[4] - 11523402480. * A[3] + 236218968 * A[2] + 337923216 * a +
+                  1592048) -
+             28080 * B[4] *
+                 (265154912 * A[10] + 2276098704. * A[9] - 105569461008. * A[8] + 496560666360. * A[7] -
+                  627891462858. * A[6] + 41935358025. * A[5] + 203913875814. * A[4] - 23984801544. * A[3] -
+                  13869306000. * A[2] + 372786832 * a + 103532640) +
+             1440 * B[3] *
+                 (310292864 * A[11] - 55169117872. * A[10] - 358957020112. * A[9] + 5714152556088. * A[8] -
+                  13241597459352. * A[7] + 4220720097141. * A[6] + 6845418090249. * A[5] - 2129559215808. * A[4] -
+                  909225098472. * A[3] + 107518582576. * A[2] + 25619444368. * a - 113832704) +
+             12 * B[2] *
+                 (135319651136. * A[12] + 1119107842176. * A[11] - 22193518174320. * A[10] - 133421793595520. * A[9] +
+                  860103051087996. * A[8] - 703353374803080. * A[7] - 704240127687381. * A[6] +
+                  513111704637960. * A[5] + 166909061348316. * A[4] - 57671564069120. * A[3] - 12453426246000. * A[2] +
+                  695901207936. * a + 93786157376.) -
+             12 * b * Ap1[1] *
+                 (4365353408. * A[12] - 720248637504. * A[11] - 4222331152560. * A[10] + 29413934270560. * A[9] +
+                  132123980710980. * A[8] - 511247376962820. * A[7] + 283403639131779. * A[6] +
+                  170415792320940. * A[5] - 79274388426588. * A[4] - 21009953050400. * A[3] + 3284035340880. * A[2] +
+                  589294339776. * a - 3693760576.) -
+             (a + 2) * (2 * a + 1) *
+                 (34221025984. * A[12] + 226022948160. * A[11] - 5067505612464. * A[10] - 18868361443936. * A[9] +
+                  86215425028308. * A[8] + 143500920544692. * A[7] - 437682618704613. * A[6] + 143500920544692. * A[5] +
+                  86215425028308. * A[4] - 18868361443936. * A[3] - 5067505612464. * A[2] + 226022948160. * a +
+                  34221025984.));
+
+        C[8] = C[0] / (22191183337881600. * Ap1[8]);
+        C[8] *=
+            (2149908480. * B[16] - 5733089280. * B[15] * (17 * a - 11) +
+             7166361600. * B[14] * (272 * A[2] - 391 * a + 104) -
+             3344302080. * B[13] * (6766 * A[3] - 16371 * A[2] + 9741 * a - 1306) +
+             1811496960. * B[12] * (93092 * A[4] - 341564 * A[3] + 344199 * A[2] - 104924 * a + 6308) -
+             517570560 * B[11] *
+                 (1626220 * A[5] - 8641508 * A[4] + 13274773 * A[3] - 6952303 * A[2] + 1007420 * a + 5564) +
+             284663808 * B[10] *
+                 (9979136 * A[6] - 75766892 * A[5] + 169256148 * A[4] - 136824959 * A[3] + 35714348 * A[2] -
+                  463692 * a - 293664) -
+             1423319040. * B[9] *
+                 (4466648 * A[7] - 49231116 * A[6] + 157507414 * A[5] - 187114257 * A[4] + 78372295 * A[3] -
+                  4470082 * A[2] - 1913996 * a + 82424) +
+             266872320 * B[8] *
+                 (33133136 * A[8] - 564264544 * A[7] + 2618606424. * A[6] - 4491310104. * A[5] + 2853943765. * A[4] -
+                  374694552 * A[3] - 135365288 * A[2] + 17623968 * a + 696912) -
+             2156544 * B[7] *
+                 (2914256144. * A[9] - 93491712432. * A[8] + 664876176984. * A[7] - 1661362937880. * A[6] +
+                  1563719627313. * A[5] - 382840842843. * A[4] - 115399415640. * A[3] + 34565562936. * A[2] +
+                  1609337232. * a - 217321904) +
+             179712 * B[6] *
+                 (1266018560. * A[10] - 789261834512. * A[9] + 10186841596896. * A[8] - 38877799073352. * A[7] +
+                  54334425968952. * A[6] - 22529574889533. * A[5] - 5132942328000. * A[4] + 3438377465592. * A[3] +
+                  84287641248. * A[2] - 72493479440. * a - 807415936) +
+             13824 * B[5] *
+                 (156356794976. * A[11] + 1180898077328. * A[10] - 90615270907936. * A[9] + 609258947056248. * A[8] -
+                  1312655191366722. * A[7] + 885900509321745. * A[6] + 112162151855265. * A[5] -
+                  212803071513258. * A[4] + 6805217831352. * A[3] + 10051742651296. * A[2] - 55035924848. * a -
+                  52946379296.) -
+             576 * B[4] *
+                 (143943926464. * A[12] - 60115486481856. * A[11] - 376366989757200. * A[10] +
+                  9534223075576160. * A[9] - 35603777465262396. * A[8] + 39375990156664980. * A[7] -
+                  868175004137259. * A[6] - 14279180718355020. * A[5] + 1985747535239364. * A[4] +
+                  1264001337603680. * A[3] - 75972792514320. * A[2] - 23855850572736. * a - 4996648256.) -
+             384 * B[3] *
+                 (2038525473856. * A[13] + 16057322146112. * A[12] - 502133360559024. * A[11] -
+                  2985686417468080. * A[10] + 32418922182093292. * A[9] - 63665380623022452. * A[8] +
+                  16481208821092575. * A[7] + 34161547357596099. * A[6] - 11490298497454932. * A[5] -
+                  5117272758337156. * A[4] + 933703210750480. * A[3] + 234855186762000. * A[2] - 7860524600000. * a -
+                  1226607567040.) +
+             96 * B[2] *
+                 (324439754752. * A[14] - 77231415197120. * A[13] - 539102931841856. * A[12] +
+                  4618258299956336. * A[11] + 28588485529469792. * A[10] - 141383982651179428. * A[9] +
+                  98783147840417772. * A[8] + 112831723492305801. * A[7] - 83329761150975036. * A[6] -
+                  26553582937192900. * A[5] + 12469117738765952. * A[4] + 2587165396642160. * A[3] -
+                  340406368038080. * A[2] - 53659641606080. * a + 219671272960.) +
+             96 * b * Ap1[1] *
+                 (1026630779520. * A[14] + 8781958472768. * A[13] - 210659786204384. * A[12] -
+                  1222283505284208. * A[11] + 5064251967491416. * A[10] + 24013052207628140. * A[9] -
+                  79710880160087370. * A[8] + 42596558293213227. * A[7] + 26570293386695790. * A[6] -
+                  14407831324576884. * A[5] - 3617322833922440. * A[4] + 950664948554384. * A[3] +
+                  172358006894496. * A[2] - 7430887938496. * a - 889746675584.) -
+             (a + 2) * (2 * a + 1) *
+                 (573840801152. * A[14] - 156998277198784. * A[13] - 898376974770592. * A[12] +
+                  8622589006459984. * A[11] + 32874204024803560. * A[10] - 111492707520083828. * A[9] -
+                  184768503480287646. * A[8] + 528612016938984183. * A[7] - 184768503480287646. * A[6] -
+                  111492707520083828. * A[5] + 32874204024803560. * A[4] + 8622589006459984. * A[3] -
+                  898376974770592. * A[2] - 156998277198784. * a + 573840801152.));
+
+        double Z = std::pow(a * x, 1 / Ap1[1]);
+        double Zp = 1.;
+        double res = C[0];
+        for (int k = 1; k < 9; k++) {
+            Zp /= Z;
+            res += (k % 2 == 0 ? 1 : -1) * C[k] * Zp;
+        }
+        if (!log_wb) {
+            res *= std::pow(Z, 0.5 - b) * std::exp(Ap1[1] / a * Z);
+        } else {
+            // logarithm of Wright's function
+            res = std::log(Z) * (0.5 - b) + Ap1[1] / a * Z + std::log(res);
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline double wb_Kmod(double exp_term, double eps, double a, double b, double x, double r) {
+        /* Compute integrand Kmod(eps, a, b, x, r) for Gauss-Laguerre quadrature.
+         *
+         * K(a, b, x, r+eps) = exp(-r-eps) * Kmod(eps, a, b, x, r)
+         * 
+         * Kmod(eps, a, b, x, r) = exp(x * (r+eps)^(-a) * cos(pi*a)) * (r+eps)^(-b)
+         *                       * sin(x * (r+eps)^(-a) * sin(pi*a) + pi * b)
+         * 
+         * Note that we additionally factor out exp(exp_term) which helps with large
+         * terms in the exponent of exp(...)
+         */
+        double x_r_a = x * std::pow(r + eps, -a);
+        return std::exp(x_r_a * cephes::cospi(a) + exp_term) * std::pow(r + eps, -b) *
+               std::sin(x_r_a * cephes::sinpi(a) + M_PI * b);
+    }
+
+    XSF_HOST_DEVICE inline double wb_P(double exp_term, double eps, double a, double b, double x, double phi) {
+        /* Compute integrand P for Gauss-Legendre quadrature.
+         *
+         * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi))
+         *                      * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi)
+         *                            + (1-b)*phi)
+         * 
+         * Note that we additionally factor out exp(exp_term) which helps with large
+         * terms in the exponent of exp(...)
+         */
+        double x_eps_a = x * std::pow(eps, -a);
+        return std::exp(eps * std::cos(phi) + x_eps_a * std::cos(a * phi) + exp_term) *
+               std::cos(eps * std::sin(phi) - x_eps_a * std::sin(a * phi) + (1 - b) * phi);
+    }
+
+    /* roots of laguerre polynomial of order 50
+     * scipy.special.roots_laguerre(50)[0] or
+     * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[0] */
+    constexpr double wb_x_laguerre[] = {
+        0.02863051833937908, 0.1508829356769337, 0.3709487815348964, 0.6890906998810479, 1.105625023539913,
+        1.620961751102501,   2.23561037591518,   2.950183366641835,  3.765399774405782,  4.682089387559285,
+        5.70119757478489,    6.823790909794551,  8.051063669390792,  9.384345308258407,  10.82510903154915,
+        12.37498160875746,   14.03575459982991,  15.80939719784467,  17.69807093335025,  19.70414653546156,
+        21.83022330657825,   24.0791514444115,   26.45405784125298,  28.95837601193738,  31.59588095662286,
+        34.37072996309045,   37.28751061055049,  40.35129757358607,  43.56772026999502,  46.94304399160304,
+        50.48426796312992,   54.19924488016862,  58.09682801724853,  62.18705417568891,  66.48137387844482,
+        70.99294482661949,   75.73701154772731,  80.73140480247769,  85.99721113646323,  91.55969041253388,
+        97.44956561485056,   103.7048912366923,  110.3738588076403,  117.5191982031112,  125.2254701334734,
+        133.6120279227287,   142.8583254892541,  153.2603719726036,  165.3856433166825,  180.6983437092145
+    };
+    /* weights for laguerre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[1] */
+    constexpr double wb_w_laguerre[] = {
+        0.07140472613518988,   0.1471486069645884,    0.1856716275748313,    0.1843853825273539,
+        0.1542011686063556,    0.1116853699022688,    0.07105288549019586,   0.04002027691150833,
+        0.02005062308007171,   0.008960851203646281,  0.00357811241531566,   0.00127761715678905,
+        0.0004080302449837189, 0.0001165288322309724, 2.974170493694165e-5,  6.777842526542028e-6,
+        1.37747950317136e-6,   2.492886181720092e-7,  4.010354350427827e-8,  5.723331748141425e-9,
+        7.229434249182665e-10, 8.061710142281779e-11, 7.913393099943723e-12, 6.81573661767678e-13,
+        5.13242671658949e-14,  3.365624762437814e-15, 1.913476326965035e-16, 9.385589781827253e-18,
+        3.950069964503411e-19, 1.417749517827512e-20, 4.309970276292175e-22, 1.101257519845548e-23,
+        2.344617755608987e-25, 4.11854415463823e-27,  5.902246763596448e-29, 6.812008916553065e-31,
+        6.237449498812102e-33, 4.452440579683377e-35, 2.426862352250487e-37, 9.852971481049686e-40,
+        2.891078872318428e-42, 5.906162708112361e-45, 8.01287459750397e-48,  6.789575424396417e-51,
+        3.308173010849252e-54, 8.250964876440456e-58, 8.848728128298018e-62, 3.064894889844417e-66,
+        1.988708229330752e-71, 6.049567152238783e-78
+    };
+    /* roots of legendre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_legendre(50, 16)[0] */
+    constexpr double wb_x_legendre[] = {
+        -0.998866404420071,  -0.9940319694320907, -0.9853540840480059, -0.9728643851066921,  -0.9566109552428079,
+        -0.9366566189448779, -0.9130785566557919, -0.885967979523613,  -0.8554297694299461,  -0.8215820708593359,
+        -0.7845558329003993, -0.7444943022260685, -0.7015524687068223, -0.6558964656854394,  -0.6077029271849502,
+        -0.5571583045146501, -0.5044581449074642, -0.4498063349740388, -0.3934143118975651,  -0.3355002454194374,
+        -0.276288193779532,  -0.2160072368760418, -0.1548905899981459, -0.09317470156008614, -0.03109833832718888,
+        0.03109833832718888, 0.09317470156008614, 0.1548905899981459,  0.2160072368760418,   0.276288193779532,
+        0.3355002454194374,  0.3934143118975651,  0.4498063349740388,  0.5044581449074642,   0.5571583045146501,
+        0.6077029271849502,  0.6558964656854394,  0.7015524687068223,  0.7444943022260685,   0.7845558329003993,
+        0.8215820708593359,  0.8554297694299461,  0.885967979523613,   0.9130785566557919,   0.9366566189448779,
+        0.9566109552428079,  0.9728643851066921,  0.9853540840480059,  0.9940319694320907,   0.998866404420071
+    };
+    /* weights for legendre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_legendre(50, 16)[1] */
+    constexpr double wb_w_legendre[] = {
+        0.002908622553155141, 0.006759799195745401, 0.01059054838365097, 0.01438082276148557,  0.01811556071348939,
+        0.02178024317012479,  0.02536067357001239,  0.0288429935805352,  0.03221372822357802,  0.03545983561514615,
+        0.03856875661258768,  0.0415284630901477,   0.04432750433880328, 0.04695505130394843,  0.04940093844946632,
+        0.05165570306958114,  0.05371062188899625,  0.05555774480621252, 0.05718992564772838,  0.05860084981322245,
+        0.05978505870426546,  0.06073797084177022,  0.06145589959031666, 0.06193606742068324,  0.06217661665534726,
+        0.06217661665534726,  0.06193606742068324,  0.06145589959031666, 0.06073797084177022,  0.05978505870426546,
+        0.05860084981322245,  0.05718992564772838,  0.05555774480621252, 0.05371062188899625,  0.05165570306958114,
+        0.04940093844946632,  0.04695505130394843,  0.04432750433880328, 0.0415284630901477,   0.03856875661258768,
+        0.03545983561514615,  0.03221372822357802,  0.0288429935805352,  0.02536067357001239,  0.02178024317012479,
+        0.01811556071348939,  0.01438082276148557,  0.01059054838365097, 0.006759799195745401, 0.002908622553155141
+    };
+    /* Fitted parameters for optimal choice of eps
+     * Call: python _precompute/wright_bessel.py 4 */
+    constexpr double wb_A[] = {0.41037, 0.30833, 6.9952, 18.382, -2.8566, 2.1122};
+
+    template
+    XSF_HOST_DEVICE inline double wright_bessel_integral(double a, double b, double x) {
+        /* 5. Integral representation
+         *
+         * K(a, b, x, r) = exp(-r + x * r^(-a) * cos(pi*a)) * r^(-b)
+         *               * sin(x * r^(-a) * sin(pi*a) + pi * b)
+         * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi))
+         *                      * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi)
+         *                        + (1-b)*phi)
+         *
+         * Phi(a, b, x) = 1/pi * int_eps^inf K(a, b, x, r) * dr
+         *              + eps^(1-b)/pi * int_0^pi P(eps, a, b, x, phi) * dphi
+         *
+         * for any eps > 0.
+         *
+         * Note that P has a misprint in Luchko (2008) Eq. 9, the cos(phi(beta-1)) at
+         * the end of the first line should be removed and the −sin(phi(beta−1)) at
+         * the end of the second line should read +(1-b)*phi.
+         * This integral representation introduced the free parameter eps (from the
+         * radius of complex contour integration). We try to choose eps such that
+         * the integrand behaves smoothly. Note that this is quite diffrent from how
+         * Luchko (2008) deals with eps: he is either looking for the limit eps -> 0
+         * or he sets (silently) eps=1. But having the freedom to set eps is much more
+         * powerful for numerical evaluation.
+         *
+         * As K has a leading exp(-r), we factor this out and apply Gauss-Laguerre
+         * quadrature rule:
+         *
+         * int_0^inf K(a, b, x, r+eps) dr = exp(-eps) int_0^inf exp(-r) Kmod(.., r) dr
+         *
+         * Note the shift r -> r+eps to have integation from 0 to infinity.
+         * The integral over P is done via a Gauss-Legendre quadrature rule.
+         *
+         * Note: Hardest argument range is large z, large b and small eps.
+         */
+
+        /* We use the free choice of eps to make the integral better behaved.
+         * 1. Concern is oscillatory behaviour of P. Therefore, we'd like to
+         *    make the change in the argument of cosine small, i.e. make arc length
+         *    int_0^phi sqrt(1 + f'(phi)^2) dphi small, with
+         *    f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a*phi) + (1-b)*phi
+         *    Proxy, make |f'(phi)| small.
+         * 2. Concern is int_0 K ~ int_0 (r+eps)^(-b) .. dr
+         *    This is difficult as r -> 0  for large b. It behaves better for larger
+         *    values of eps.
+         */
+
+        // Minimize oscillatory behavoir of P
+        double eps =
+            (wb_A[0] * b * std::exp(-0.5 * a) +
+             std::exp(
+                 wb_A[1] + 1 / (1 + a) * std::log(x) - wb_A[2] * std::exp(-wb_A[3] * a) +
+                 wb_A[4] / (1 + std::exp(wb_A[5] * a))
+             ));
+
+        if (a >= 4 && x >= 100) {
+            eps += 1; // This part is hard to fit
+        }
+
+        // Large b
+        if (b >= 8) {
+            /* Make P small compared to K by setting eps large enough.
+             * int K ~ exp(-eps) and int P ~ eps^(1-b) */
+            eps = std::fmax(eps, std::pow(b, -b / (1. - b)) + 0.1 * b);
+        }
+
+        // safeguard, higher better for larger a, lower better for tiny a.
+        eps = std::fmin(eps, 150.);
+        eps = std::fmax(eps, 3.); // 3 seems to be a pretty good choice in general.
+
+        // We factor out exp(-exp_term) from wb_Kmod and wb_P to avoid overflow of
+        // exp(..).
+        double exp_term = 0;
+        // From the exponent of K:
+        double r = wb_x_laguerre[50-1];  // largest value of x used in wb_Kmod
+        double x_r_a = x * std::pow(r + eps, -a);
+        exp_term = std::fmax(exp_term, x_r_a * cephes::cospi(a));
+        // From the exponent of P:
+        double x_eps_a = x * std::pow(eps, -a);
+        // phi = 0  =>  cos(phi) = cos(a * phi) = 1
+        exp_term = std::fmax(exp_term, eps + x_eps_a);
+        // phi = pi  => cos(phi) = -1
+        exp_term = std::fmax(exp_term, -eps + x_eps_a * cephes::cospi(a));
+
+        double res1 = 0;
+        double res2 = 0;
+
+        double y;
+        for (int k = 0; k < 50; k++) {
+            res1 += wb_w_laguerre[k] * wb_Kmod(-exp_term, eps, a, b, x, wb_x_laguerre[k]);
+            // y = (b-a)*(x+1)/2.0 + a  for integration from a=0 to b=pi
+            y = M_PI * (wb_x_legendre[k] + 1) / 2.0;
+            res2 += wb_w_legendre[k] * wb_P(-exp_term, eps, a, b, x, y);
+        }
+        res1 *= std::exp(-eps);
+        // (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1)
+        res2 *= M_PI / 2.0;
+        res2 *= std::pow(eps, 1 - b);
+
+        if (!log_wb) {
+            // Remember the factored out exp_term from wb_Kmod and wb_P
+            return std::exp(exp_term) / M_PI * (res1 + res2);
+        } else {
+            // logarithm of Wright's function
+            return exp_term + std::log((res1 + res2) / M_PI);
+        }
+    }
+} // namespace detail
+
+template
+XSF_HOST_DEVICE inline double wright_bessel_t(double a, double b, double x) {
+    /* Compute Wright's generalized Bessel function for scalar arguments.
+     *
+     * According to [1], it is an entire function defined as
+     *
+     * .. math:: \Phi(a, b; x) = \sum_{k=0}^\infty \frac{x^k}{k! \Gamma(a k + b)}
+     *
+     * So far, only non-negative values of rho=a, beta=b and z=x are implemented.
+     * There are 5 different approaches depending on the ranges of the arguments:
+     *
+     * 1. Taylor series expansion in x=0 [1], for x <= 1.
+     *    Involves gamma funtions in each term.
+     * 2. Taylor series expansion in x=0 [2], for large a.
+     * 3. Taylor series in a=0, for tiny a and not too large x.
+     * 4. Asymptotic expansion for large x [3, 4].
+     *    Suitable for large x while still small a and b.
+     * 5. Integral representation [5], in principle for all arguments.
+     *
+     * References
+     * ----------
+     * [1] https://dlmf.nist.gov/10.46.E1
+     * [2] P. K. Dunn, G. K. Smyth (2005), Series evaluation of Tweedie exponential
+     *     dispersion model densities. Statistics and Computing 15 (2005): 267-280.
+     * [3] E. M. Wright (1935), The asymptotic expansion of the generalized Bessel
+     *     function. Proc. London Math. Soc. (2) 38, pp. 257-270.
+     *     https://doi.org/10.1112/plms/s2-38.1.257
+     * [4] R. B. Paris (2017), The asymptotics of the generalised Bessel function,
+     *     Mathematica Aeterna, Vol. 7, 2017, no. 4, 381 - 406,
+     *     https://arxiv.org/abs/1711.03006
+     * [5] Y. F. Luchko (2008), Algorithms for Evaluation of the Wright Function for
+     *     the Real Arguments' Values, Fractional Calculus and Applied Analysis 11(1)
+     *     http://sci-gems.math.bas.bg/jspui/bitstream/10525/1298/1/fcaa-vol11-num1-2008-57p-75p.pdf
+     */
+    if (std::isnan(a) || std::isnan(b) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (a < 0 || b < 0 || x < 0) {
+        set_error("wright_bessel", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(x)) {
+        if (std::isinf(a) || std::isinf(b)) {
+            return std::numeric_limits::quiet_NaN();
+        }
+        return std::numeric_limits::infinity();
+    }
+    if (std::isinf(a) || std::isinf(b)) {
+        return std::numeric_limits::quiet_NaN(); // or 0
+    }
+    if (a >= detail::rgamma_zero || b >= detail::rgamma_zero) {
+        set_error("wright_bessel", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0) {
+        // return rgamma(b)
+        if (!log_wb) {
+            return cephes::rgamma(b);
+        } else {
+            // logarithm of Wright's function
+            return -cephes::lgam(b);
+        }
+    }
+    if (a == 0) {
+        // return exp(x) * rgamma(b)
+        if (!log_wb) {
+            return detail::exp_rgamma(x, b);
+        } else {
+            // logarithm of Wright's function
+            return x - cephes::lgam(b);
+        }
+    }
+
+    constexpr double exp_inf = 709.78271289338403;
+    int order;
+    if ((a <= 1e-3 && b <= 50 && x <= 9) || (a <= 1e-4 && b <= 70 && x <= 100) ||
+        (a <= 1e-5 && b <= 170 && (x < exp_inf || (log_wb && x <= 1e3)))) {
+        /* Taylor Series expansion in a=0 to order=order => precision <= 1e-11
+         * If beta is also small => precision <= 1e-11.
+         * max order = 5 */
+        if (a <= 1e-5) {
+            if (x <= 1) {
+                order = 2;
+            } else if (x <= 10) {
+                order = 3;
+            } else if (x <= 100) {
+                order = 4;
+            } else { // x < exp_inf
+                order = 5;
+            }
+        } else if (a <= 1e-4) {
+            if (x <= 1e-2) {
+                order = 2;
+            } else if (x <= 1) {
+                order = 3;
+            } else if (x <= 10) {
+                order = 4;
+            } else { // x <= 100
+                order = 5;
+            }
+        } else { // a <= 1e-3
+            if (x <= 1e-5) {
+                order = 2;
+            } else if (x <= 1e-1) {
+                order = 3;
+            } else if (x <= 1) {
+                order = 4;
+            } else { // x <= 9
+                order = 5;
+            }
+        }
+
+        return detail::wb_small_a(a, b, x, order);
+    }
+
+    if (x <= 1) {
+        // 18 term Taylor Series => error mostly smaller 5e-14
+        double res = detail::wb_series(a, b, x, 0, 18);
+        if (log_wb) res = std::log(res);
+        return res;
+    }
+    if (x <= 2) {
+        // 20 term Taylor Series => error mostly smaller 1e-12 to 1e-13
+        double res = detail::wb_series(a, b, x, 0, 20);
+        if (log_wb) res = std::log(res);
+        return res;
+    }
+    if (a >= 5) {
+        /* Taylor series around the approximate maximum term.
+         * Set number of terms=order. */
+        if (a >= 10) {
+            if (x <= 1e11) {
+                order = 6;
+            } else {
+                order = static_cast(std::fmin(std::log10(x) - 5 + b / 10, 30));
+            }
+        } else {
+            if (x <= 1e4) {
+                order = 6;
+            } else if (x <= 1e8) {
+                order = static_cast(2 * std::log10(x));
+            } else if (x <= 1e10) {
+                order = static_cast(4 * std::log10(x) - 16);
+            } else {
+                order = static_cast(std::fmin(6 * std::log10(x) - 36, 100));
+            }
+        }
+        return detail::wb_large_a(a, b, x, order);
+    }
+    if (std::pow(a * x, 1 / (1. + a)) >= 14 + b * b / (2 * (1 + a))) {
+        /* Asymptotic expansion in Z = (a*x)^(1/(1+a)) up to 8th term 1/Z^8.
+         * For 1/Z^k, the highest term in b is b^(2*k) * a0 / (2^k k! (1+a)^k).
+         * As a0 is a common factor to all orders, this explains a bit the
+         * domain of good convergence set above.
+         * => precision ~ 1e-11 but can go down to ~1e-8 or 1e-7
+         * Note: We ensured a <= 5 as this is a bad approximation for large a. */
+        return detail::wb_asymptotic(a, b, x);
+    }
+    if (0.5 <= a && a <= 1.8 && 100 <= b && 1e5 <= x) {
+        // This is a very hard domain. This condition is placed after wb_asymptotic.
+        // TODO: Explore ways to cover this domain.
+        return std::numeric_limits::quiet_NaN();
+    }
+    return detail::wright_bessel_integral(a, b, x);
+}
+
+
+XSF_HOST_DEVICE inline double wright_bessel(double a, double b, double x) {
+    return wright_bessel_t(a, b, x);
+}
+
+XSF_HOST_DEVICE inline float wright_bessel(float a, float b, float x) {
+    return wright_bessel(static_cast(a), static_cast(b), static_cast(x));
+}
+
+XSF_HOST_DEVICE inline double log_wright_bessel(double a, double b, double x) {
+    return wright_bessel_t(a, b, x);
+}
+
+XSF_HOST_DEVICE inline float log_wright_bessel(float a, float b, float x) {
+    return log_wright_bessel(static_cast(a), static_cast(b), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h
new file mode 100644
index 0000000000000000000000000000000000000000..64e83ca390a094b85380ff69c24ba2cdead33d7f
--- /dev/null
+++ b/Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h
@@ -0,0 +1,35 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+#pragma once
+
+#include "config.h"
+
+namespace xsf {
+namespace detail {
+
+    XSF_HOST_DEVICE inline std::complex zlog1(std::complex z) {
+        /* Compute log, paying special attention to accuracy around 1. We
+         * implement this ourselves because some systems (most notably the
+         * Travis CI machines) are weak in this regime. */
+        std::complex coeff = -1.0;
+        std::complex res = 0.0;
+
+        if (std::abs(z - 1.0) > 0.1) {
+            return std::log(z);
+        }
+
+        z -= 1.0;
+        for (int n = 1; n < 17; n++) {
+            coeff *= -z;
+            res += coeff / static_cast(n);
+            if (std::abs(res / coeff) < std::numeric_limits::epsilon()) {
+                break;
+            }
+        }
+        return res;
+    }
+} // namespace detail
+} // namespace xsf